text
stringlengths
517
228k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: parse_wcc_attr(netdissect_options *ndo, const uint32_t *dp) { ND_PRINT((ndo, " sz %" PRIu64, EXTRACT_64BITS(&dp[0]))); ND_PRINT((ndo, " mtime %u.%06u ctime %u.%06u", EXTRACT_32BITS(&dp[2]), EXTRACT_32BITS(&dp[3]), EXTRACT_32BITS(&dp[4]), EXTRACT_32BITS(&dp[5]))); return (dp + 6); } ; 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: grantpt (int fd) { int retval = -1; #ifdef PATH_MAX char _buf[PATH_MAX]; #else char _buf[512]; #endif char *buf = _buf; struct stat64 st; if (__builtin_expect (pts_name (fd, &buf, sizeof (_buf), &st), 0)) { int save_errno = errno; /* Check, if the file descriptor is valid. pts_name returns the wrong errno number, so we cannot use that. */ if (__libc_fcntl (fd, F_GETFD) == -1 && errno == EBADF) return -1; /* If the filedescriptor is no TTY, grantpt has to set errno to EINVAL. */ if (save_errno == ENOTTY) __set_errno (EINVAL); else __set_errno (save_errno); return -1; } /* Make sure that we own the device. */ uid_t uid = __getuid (); if (st.st_uid != uid) { if (__chown (buf, uid, st.st_gid) < 0) goto helper; } static int tty_gid = -1; if (__builtin_expect (tty_gid == -1, 0)) { char *grtmpbuf; struct group grbuf; size_t grbuflen = __sysconf (_SC_GETGR_R_SIZE_MAX); struct group *p; /* Get the group ID of the special `tty' group. */ if (grbuflen == (size_t) -1L) /* `sysconf' does not support _SC_GETGR_R_SIZE_MAX. Try a moderate value. */ grbuflen = 1024; grtmpbuf = (char *) __alloca (grbuflen); __getgrnam_r (TTY_GROUP, &grbuf, grtmpbuf, grbuflen, &p); if (p != NULL) tty_gid = p->gr_gid; } gid_t gid = tty_gid == -1 ? __getgid () : tty_gid; /* Make sure the group of the device is that special group. */ if (st.st_gid != gid) { if (__chown (buf, uid, gid) < 0) goto helper; } /* Make sure the permission mode is set to readable and writable by the owner, and writable by the group. */ if ((st.st_mode & ACCESSPERMS) != (S_IRUSR|S_IWUSR|S_IWGRP)) { if (__chmod (buf, S_IRUSR|S_IWUSR|S_IWGRP) < 0) goto helper; } retval = 0; goto cleanup; /* We have to use the helper program. */ helper:; pid_t pid = __fork (); if (pid == -1) goto cleanup; else if (pid == 0) { /* Disable core dumps. */ struct rlimit rl = { 0, 0 }; __setrlimit (RLIMIT_CORE, &rl); /* We pass the master pseudo terminal as file descriptor PTY_FILENO. */ if (fd != PTY_FILENO) if (__dup2 (fd, PTY_FILENO) < 0) _exit (FAIL_EBADF); #ifdef CLOSE_ALL_FDS CLOSE_ALL_FDS (); #endif execle (_PATH_PT_CHOWN, basename (_PATH_PT_CHOWN), NULL, NULL); _exit (FAIL_EXEC); } else { int w; if (__waitpid (pid, &w, 0) == -1) goto cleanup; if (!WIFEXITED (w)) __set_errno (ENOEXEC); else switch (WEXITSTATUS (w)) { case 0: retval = 0; break; case FAIL_EBADF: __set_errno (EBADF); break; case FAIL_EINVAL: __set_errno (EINVAL); break; case FAIL_EACCES: __set_errno (EACCES); break; case FAIL_EXEC: __set_errno (ENOEXEC); break; case FAIL_ENOMEM: __set_errno (ENOMEM); break; default: assert(! "getpt: internal error: invalid exit code from pt_chown"); } } cleanup: if (buf != _buf) free (buf); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'CVE-2013-2207, BZ #15755: Disable pt_chown. The helper binary pt_chown tricked into granting access to another user's pseudo-terminal. Pre-conditions for the attack: * Attacker with local user account * Kernel with FUSE support * "user_allow_other" in /etc/fuse.conf * Victim with allocated slave in /dev/pts Using the setuid installed pt_chown and a weak check on whether a file descriptor is a tty, an attacker could fake a pty check using FUSE and trick pt_chown to grant ownership of a pty descriptor that the current user does not own. It cannot access /dev/pts/ptmx however. In most modern distributions pt_chown is not needed because devpts is enabled by default. The fix for this CVE is to disable building and using pt_chown by default. We still provide a configure option to enable hte use of pt_chown but distributions do so at their own risk.'</s>
<s>[INST] Given the following code containing errors, provide 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 derive_boundaryStrength(de265_image* img, bool vertical, int yStart,int yEnd, int xStart,int xEnd) { int xIncr = vertical ? 2 : 1; int yIncr = vertical ? 1 : 2; int xOffs = vertical ? 1 : 0; int yOffs = vertical ? 0 : 1; int edgeMask = vertical ? (DEBLOCK_FLAG_VERTI | DEBLOCK_PB_EDGE_VERTI) : (DEBLOCK_FLAG_HORIZ | DEBLOCK_PB_EDGE_HORIZ); int transformEdgeMask = vertical ? DEBLOCK_FLAG_VERTI : DEBLOCK_FLAG_HORIZ; xEnd = libde265_min(xEnd,img->get_deblk_width()); yEnd = libde265_min(yEnd,img->get_deblk_height()); int TUShift = img->get_sps().Log2MinTrafoSize; int TUStride= img->get_sps().PicWidthInTbsY; for (int y=yStart;y<yEnd;y+=yIncr) for (int x=xStart;x<xEnd;x+=xIncr) { int xDi = x<<2; int yDi = y<<2; logtrace(LogDeblock,"%d %d %s = %s\n",xDi,yDi, vertical?"Vertical":"Horizontal", (img->get_deblk_flags(xDi,yDi) & edgeMask) ? "edge" : "..."); uint8_t edgeFlags = img->get_deblk_flags(xDi,yDi); if (edgeFlags & edgeMask) { bool p_is_intra_pred = (img->get_pred_mode(xDi-xOffs, yDi-yOffs) == MODE_INTRA); bool q_is_intra_pred = (img->get_pred_mode(xDi, yDi ) == MODE_INTRA); int bS; if (p_is_intra_pred || q_is_intra_pred) { bS = 2; } else { // opposing site int xDiOpp = xDi-xOffs; int yDiOpp = yDi-yOffs; if ((edgeFlags & transformEdgeMask) && (img->get_nonzero_coefficient(xDi ,yDi) || img->get_nonzero_coefficient(xDiOpp,yDiOpp))) { bS = 1; } else { bS = 0; const PBMotion& mviP = img->get_mv_info(xDiOpp,yDiOpp); const PBMotion& mviQ = img->get_mv_info(xDi ,yDi); slice_segment_header* shdrP = img->get_SliceHeader(xDiOpp,yDiOpp); slice_segment_header* shdrQ = img->get_SliceHeader(xDi ,yDi); int refPicP0 = mviP.predFlag[0] ? shdrP->RefPicList[0][ mviP.refIdx[0] ] : -1; int refPicP1 = mviP.predFlag[1] ? shdrP->RefPicList[1][ mviP.refIdx[1] ] : -1; int refPicQ0 = mviQ.predFlag[0] ? shdrQ->RefPicList[0][ mviQ.refIdx[0] ] : -1; int refPicQ1 = mviQ.predFlag[1] ? shdrQ->RefPicList[1][ mviQ.refIdx[1] ] : -1; bool samePics = ((refPicP0==refPicQ0 && refPicP1==refPicQ1) || (refPicP0==refPicQ1 && refPicP1==refPicQ0)); if (!samePics) { bS = 1; } else { MotionVector mvP0 = mviP.mv[0]; if (!mviP.predFlag[0]) { mvP0.x=mvP0.y=0; } MotionVector mvP1 = mviP.mv[1]; if (!mviP.predFlag[1]) { mvP1.x=mvP1.y=0; } MotionVector mvQ0 = mviQ.mv[0]; if (!mviQ.predFlag[0]) { mvQ0.x=mvQ0.y=0; } MotionVector mvQ1 = mviQ.mv[1]; if (!mviQ.predFlag[1]) { mvQ1.x=mvQ1.y=0; } int numMV_P = mviP.predFlag[0] + mviP.predFlag[1]; int numMV_Q = mviQ.predFlag[0] + mviQ.predFlag[1]; if (numMV_P!=numMV_Q) { img->decctx->add_warning(DE265_WARNING_NUMMVP_NOT_EQUAL_TO_NUMMVQ, false); img->integrity = INTEGRITY_DECODING_ERRORS; } // two different reference pictures or only one reference picture if (refPicP0 != refPicP1) { if (refPicP0 == refPicQ0) { if (abs_value(mvP0.x-mvQ0.x) >= 4 || abs_value(mvP0.y-mvQ0.y) >= 4 || abs_value(mvP1.x-mvQ1.x) >= 4 || abs_value(mvP1.y-mvQ1.y) >= 4) { bS = 1; } } else { if (abs_value(mvP0.x-mvQ1.x) >= 4 || abs_value(mvP0.y-mvQ1.y) >= 4 || abs_value(mvP1.x-mvQ0.x) >= 4 || abs_value(mvP1.y-mvQ0.y) >= 4) { bS = 1; } } } else { assert(refPicQ0==refPicQ1); if ((abs_value(mvP0.x-mvQ0.x) >= 4 || abs_value(mvP0.y-mvQ0.y) >= 4 || abs_value(mvP1.x-mvQ1.x) >= 4 || abs_value(mvP1.y-mvQ1.y) >= 4) && (abs_value(mvP0.x-mvQ1.x) >= 4 || abs_value(mvP0.y-mvQ1.y) >= 4 || abs_value(mvP1.x-mvQ0.x) >= 4 || abs_value(mvP1.y-mvQ0.y) >= 4)) { bS = 1; } } } /* printf("unimplemented deblocking code for CU at %d;%d\n",xDi,yDi); logerror(LogDeblock, "unimplemented code reached (file %s, line %d)\n", __FILE__, __LINE__); */ } } img->set_deblk_bS(xDi,yDi, bS); } else { img->set_deblk_bS(xDi,yDi, 0); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'fix reading invalid images where shdr references are NULL in part of the image (#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: RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix #7152 - Null deref in cms'</s>
<s>[INST] Given the following code containing errors, provide 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 samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr_name, const char *value) { struct ldb_message_element *el; struct ldb_val val, *vals; char *v; unsigned int i; bool found = false; int ret; v = talloc_strdup(mem_ctx, value); if (v == NULL) { return ldb_oom(sam_ldb); } val.data = (uint8_t *) v; val.length = strlen(v); if (val.length == 0) { /* allow empty strings as non-existent attributes */ return LDB_SUCCESS; } for (i = 0; i < msg->num_elements; i++) { el = &msg->elements[i]; if ((ldb_attr_cmp(el->name, attr_name) == 0) && (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) { found = true; break; } } if (!found) { ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE, &el); if (ret != LDB_SUCCESS) { return ret; } } vals = talloc_realloc(msg->elements, el->values, struct ldb_val, el->num_values + 1); if (vals == NULL) { return ldb_oom(sam_ldb); } el->values = vals; el->values[el->num_values] = val; ++(el->num_values); return LDB_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Ensure shallow copy modifications do not affect original message Using the newly added ldb flag, we can now detect when a message has been shallow-copied so that its elements share their values with the original message elements. Then when adding values to the copied message, we now make a copy of the shared values array first. This should prevent a use-after-free that occurred in LDB modules when new values were added to a shallow copy of a message by calling talloc_realloc() on the original values array, invalidating the 'values' pointer in the original message element. The original values pointer can later be used in the database audit logging module which logs database requests, and potentially cause a crash. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: DecodeIPV6ExtHdrs(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { SCEnter(); uint8_t *orig_pkt = pkt; uint8_t nh = 0; /* careful, 0 is actually a real type */ uint16_t hdrextlen = 0; uint16_t plen; char dstopts = 0; char exthdr_fh_done = 0; int hh = 0; int rh = 0; int eh = 0; int ah = 0; nh = IPV6_GET_NH(p); plen = len; while(1) { /* No upper layer, but we do have data. Suspicious. */ if (nh == IPPROTO_NONE && plen > 0) { ENGINE_SET_EVENT(p, IPV6_DATA_AFTER_NONE_HEADER); SCReturn; } if (plen < 2) { /* minimal needed in a hdr */ SCReturn; } switch(nh) { case IPPROTO_TCP: IPV6_SET_L4PROTO(p,nh); DecodeTCP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_UDP: IPV6_SET_L4PROTO(p,nh); DecodeUDP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ICMPV6: IPV6_SET_L4PROTO(p,nh); DecodeICMPV6(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_SCTP: IPV6_SET_L4PROTO(p,nh); DecodeSCTP(tv, dtv, p, pkt, plen, pq); SCReturn; case IPPROTO_ROUTING: IPV6_SET_L4PROTO(p,nh); hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (rh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_RH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } rh = 1; IPV6_EXTHDR_SET_RH(p); uint8_t ip6rh_type = *(pkt + 2); if (ip6rh_type == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_RH_TYPE_0); } p->ip6eh.rh_type = ip6rh_type; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; case IPPROTO_HOPOPTS: case IPPROTO_DSTOPTS: { IPV6OptHAO hao_s, *hao = &hao_s; IPV6OptRA ra_s, *ra = &ra_s; IPV6OptJumbo jumbo_s, *jumbo = &jumbo_s; uint16_t optslen = 0; IPV6_SET_L4PROTO(p,nh); hdrextlen = (*(pkt+1) + 1) << 3; if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } uint8_t *ptr = pkt + 2; /* +2 to go past nxthdr and len */ /* point the pointers to right structures * in Packet. */ if (nh == IPPROTO_HOPOPTS) { if (hh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_HH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } hh = 1; optslen = ((*(pkt + 1) + 1 ) << 3) - 2; } else if (nh == IPPROTO_DSTOPTS) { if (dstopts == 0) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 1; } else if (dstopts == 1) { optslen = ((*(pkt + 1) + 1 ) << 3) - 2; dstopts = 2; } else { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_DH); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } } if (optslen > plen) { /* since the packet is long enough (we checked * plen against hdrlen, the optlen must be malformed. */ ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); /* skip past this extension so we can continue parsing the rest * of the packet */ nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /** \todo move into own function to loaded on demand */ uint16_t padn_cnt = 0; uint16_t other_cnt = 0; uint16_t offset = 0; while(offset < optslen) { if (*ptr == IPV6OPT_PAD1) { padn_cnt++; offset++; ptr++; continue; } if (offset + 1 >= optslen) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } /* length field for each opt */ uint8_t ip6_optlen = *(ptr + 1); /* see if the optlen from the packet fits the total optslen */ if ((offset + 1 + ip6_optlen) > optslen) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } if (*ptr == IPV6OPT_PADN) /* PadN */ { //printf("PadN option\n"); padn_cnt++; /* a zero padN len would be weird */ if (ip6_optlen == 0) ENGINE_SET_EVENT(p, IPV6_EXTHDR_ZERO_LEN_PADN); } else if (*ptr == IPV6OPT_RA) /* RA */ { ra->ip6ra_type = *(ptr); ra->ip6ra_len = ip6_optlen; if (ip6_optlen < sizeof(ra->ip6ra_value)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&ra->ip6ra_value, (ptr + 2), sizeof(ra->ip6ra_value)); ra->ip6ra_value = SCNtohs(ra->ip6ra_value); //printf("RA option: type %" PRIu32 " len %" PRIu32 " value %" PRIu32 "\n", // ra->ip6ra_type, ra->ip6ra_len, ra->ip6ra_value); other_cnt++; } else if (*ptr == IPV6OPT_JUMBO) /* Jumbo */ { jumbo->ip6j_type = *(ptr); jumbo->ip6j_len = ip6_optlen; if (ip6_optlen < sizeof(jumbo->ip6j_payload_len)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&jumbo->ip6j_payload_len, (ptr+2), sizeof(jumbo->ip6j_payload_len)); jumbo->ip6j_payload_len = SCNtohl(jumbo->ip6j_payload_len); //printf("Jumbo option: type %" PRIu32 " len %" PRIu32 " payload len %" PRIu32 "\n", // jumbo->ip6j_type, jumbo->ip6j_len, jumbo->ip6j_payload_len); } else if (*ptr == IPV6OPT_HAO) /* HAO */ { hao->ip6hao_type = *(ptr); hao->ip6hao_len = ip6_optlen; if (ip6_optlen < sizeof(hao->ip6hao_hoa)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_INVALID_OPTLEN); break; } memcpy(&hao->ip6hao_hoa, (ptr+2), sizeof(hao->ip6hao_hoa)); //printf("HAO option: type %" PRIu32 " len %" PRIu32 " ", // hao->ip6hao_type, hao->ip6hao_len); //char addr_buf[46]; //PrintInet(AF_INET6, (char *)&(hao->ip6hao_hoa), // addr_buf,sizeof(addr_buf)); //printf("home addr %s\n", addr_buf); other_cnt++; } else { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_UNKNOWN_OPT); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_UNKNOWN_OPT); other_cnt++; } uint16_t optlen = (*(ptr + 1) + 2); ptr += optlen; /* +2 for opt type and opt len fields */ offset += optlen; } /* flag packets that have only padding */ if (padn_cnt > 0 && other_cnt == 0) { if (nh == IPPROTO_HOPOPTS) ENGINE_SET_EVENT(p, IPV6_HOPOPTS_ONLY_PADDING); else ENGINE_SET_EVENT(p, IPV6_DSTOPTS_ONLY_PADDING); } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_FRAGMENT: { IPV6_SET_L4PROTO(p,nh); /* store the offset of this extension into the packet * past the ipv6 header. We use it in defrag for creating * a defragmented packet without the frag header */ if (exthdr_fh_done == 0) { p->ip6eh.fh_offset = pkt - orig_pkt; exthdr_fh_done = 1; } uint16_t prev_hdrextlen = hdrextlen; hdrextlen = sizeof(IPV6FragHdr); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } /* for the frag header, the length field is reserved */ if (*(pkt + 1) != 0) { ENGINE_SET_EVENT(p, IPV6_FH_NON_ZERO_RES_FIELD); /* non fatal, lets try to continue */ } if (IPV6_EXTHDR_ISSET_FH(p)) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* set the header flag first */ IPV6_EXTHDR_SET_FH(p); /* parse the header and setup the vars */ DecodeIPV6FragHeader(p, pkt, hdrextlen, plen, prev_hdrextlen); /* if FH has offset 0 and no more fragments are coming, we * parse this packet further right away, no defrag will be * needed. It is a useless FH then though, so we do set an * decoder event. */ if (p->ip6eh.fh_more_frags_set == 0 && p->ip6eh.fh_offset == 0) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_USELESS_FH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } /* the rest is parsed upon reassembly */ p->flags |= PKT_IS_FRAGMENT; SCReturn; } case IPPROTO_ESP: { IPV6_SET_L4PROTO(p,nh); hdrextlen = sizeof(IPV6EspHdr); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } if (eh) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_EH); SCReturn; } eh = 1; nh = IPPROTO_NONE; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_AH: { IPV6_SET_L4PROTO(p,nh); /* we need the header as a minimum */ hdrextlen = sizeof(IPV6AuthHdr); /* the payload len field is the number of extra 4 byte fields, * IPV6AuthHdr already contains the first */ if (*(pkt+1) > 0) hdrextlen += ((*(pkt+1) - 1) * 4); SCLogDebug("hdrextlen %"PRIu8, hdrextlen); if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } IPV6AuthHdr *ahhdr = (IPV6AuthHdr *)pkt; if (ahhdr->ip6ah_reserved != 0x0000) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_AH_RES_NOT_NULL); } if (ah) { ENGINE_SET_EVENT(p, IPV6_EXTHDR_DUPL_AH); nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } ah = 1; nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; } case IPPROTO_IPIP: IPV6_SET_L4PROTO(p,nh); DecodeIPv4inIPv6(tv, dtv, p, pkt, plen, pq); SCReturn; /* none, last header */ case IPPROTO_NONE: IPV6_SET_L4PROTO(p,nh); SCReturn; case IPPROTO_ICMP: ENGINE_SET_EVENT(p,IPV6_WITH_ICMPV4); SCReturn; /* no parsing yet, just skip it */ case IPPROTO_MH: case IPPROTO_HIP: case IPPROTO_SHIM6: hdrextlen = 8 + (*(pkt+1) * 8); /* 8 bytes + length in 8 octet units */ if (hdrextlen > plen) { ENGINE_SET_EVENT(p, IPV6_TRUNC_EXTHDR); SCReturn; } nh = *pkt; pkt += hdrextlen; plen -= hdrextlen; break; default: ENGINE_SET_EVENT(p, IPV6_UNKNOWN_NEXT_HEADER); IPV6_SET_L4PROTO(p,nh); SCReturn; } } SCReturn; } ; 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: escape_xml(const char *text) { static char *escaped; static size_t escaped_size; char *out; size_t len; if (!strlen(text)) return "empty string"; for (out=escaped, len=0; *text; ++len, ++out, ++text) { /* Make sure there's plenty of room for a quoted character */ if ((len + 8) > escaped_size) { char *bigger_escaped; escaped_size += 128; bigger_escaped = realloc(escaped, escaped_size); if (!bigger_escaped) { free(escaped); /* avoid leaking memory */ escaped = NULL; escaped_size = 0; /* Error string is cleverly chosen to fail XML validation */ return ">>> out of memory <<<"; } out = bigger_escaped + len; escaped = bigger_escaped; } switch (*text) { case '&': strcpy(out, "&amp;"); len += strlen(out) - 1; out = escaped + len; break; case '<': strcpy(out, "&lt;"); len += strlen(out) - 1; out = escaped + len; break; case '>': strcpy(out, "&gt;"); len += strlen(out) - 1; out = escaped + len; break; default: *out = *text; break; } } *out = '\x0'; /* NUL terminate the string */ return escaped; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'actually return empty stringand not 'em,pty string' as expected'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int session_new(nghttp2_session **session_ptr, const nghttp2_session_callbacks *callbacks, void *user_data, int server, const nghttp2_option *option, nghttp2_mem *mem) { int rv; size_t nbuffer; size_t max_deflate_dynamic_table_size = NGHTTP2_HD_DEFAULT_MAX_DEFLATE_BUFFER_SIZE; if (mem == NULL) { mem = nghttp2_mem_default(); } *session_ptr = nghttp2_mem_calloc(mem, 1, sizeof(nghttp2_session)); if (*session_ptr == NULL) { rv = NGHTTP2_ERR_NOMEM; goto fail_session; } (*session_ptr)->mem = *mem; mem = &(*session_ptr)->mem; /* next_stream_id is initialized in either nghttp2_session_client_new2 or nghttp2_session_server_new2 */ nghttp2_stream_init(&(*session_ptr)->root, 0, NGHTTP2_STREAM_FLAG_NONE, NGHTTP2_STREAM_IDLE, NGHTTP2_DEFAULT_WEIGHT, 0, 0, NULL, mem); (*session_ptr)->remote_window_size = NGHTTP2_INITIAL_CONNECTION_WINDOW_SIZE; (*session_ptr)->recv_window_size = 0; (*session_ptr)->consumed_size = 0; (*session_ptr)->recv_reduction = 0; (*session_ptr)->local_window_size = NGHTTP2_INITIAL_CONNECTION_WINDOW_SIZE; (*session_ptr)->goaway_flags = NGHTTP2_GOAWAY_NONE; (*session_ptr)->local_last_stream_id = (1u << 31) - 1; (*session_ptr)->remote_last_stream_id = (1u << 31) - 1; (*session_ptr)->pending_local_max_concurrent_stream = NGHTTP2_DEFAULT_MAX_CONCURRENT_STREAMS; (*session_ptr)->pending_enable_push = 1; if (server) { (*session_ptr)->server = 1; } init_settings(&(*session_ptr)->remote_settings); init_settings(&(*session_ptr)->local_settings); (*session_ptr)->max_incoming_reserved_streams = NGHTTP2_MAX_INCOMING_RESERVED_STREAMS; /* Limit max outgoing concurrent streams to sensible value */ (*session_ptr)->remote_settings.max_concurrent_streams = 100; (*session_ptr)->max_send_header_block_length = NGHTTP2_MAX_HEADERSLEN; (*session_ptr)->max_outbound_ack = NGHTTP2_DEFAULT_MAX_OBQ_FLOOD_ITEM; if (option) { if ((option->opt_set_mask & NGHTTP2_OPT_NO_AUTO_WINDOW_UPDATE) && option->no_auto_window_update) { (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_AUTO_WINDOW_UPDATE; } if (option->opt_set_mask & NGHTTP2_OPT_PEER_MAX_CONCURRENT_STREAMS) { (*session_ptr)->remote_settings.max_concurrent_streams = option->peer_max_concurrent_streams; } if (option->opt_set_mask & NGHTTP2_OPT_MAX_RESERVED_REMOTE_STREAMS) { (*session_ptr)->max_incoming_reserved_streams = option->max_reserved_remote_streams; } if ((option->opt_set_mask & NGHTTP2_OPT_NO_RECV_CLIENT_MAGIC) && option->no_recv_client_magic) { (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_RECV_CLIENT_MAGIC; } if ((option->opt_set_mask & NGHTTP2_OPT_NO_HTTP_MESSAGING) && option->no_http_messaging) { (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_HTTP_MESSAGING; } if (option->opt_set_mask & NGHTTP2_OPT_USER_RECV_EXT_TYPES) { memcpy((*session_ptr)->user_recv_ext_types, option->user_recv_ext_types, sizeof((*session_ptr)->user_recv_ext_types)); } if (option->opt_set_mask & NGHTTP2_OPT_BUILTIN_RECV_EXT_TYPES) { (*session_ptr)->builtin_recv_ext_types = option->builtin_recv_ext_types; } if ((option->opt_set_mask & NGHTTP2_OPT_NO_AUTO_PING_ACK) && option->no_auto_ping_ack) { (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_AUTO_PING_ACK; } if (option->opt_set_mask & NGHTTP2_OPT_MAX_SEND_HEADER_BLOCK_LENGTH) { (*session_ptr)->max_send_header_block_length = option->max_send_header_block_length; } if (option->opt_set_mask & NGHTTP2_OPT_MAX_DEFLATE_DYNAMIC_TABLE_SIZE) { max_deflate_dynamic_table_size = option->max_deflate_dynamic_table_size; } if ((option->opt_set_mask & NGHTTP2_OPT_NO_CLOSED_STREAMS) && option->no_closed_streams) { (*session_ptr)->opt_flags |= NGHTTP2_OPTMASK_NO_CLOSED_STREAMS; } if (option->opt_set_mask & NGHTTP2_OPT_MAX_OUTBOUND_ACK) { (*session_ptr)->max_outbound_ack = option->max_outbound_ack; } } rv = nghttp2_hd_deflate_init2(&(*session_ptr)->hd_deflater, max_deflate_dynamic_table_size, mem); if (rv != 0) { goto fail_hd_deflater; } rv = nghttp2_hd_inflate_init(&(*session_ptr)->hd_inflater, mem); if (rv != 0) { goto fail_hd_inflater; } rv = nghttp2_map_init(&(*session_ptr)->streams, mem); if (rv != 0) { goto fail_map; } nbuffer = ((*session_ptr)->max_send_header_block_length + NGHTTP2_FRAMEBUF_CHUNKLEN - 1) / NGHTTP2_FRAMEBUF_CHUNKLEN; if (nbuffer == 0) { nbuffer = 1; } /* 1 for Pad Field. */ rv = nghttp2_bufs_init3(&(*session_ptr)->aob.framebufs, NGHTTP2_FRAMEBUF_CHUNKLEN, nbuffer, 1, NGHTTP2_FRAME_HDLEN + 1, mem); if (rv != 0) { goto fail_aob_framebuf; } active_outbound_item_reset(&(*session_ptr)->aob, mem); (*session_ptr)->callbacks = *callbacks; (*session_ptr)->user_data = user_data; session_inbound_frame_reset(*session_ptr); if (nghttp2_enable_strict_preface) { nghttp2_inbound_frame *iframe = &(*session_ptr)->iframe; if (server && ((*session_ptr)->opt_flags & NGHTTP2_OPTMASK_NO_RECV_CLIENT_MAGIC) == 0) { iframe->state = NGHTTP2_IB_READ_CLIENT_MAGIC; iframe->payloadleft = NGHTTP2_CLIENT_MAGIC_LEN; } else { iframe->state = NGHTTP2_IB_READ_FIRST_SETTINGS; } if (!server) { (*session_ptr)->aob.state = NGHTTP2_OB_SEND_CLIENT_MAGIC; nghttp2_bufs_add(&(*session_ptr)->aob.framebufs, NGHTTP2_CLIENT_MAGIC, NGHTTP2_CLIENT_MAGIC_LEN); } } return 0; fail_aob_framebuf: nghttp2_map_free(&(*session_ptr)->streams); fail_map: nghttp2_hd_inflate_free(&(*session_ptr)->hd_inflater); fail_hd_inflater: nghttp2_hd_deflate_free(&(*session_ptr)->hd_deflater); fail_hd_deflater: nghttp2_mem_free(mem, *session_ptr); fail_session: return rv; } ; 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: static int read_part_of_packet(AVFormatContext *s, int64_t *pts, int *len, int *strid, int read_packet) { AVIOContext *pb = s->pb; PVAContext *pvactx = s->priv_data; int syncword, streamid, reserved, flags, length, pts_flag; int64_t pva_pts = AV_NOPTS_VALUE, startpos; int ret; recover: startpos = avio_tell(pb); syncword = avio_rb16(pb); streamid = avio_r8(pb); avio_r8(pb); /* counter not used */ reserved = avio_r8(pb); flags = avio_r8(pb); length = avio_rb16(pb); pts_flag = flags & 0x10; if (syncword != PVA_MAGIC) { pva_log(s, AV_LOG_ERROR, "invalid syncword\n"); return AVERROR(EIO); } if (streamid != PVA_VIDEO_PAYLOAD && streamid != PVA_AUDIO_PAYLOAD) { pva_log(s, AV_LOG_ERROR, "invalid streamid\n"); return AVERROR(EIO); } if (reserved != 0x55) { pva_log(s, AV_LOG_WARNING, "expected reserved byte to be 0x55\n"); } if (length > PVA_MAX_PAYLOAD_LENGTH) { pva_log(s, AV_LOG_ERROR, "invalid payload length %u\n", length); return AVERROR(EIO); } if (streamid == PVA_VIDEO_PAYLOAD && pts_flag) { pva_pts = avio_rb32(pb); length -= 4; } else if (streamid == PVA_AUDIO_PAYLOAD) { /* PVA Audio Packets either start with a signaled PES packet or * are a continuation of the previous PES packet. New PES packets * always start at the beginning of a PVA Packet, never somewhere in * the middle. */ if (!pvactx->continue_pes) { int pes_signal, pes_header_data_length, pes_packet_length, pes_flags; unsigned char pes_header_data[256]; pes_signal = avio_rb24(pb); avio_r8(pb); pes_packet_length = avio_rb16(pb); pes_flags = avio_rb16(pb); pes_header_data_length = avio_r8(pb); if (pes_signal != 1 || pes_header_data_length == 0) { pva_log(s, AV_LOG_WARNING, "expected non empty signaled PES packet, " "trying to recover\n"); avio_skip(pb, length - 9); if (!read_packet) return AVERROR(EIO); goto recover; } ret = avio_read(pb, pes_header_data, pes_header_data_length); if (ret != pes_header_data_length) return ret < 0 ? ret : AVERROR_INVALIDDATA; length -= 9 + pes_header_data_length; pes_packet_length -= 3 + pes_header_data_length; pvactx->continue_pes = pes_packet_length; if (pes_flags & 0x80 && (pes_header_data[0] & 0xf0) == 0x20) { if (pes_header_data_length < 5) { pva_log(s, AV_LOG_ERROR, "header too short\n"); avio_skip(pb, length); return AVERROR_INVALIDDATA; } pva_pts = ff_parse_pes_pts(pes_header_data); } } pvactx->continue_pes -= length; if (pvactx->continue_pes < 0) { pva_log(s, AV_LOG_WARNING, "audio data corruption\n"); pvactx->continue_pes = 0; } } if (pva_pts != AV_NOPTS_VALUE) av_add_index_entry(s->streams[streamid-1], startpos, pva_pts, 0, 0, AVINDEX_KEYFRAME); *pts = pva_pts; *len = length; *strid = streamid; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-835'], 'message': 'avformat/pva: Check for EOF before retrying in read_part_of_packet() Fixes: Infinite loop Fixes: pva-4b1835dbc2027bf3c567005dcc78e85199240d06 Found-by: Paul Ch <paulcher@icloud.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc>'</s>
<s>[INST] Given the following code containing errors, provide 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_hash_init(unsigned long state, const void *iv __maybe_unused, size_t iv_len __maybe_unused) { 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_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; switch (TEE_ALG_GET_CLASS(cs->algo)) { case TEE_OPERATION_DIGEST: res = crypto_hash_init(cs->ctx, cs->algo); if (res != TEE_SUCCESS) return res; break; case TEE_OPERATION_MAC: { struct tee_obj *o; struct tee_cryp_obj_secret *key; res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o); if (res != TEE_SUCCESS) return res; if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) return TEE_ERROR_BAD_PARAMETERS; key = (struct tee_cryp_obj_secret *)o->attr; res = crypto_mac_init(cs->ctx, cs->algo, (void *)(key + 1), key->key_size); if (res != TEE_SUCCESS) return res; break; } default: return TEE_ERROR_BAD_PARAMETERS; } 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: FilterConfigSharedPtr getConfig() { envoy::extensions::filters::http::oauth2::v3::OAuth2Config p; auto* endpoint = p.mutable_token_endpoint(); endpoint->set_cluster("auth.example.com"); endpoint->set_uri("auth.example.com/_oauth"); endpoint->mutable_timeout()->set_seconds(1); p.set_redirect_uri("%REQ(:scheme)%://%REQ(:authority)%" + TEST_CALLBACK); p.mutable_redirect_path_matcher()->mutable_path()->set_exact(TEST_CALLBACK); p.set_authorization_endpoint("https://auth.example.com/oauth/authorize/"); p.mutable_signout_path()->mutable_path()->set_exact("/_signout"); p.set_forward_bearer_token(true); p.add_auth_scopes("user"); p.add_auth_scopes("openid"); p.add_auth_scopes("email"); p.add_resources("oauth2-resource"); p.add_resources("http://example.com"); p.add_resources("https://example.com"); auto* matcher = p.add_pass_through_matcher(); matcher->set_name(":method"); matcher->mutable_string_match()->set_exact("OPTIONS"); auto credentials = p.mutable_credentials(); credentials->set_client_id(TEST_CLIENT_ID); credentials->mutable_token_secret()->set_name("secret"); credentials->mutable_hmac_secret()->set_name("hmac"); // Skipping setting credentials.cookie_names field should give default cookie names: // BearerToken, OauthHMAC, and OauthExpires. MessageUtil::validate(p, ProtobufMessage::getStrictValidationVisitor()); // Create filter config. auto secret_reader = std::make_shared<MockSecretReader>(); FilterConfigSharedPtr c = std::make_shared<FilterConfig>(p, factory_context_.cluster_manager_, secret_reader, scope_, "test."); return c; } ; 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: void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'parse_qt: possible integer overflow'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static unsigned xen_netbk_tx_build_gops(struct xen_netbk *netbk) { struct gnttab_copy *gop = netbk->tx_copy_ops, *request_gop; struct sk_buff *skb; int ret; while (((nr_pending_reqs(netbk) + MAX_SKB_FRAGS) < MAX_PENDING_REQS) && !list_empty(&netbk->net_schedule_list)) { struct xenvif *vif; struct xen_netif_tx_request txreq; struct xen_netif_tx_request txfrags[MAX_SKB_FRAGS]; struct page *page; struct xen_netif_extra_info extras[XEN_NETIF_EXTRA_TYPE_MAX-1]; u16 pending_idx; RING_IDX idx; int work_to_do; unsigned int data_len; pending_ring_idx_t index; /* Get a netif from the list with work to do. */ vif = poll_net_schedule_list(netbk); if (!vif) continue; RING_FINAL_CHECK_FOR_REQUESTS(&vif->tx, work_to_do); if (!work_to_do) { xenvif_put(vif); continue; } idx = vif->tx.req_cons; rmb(); /* Ensure that we see the request before we copy it. */ memcpy(&txreq, RING_GET_REQUEST(&vif->tx, idx), sizeof(txreq)); /* Credit-based scheduling. */ if (txreq.size > vif->remaining_credit && tx_credit_exceeded(vif, txreq.size)) { xenvif_put(vif); continue; } vif->remaining_credit -= txreq.size; work_to_do--; vif->tx.req_cons = ++idx; memset(extras, 0, sizeof(extras)); if (txreq.flags & XEN_NETTXF_extra_info) { work_to_do = xen_netbk_get_extras(vif, extras, work_to_do); idx = vif->tx.req_cons; if (unlikely(work_to_do < 0)) { netbk_tx_err(vif, &txreq, idx); continue; } } ret = netbk_count_requests(vif, &txreq, txfrags, work_to_do); if (unlikely(ret < 0)) { netbk_tx_err(vif, &txreq, idx - ret); continue; } idx += ret; if (unlikely(txreq.size < ETH_HLEN)) { netdev_dbg(vif->dev, "Bad packet size: %d\n", txreq.size); netbk_tx_err(vif, &txreq, idx); continue; } /* No crossing a page as the payload mustn't fragment. */ if (unlikely((txreq.offset + txreq.size) > PAGE_SIZE)) { netdev_dbg(vif->dev, "txreq.offset: %x, size: %u, end: %lu\n", txreq.offset, txreq.size, (txreq.offset&~PAGE_MASK) + txreq.size); netbk_tx_err(vif, &txreq, idx); continue; } index = pending_index(netbk->pending_cons); pending_idx = netbk->pending_ring[index]; data_len = (txreq.size > PKT_PROT_LEN && ret < MAX_SKB_FRAGS) ? PKT_PROT_LEN : txreq.size; skb = alloc_skb(data_len + NET_SKB_PAD + NET_IP_ALIGN, GFP_ATOMIC | __GFP_NOWARN); if (unlikely(skb == NULL)) { netdev_dbg(vif->dev, "Can't allocate a skb in start_xmit.\n"); netbk_tx_err(vif, &txreq, idx); break; } /* Packets passed to netif_rx() must have some headroom. */ skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN); if (extras[XEN_NETIF_EXTRA_TYPE_GSO - 1].type) { struct xen_netif_extra_info *gso; gso = &extras[XEN_NETIF_EXTRA_TYPE_GSO - 1]; if (netbk_set_skb_gso(vif, skb, gso)) { kfree_skb(skb); netbk_tx_err(vif, &txreq, idx); continue; } } /* XXX could copy straight to head */ page = xen_netbk_alloc_page(netbk, skb, pending_idx); if (!page) { kfree_skb(skb); netbk_tx_err(vif, &txreq, idx); continue; } gop->source.u.ref = txreq.gref; gop->source.domid = vif->domid; gop->source.offset = txreq.offset; gop->dest.u.gmfn = virt_to_mfn(page_address(page)); gop->dest.domid = DOMID_SELF; gop->dest.offset = txreq.offset; gop->len = txreq.size; gop->flags = GNTCOPY_source_gref; gop++; memcpy(&netbk->pending_tx_info[pending_idx].req, &txreq, sizeof(txreq)); netbk->pending_tx_info[pending_idx].vif = vif; *((u16 *)skb->data) = pending_idx; __skb_put(skb, data_len); skb_shinfo(skb)->nr_frags = ret; if (data_len < txreq.size) { skb_shinfo(skb)->nr_frags++; frag_set_pending_idx(&skb_shinfo(skb)->frags[0], pending_idx); } else { frag_set_pending_idx(&skb_shinfo(skb)->frags[0], INVALID_PENDING_IDX); } netbk->pending_cons++; request_gop = xen_netbk_get_requests(netbk, vif, skb, txfrags, gop); if (request_gop == NULL) { kfree_skb(skb); netbk_tx_err(vif, &txreq, idx); continue; } gop = request_gop; __skb_queue_tail(&netbk->tx_queue, skb); vif->tx.req_cons = idx; xen_netbk_check_rx_xenvif(vif); if ((gop-netbk->tx_copy_ops) >= ARRAY_SIZE(netbk->tx_copy_ops)) break; } return gop - netbk->tx_copy_ops; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'xen/netback: shutdown the ring if it contains garbage. A buggy or malicious frontend should not be able to confuse netback. If we spot anything which is not as it should be then shutdown the device and don't try to continue with the ring in a potentially hostile state. Well behaved and non-hostile frontends will not be penalised. As well as making the existing checks for such errors fatal also add a new check that ensures that there isn't an insane number of requests on the ring (i.e. more than would fit in the ring). If the ring contains garbage then previously is was possible to loop over this insane number, getting an error each time and therefore not generating any more pending requests and therefore not exiting the loop in xen_netbk_tx_build_gops for an externded period. Also turn various netdev_dbg calls which no precipitate a fatal error into netdev_err, they are rate limited because the device is shutdown afterwards. This fixes at least one known DoS/softlockup of the backend domain. Signed-off-by: Ian Campbell <ian.campbell@citrix.com> Reviewed-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> Acked-by: Jan Beulich <JBeulich@suse.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err = -EIO; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) goto out; symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out: up_read(&iinfo->i_data_sem); SetPageError(page); kunmap(page); unlock_page(page); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'udf: Verify symlink size before loading it UDF specification allows arbitrarily large symlinks. However we support only symlinks at most one block large. Check the length of the symlink so that we don't access memory beyond end of the symlink block. CC: stable@vger.kernel.org Reported-by: Carl Henrik Lunde <chlunde@gmail.com> Signed-off-by: Jan Kara <jack@suse.cz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int utf8s_to_utf16s(const u8 *s, int len, wchar_t *pwcs) { u16 *op; int size; unicode_t u; op = pwcs; while (*s && len > 0) { if (*s & 0x80) { size = utf8_to_utf32(s, len, &u); if (size < 0) return -EINVAL; if (u >= PLANE_SIZE) { u -= PLANE_SIZE; *op++ = (wchar_t) (SURROGATE_PAIR | ((u >> 10) & SURROGATE_BITS)); *op++ = (wchar_t) (SURROGATE_PAIR | SURROGATE_LOW | (u & SURROGATE_BITS)); } else { *op++ = (wchar_t) u; } s += size; len -= size; } else { *op++ = *s++; len--; } } return op - pwcs; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'NLS: improve UTF8 -> UTF16 string conversion routine The utf8s_to_utf16s conversion routine needs to be improved. Unlike its utf16s_to_utf8s sibling, it doesn't accept arguments specifying the maximum length of the output buffer or the endianness of its 16-bit output. This patch (as1501) adds the two missing arguments, and adjusts the only two places in the kernel where the function is called. A follow-on patch will add a third caller that does utilize the new capabilities. The two conversion routines are still annoyingly inconsistent in the way they handle invalid byte combinations. But that's a subject for a different patch. Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: Clemens Ladisch <clemens@ladisch.de> Signed-off-by: Greg Kroah-Hartman <gregkh@suse.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: u64 secure_dccp_sequence_number(__be32 saddr, __be32 daddr, __be16 sport, __be16 dport) { u64 seq; __u32 hash[4]; struct keydata *keyptr = get_keyptr(); hash[0] = (__force u32)saddr; hash[1] = (__force u32)daddr; hash[2] = ((__force u16)sport << 16) + (__force u16)dport; hash[3] = keyptr->secret[11]; seq = half_md4_transform(hash, keyptr->secret); seq |= ((u64)keyptr->count) << (32 - HASH_BITS); seq += ktime_to_ns(ktime_get_real()); seq &= (1ull << 48) - 1; return seq; } ; 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 GetDeviceForInput(const EagerOperation& op, const EagerContext& ctx, TensorHandle* tensor_handle, Device** result) { Device* cpu_device = ctx.HostCPU(); string device_name; if (tensor_handle->Type() != TensorHandle::LOCAL) { Device* device = tensor_handle->device(); device_name = device != nullptr ? device->name() : cpu_device->name(); *result = (device == nullptr ? cpu_device : device); } else if (tensor_handle->dtype == DT_RESOURCE) { // Use the resource's actual device because it is the device that will // influence partitioning the multi-device function. const Tensor* tensor; // TODO(fishx): Avoid blocking here. TF_RETURN_IF_ERROR(tensor_handle->Tensor(&tensor)); const ResourceHandle& handle = tensor->flat<ResourceHandle>()(0); device_name = handle.device(); Device* input_device; TF_RETURN_IF_ERROR( ctx.FindDeviceFromName(device_name.c_str(), &input_device)); *result = input_device; } else { Device* device = tensor_handle->device(); const bool is_tpu = device != nullptr && device->device_type() == "TPU"; // int32 return values can be placed on TPUs. const bool use_host_memory = is_tpu ? MTypeFromDTypeIntsOnDevice(tensor_handle->dtype) : MTypeFromDType(tensor_handle->dtype); if (use_host_memory) { *result = cpu_device; } else { // Eager ops executing as functions should have their preferred inputs set // to the op's device. This allows us to avoid expensive D2H copies if a // mirror of the tensor already exists on the op's device. if (!op.is_function() && device != nullptr && device != cpu_device) { device = absl::get<Device*>(op.Device()); } *result = (device == nullptr ? cpu_device : device); } } return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-475'], 'message': 'Fix empty resource handle vulnerability. Some ops that attempt to extract a resource handle from user input can lead to nullptr dereferences. This returns an error in such a case. PiperOrigin-RevId: 445571938'</s>
<s>[INST] Given the following code containing errors, provide 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 ldb_msg_add_string(struct ldb_message *msg, const char *attr_name, const char *str) { struct ldb_val val; val.data = discard_const_p(uint8_t, str); val.length = strlen(str); if (val.length == 0) { /* allow empty strings as non-existent attributes */ return LDB_SUCCESS; } return ldb_msg_add_value(msg, attr_name, &val, NULL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'CVE-2022-32746 ldb: Add functions for appending to an ldb_message Currently, there are many places where we use ldb_msg_add_empty() to add an empty element to a message, and then call ldb_msg_add_value() or similar to add values to that element. However, this performs an unnecessary search of the message's elements to locate the new element. Moreover, if an element with the same attribute name already exists earlier in the message, the values will be added to that element, instead of to the intended newly added element. A similar pattern exists where we add values to a message, and then call ldb_msg_find_element() to locate that message element and sets its flags to (e.g.) LDB_FLAG_MOD_REPLACE. This also performs an unnecessary search, and may locate the wrong message element for setting the flags. To avoid these problems, add functions for appending a value to a message, so that a particular value can be added to the end of a message in a single operation. For ADD requests, it is important that no two message elements share the same attribute name, otherwise things will break. (Normally, ldb_msg_normalize() is called before processing the request to help ensure this.) Thus, we must be careful not to append an attribute to an ADD message, unless we are sure (e.g. through ldb_msg_find_element()) that an existing element for that attribute is not present. These functions will be used in the next commit. BUG: https://bugzilla.samba.org/show_bug.cgi?id=15009 Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: EbmlElement * EbmlElement::FindNextElement(IOCallback & DataStream, const EbmlSemanticContext & Context, int & UpperLevel, uint64 MaxDataSize, bool AllowDummyElt, unsigned int MaxLowerLevel) { int PossibleID_Length = 0; binary PossibleIdNSize[16]; int PossibleSizeLength; uint64 SizeUnknown; int ReadIndex = 0; // trick for the algo, start index at 0 uint32 ReadSize = 0; uint64 SizeFound; int SizeIdx; bool bFound; int UpperLevel_original = UpperLevel; do { // read a potential ID do { assert(ReadIndex < 16); // build the ID with the current Read Buffer bFound = false; binary IdBitMask = 1 << 7; for (SizeIdx = 0; SizeIdx < ReadIndex && SizeIdx < 4; SizeIdx++) { if (PossibleIdNSize[0] & (IdBitMask >> SizeIdx)) { // ID found PossibleID_Length = SizeIdx + 1; IdBitMask >>= SizeIdx; bFound = true; break; } } if (bFound) { break; } if (ReadIndex >= 4) { // ID not found // shift left the read octets memmove(&PossibleIdNSize[0],&PossibleIdNSize[1], --ReadIndex); } if (DataStream.read(&PossibleIdNSize[ReadIndex++], 1) == 0) { return NULL; // no more data ? } ReadSize++; } while (!bFound && MaxDataSize > ReadSize); if (!bFound) // we reached the maximum we could read without a proper ID return NULL; SizeIdx = ReadIndex; ReadIndex -= PossibleID_Length; // read the data size uint32 _SizeLength; PossibleSizeLength = ReadIndex; while (1) { _SizeLength = PossibleSizeLength; SizeFound = ReadCodedSizeValue(&PossibleIdNSize[PossibleID_Length], _SizeLength, SizeUnknown); if (_SizeLength != 0) { bFound = true; break; } if (PossibleSizeLength >= 8) { bFound = false; break; } if( DataStream.read( &PossibleIdNSize[SizeIdx++], 1 ) == 0 ) { return NULL; // no more data ? } ReadSize++; PossibleSizeLength++; } if (bFound) { // find the element in the context and use the correct creator EbmlId PossibleID(PossibleIdNSize, PossibleID_Length); EbmlElement * Result = CreateElementUsingContext(PossibleID, Context, UpperLevel, false, AllowDummyElt, MaxLowerLevel); ///< \todo continue is misplaced if (Result != NULL) { if (AllowDummyElt || !Result->IsDummy()) { Result->SetSizeLength(_SizeLength); Result->Size = SizeFound; // UpperLevel values // -1 : global element // 0 : child // 1 : same level // + : further parent if (Result->ValidateSize() && (SizeFound == SizeUnknown || UpperLevel > 0 || MaxDataSize == 0 || MaxDataSize >= (PossibleID_Length + PossibleSizeLength + SizeFound))) { if (SizeFound == SizeUnknown) { Result->SetSizeInfinite(); } Result->SizePosition = DataStream.getFilePointer() - SizeIdx + EBML_ID_LENGTH(PossibleID); Result->ElementPosition = Result->SizePosition - EBML_ID_LENGTH(PossibleID); // place the file at the beggining of the data DataStream.setFilePointer(Result->SizePosition + _SizeLength); return Result; } } delete Result; } } // recover all the data in the buffer minus one byte ReadIndex = SizeIdx - 1; memmove(&PossibleIdNSize[0], &PossibleIdNSize[1], ReadIndex); UpperLevel = UpperLevel_original; } while ( MaxDataSize > DataStream.getFilePointer() - SizeIdx + PossibleID_Length ); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Check the max size to read before actually reading The size check waas also missing from the length parsing'</s>
<s>[INST] Given the following code containing errors, provide 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 recalculate_apic_map(struct kvm *kvm) { struct kvm_apic_map *new, *old = NULL; struct kvm_vcpu *vcpu; int i; new = kzalloc(sizeof(struct kvm_apic_map), GFP_KERNEL); mutex_lock(&kvm->arch.apic_map_lock); if (!new) goto out; new->ldr_bits = 8; /* flat mode is default */ new->cid_shift = 8; new->cid_mask = 0; new->lid_mask = 0xff; kvm_for_each_vcpu(i, vcpu, kvm) { struct kvm_lapic *apic = vcpu->arch.apic; u16 cid, lid; u32 ldr; if (!kvm_apic_present(vcpu)) continue; /* * All APICs have to be configured in the same mode by an OS. * We take advatage of this while building logical id loockup * table. After reset APICs are in xapic/flat mode, so if we * find apic with different setting we assume this is the mode * OS wants all apics to be in; build lookup table accordingly. */ if (apic_x2apic_mode(apic)) { new->ldr_bits = 32; new->cid_shift = 16; new->cid_mask = new->lid_mask = 0xffff; } else if (kvm_apic_sw_enabled(apic) && !new->cid_mask /* flat mode */ && kvm_apic_get_reg(apic, APIC_DFR) == APIC_DFR_CLUSTER) { new->cid_shift = 4; new->cid_mask = 0xf; new->lid_mask = 0xf; } new->phys_map[kvm_apic_id(apic)] = apic; ldr = kvm_apic_get_reg(apic, APIC_LDR); cid = apic_cluster_id(new, ldr); lid = apic_logical_id(new, ldr); if (lid) new->logical_map[cid][ffs(lid) - 1] = apic; } out: old = rcu_dereference_protected(kvm->arch.apic_map, lockdep_is_held(&kvm->arch.apic_map_lock)); rcu_assign_pointer(kvm->arch.apic_map, new); mutex_unlock(&kvm->arch.apic_map_lock); if (old) kfree_rcu(old, rcu); kvm_vcpu_request_scan_ioapic(kvm); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-189'], 'message': 'KVM: x86: fix guest-initiated crash with x2apic (CVE-2013-6376) A guest can cause a BUG_ON() leading to a host kernel crash. When the guest writes to the ICR to request an IPI, while in x2apic mode the following things happen, the destination is read from ICR2, which is a register that the guest can control. kvm_irq_delivery_to_apic_fast uses the high 16 bits of ICR2 as the cluster id. A BUG_ON is triggered, which is a protection against accessing map->logical_map with an out-of-bounds access and manages to avoid that anything really unsafe occurs. The logic in the code is correct from real HW point of view. The problem is that KVM supports only one cluster with ID 0 in clustered mode, but the code that has the bug does not take this into account. Reported-by: Lars Bull <larsbull@google.com> Cc: stable@vger.kernel.org Signed-off-by: Gleb Natapov <gleb@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int tipc_link_proto_rcv(struct tipc_link *l, struct sk_buff *skb, struct sk_buff_head *xmitq) { struct tipc_msg *hdr = buf_msg(skb); struct tipc_gap_ack_blks *ga = NULL; bool reply = msg_probe(hdr), retransmitted = false; u16 dlen = msg_data_sz(hdr), glen = 0; u16 peers_snd_nxt = msg_next_sent(hdr); u16 peers_tol = msg_link_tolerance(hdr); u16 peers_prio = msg_linkprio(hdr); u16 gap = msg_seq_gap(hdr); u16 ack = msg_ack(hdr); u16 rcv_nxt = l->rcv_nxt; u16 rcvgap = 0; int mtyp = msg_type(hdr); int rc = 0, released; char *if_name; void *data; trace_tipc_proto_rcv(skb, false, l->name); if (tipc_link_is_blocked(l) || !xmitq) goto exit; if (tipc_own_addr(l->net) > msg_prevnode(hdr)) l->net_plane = msg_net_plane(hdr); skb_linearize(skb); hdr = buf_msg(skb); data = msg_data(hdr); if (!tipc_link_validate_msg(l, hdr)) { trace_tipc_skb_dump(skb, false, "PROTO invalid (1)!"); trace_tipc_link_dump(l, TIPC_DUMP_NONE, "PROTO invalid (1)!"); goto exit; } switch (mtyp) { case RESET_MSG: case ACTIVATE_MSG: /* Complete own link name with peer's interface name */ if_name = strrchr(l->name, ':') + 1; if (sizeof(l->name) - (if_name - l->name) <= TIPC_MAX_IF_NAME) break; if (msg_data_sz(hdr) < TIPC_MAX_IF_NAME) break; strncpy(if_name, data, TIPC_MAX_IF_NAME); /* Update own tolerance if peer indicates a non-zero value */ if (in_range(peers_tol, TIPC_MIN_LINK_TOL, TIPC_MAX_LINK_TOL)) { l->tolerance = peers_tol; l->bc_rcvlink->tolerance = peers_tol; } /* Update own priority if peer's priority is higher */ if (in_range(peers_prio, l->priority + 1, TIPC_MAX_LINK_PRI)) l->priority = peers_prio; /* If peer is going down we want full re-establish cycle */ if (msg_peer_stopping(hdr)) { rc = tipc_link_fsm_evt(l, LINK_FAILURE_EVT); break; } /* If this endpoint was re-created while peer was ESTABLISHING * it doesn't know current session number. Force re-synch. */ if (mtyp == ACTIVATE_MSG && msg_dest_session_valid(hdr) && l->session != msg_dest_session(hdr)) { if (less(l->session, msg_dest_session(hdr))) l->session = msg_dest_session(hdr) + 1; break; } /* ACTIVATE_MSG serves as PEER_RESET if link is already down */ if (mtyp == RESET_MSG || !link_is_up(l)) rc = tipc_link_fsm_evt(l, LINK_PEER_RESET_EVT); /* ACTIVATE_MSG takes up link if it was already locally reset */ if (mtyp == ACTIVATE_MSG && l->state == LINK_ESTABLISHING) rc = TIPC_LINK_UP_EVT; l->peer_session = msg_session(hdr); l->in_session = true; l->peer_bearer_id = msg_bearer_id(hdr); if (l->mtu > msg_max_pkt(hdr)) l->mtu = msg_max_pkt(hdr); break; case STATE_MSG: l->rcv_nxt_state = msg_seqno(hdr) + 1; /* Update own tolerance if peer indicates a non-zero value */ if (in_range(peers_tol, TIPC_MIN_LINK_TOL, TIPC_MAX_LINK_TOL)) { l->tolerance = peers_tol; l->bc_rcvlink->tolerance = peers_tol; } /* Update own prio if peer indicates a different value */ if ((peers_prio != l->priority) && in_range(peers_prio, 1, TIPC_MAX_LINK_PRI)) { l->priority = peers_prio; rc = tipc_link_fsm_evt(l, LINK_FAILURE_EVT); } l->silent_intv_cnt = 0; l->stats.recv_states++; if (msg_probe(hdr)) l->stats.recv_probes++; if (!link_is_up(l)) { if (l->state == LINK_ESTABLISHING) rc = TIPC_LINK_UP_EVT; break; } /* Receive Gap ACK blocks from peer if any */ glen = tipc_get_gap_ack_blks(&ga, l, hdr, true); tipc_mon_rcv(l->net, data + glen, dlen - glen, l->addr, &l->mon_state, l->bearer_id); /* Send NACK if peer has sent pkts we haven't received yet */ if ((reply || msg_is_keepalive(hdr)) && more(peers_snd_nxt, rcv_nxt) && !tipc_link_is_synching(l) && skb_queue_empty(&l->deferdq)) rcvgap = peers_snd_nxt - l->rcv_nxt; if (rcvgap || reply) tipc_link_build_proto_msg(l, STATE_MSG, 0, reply, rcvgap, 0, 0, xmitq); released = tipc_link_advance_transmq(l, l, ack, gap, ga, xmitq, &retransmitted, &rc); if (gap) l->stats.recv_nacks++; if (released || retransmitted) tipc_link_update_cwin(l, released, retransmitted); if (released) tipc_link_advance_backlog(l, xmitq); if (unlikely(!skb_queue_empty(&l->wakeupq))) link_prepare_wakeup(l); } exit: kfree_skb(skb); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tipc: improve size validations for received domain records The function tipc_mon_rcv() allows a node to receive and process domain_record structs from peer nodes to track their views of the network topology. This patch verifies that the number of members in a received domain record does not exceed the limit defined by MAX_MON_DOMAIN, something that may otherwise lead to a stack overflow. tipc_mon_rcv() is called from the function tipc_link_proto_rcv(), where we are reading a 32 bit message data length field into a uint16. To avert any risk of bit overflow, we add an extra sanity check for this in that function. We cannot see that happen with the current code, but future designers being unaware of this risk, may introduce it by allowing delivery of very large (> 64k) sk buffers from the bearer layer. This potential problem was identified by Eric Dumazet. This fixes CVE-2022-0435 Reported-by: Samuel Page <samuel.page@appgate.com> Reported-by: Eric Dumazet <edumazet@google.com> Fixes: 35c55c9877f8 ("tipc: add neighbor monitoring framework") Signed-off-by: Jon Maloy <jmaloy@redhat.com> Reviewed-by: Xin Long <lucien.xin@gmail.com> Reviewed-by: Samuel Page <samuel.page@appgate.com> Reviewed-by: Eric Dumazet <edumazet@google.com> 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: void Compute(OpKernelContext* context) override { const Tensor& tensor_in = context->input(0); const Tensor& tensor_out = context->input(1); const Tensor& out_grad_backprop = context->input(2); // For maxpooling3d, tensor_in should have 5 dimensions. OP_REQUIRES(context, tensor_in.dims() == 5, errors::InvalidArgument("tensor_in must be 5-dimensional")); OP_REQUIRES(context, tensor_out.dims() == 5, errors::InvalidArgument("tensor_out must be 5-dimensional")); // For maxpooling3d, out_grad_backprop should have 5 dimensions. OP_REQUIRES( context, out_grad_backprop.dims() == 5, errors::InvalidArgument("out_grad_backprop must be 5-dimensional")); Pool3dParameters params{context, ksize_, stride_, padding_, data_format_, tensor_in.shape()}; Tensor* output = nullptr; OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {2}, 0, tensor_out.shape(), &output)); LaunchMaxPooling3dGradGradOp<Device, T>::launch( context, params, tensor_in, tensor_out, out_grad_backprop, output); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Add missing validation to pooling_ops_3d PiperOrigin-RevId: 372218727 Change-Id: I6b9ed4266aa7286c02f1f230d7bea922c1be547e'</s>
<s>[INST] Given the following code containing errors, provide 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_write_dsdt(int bus) { struct businfo *bi; struct slotinfo *si; struct pci_vdev *dev; int count, func, slot; /* * If there are no devices on this 'bus' then just return. */ bi = pci_businfo[bus]; if (bi == NULL) { /* * Bus 0 is special because it decodes the I/O ports used * for PCI config space access even if there are no devices * on it. */ if (bus != 0) return; } dsdt_line(" Device (PCI%01X)", bus); dsdt_line(" {"); dsdt_line(" Name (_HID, EisaId (\"PNP0A03\"))"); dsdt_line(" Name (_ADR, Zero)"); dsdt_line(" Method (_BBN, 0, NotSerialized)"); dsdt_line(" {"); dsdt_line(" Return (0x%08X)", bus); dsdt_line(" }"); dsdt_line(" Name (_CRS, ResourceTemplate ()"); dsdt_line(" {"); dsdt_line(" WordBusNumber (ResourceProducer, MinFixed, " "MaxFixed, PosDecode,"); dsdt_line(" 0x0000, // Granularity"); dsdt_line(" 0x%04X, // Range Minimum", bus); dsdt_line(" 0x%04X, // Range Maximum", bus); dsdt_line(" 0x0000, // Translation Offset"); dsdt_line(" 0x0001, // Length"); dsdt_line(" ,, )"); if (bus == 0) { dsdt_indent(3); dsdt_fixed_ioport(0xCF8, 8); dsdt_unindent(3); dsdt_line(" WordIO (ResourceProducer, MinFixed, MaxFixed, " "PosDecode, EntireRange,"); dsdt_line(" 0x0000, // Granularity"); dsdt_line(" 0x0000, // Range Minimum"); dsdt_line(" 0x0CF7, // Range Maximum"); dsdt_line(" 0x0000, // Translation Offset"); dsdt_line(" 0x0CF8, // Length"); dsdt_line(" ,, , TypeStatic)"); dsdt_line(" WordIO (ResourceProducer, MinFixed, MaxFixed, " "PosDecode, EntireRange,"); dsdt_line(" 0x0000, // Granularity"); dsdt_line(" 0x0D00, // Range Minimum"); dsdt_line(" 0x%04X, // Range Maximum", PCI_EMUL_IOBASE - 1); dsdt_line(" 0x0000, // Translation Offset"); dsdt_line(" 0x%04X, // Length", PCI_EMUL_IOBASE - 0x0D00); dsdt_line(" ,, , TypeStatic)"); if (bi == NULL) { dsdt_line(" })"); goto done; } } assert(bi != NULL); /* i/o window */ dsdt_line(" WordIO (ResourceProducer, MinFixed, MaxFixed, " "PosDecode, EntireRange,"); dsdt_line(" 0x0000, // Granularity"); dsdt_line(" 0x%04X, // Range Minimum", bi->iobase); dsdt_line(" 0x%04X, // Range Maximum", bi->iolimit - 1); dsdt_line(" 0x0000, // Translation Offset"); dsdt_line(" 0x%04X, // Length", bi->iolimit - bi->iobase); dsdt_line(" ,, , TypeStatic)"); /* mmio window (32-bit) */ dsdt_line(" DWordMemory (ResourceProducer, PosDecode, " "MinFixed, MaxFixed, NonCacheable, ReadWrite,"); dsdt_line(" 0x00000000, // Granularity"); dsdt_line(" 0x%08X, // Range Minimum\n", bi->membase32); dsdt_line(" 0x%08X, // Range Maximum\n", bi->memlimit32 - 1); dsdt_line(" 0x00000000, // Translation Offset"); dsdt_line(" 0x%08X, // Length\n", bi->memlimit32 - bi->membase32); dsdt_line(" ,, , AddressRangeMemory, TypeStatic)"); /* mmio window (64-bit) */ dsdt_line(" QWordMemory (ResourceProducer, PosDecode, " "MinFixed, MaxFixed, NonCacheable, ReadWrite,"); dsdt_line(" 0x0000000000000000, // Granularity"); dsdt_line(" 0x%016lX, // Range Minimum\n", bi->membase64); dsdt_line(" 0x%016lX, // Range Maximum\n", bi->memlimit64 - 1); dsdt_line(" 0x0000000000000000, // Translation Offset"); dsdt_line(" 0x%016lX, // Length\n", bi->memlimit64 - bi->membase64); dsdt_line(" ,, , AddressRangeMemory, TypeStatic)"); dsdt_line(" })"); if (!is_rtvm) { count = pci_count_lintr(bus); if (count != 0) { dsdt_indent(2); dsdt_line("Name (PPRT, Package ()"); dsdt_line("{"); pci_walk_lintr(bus, pci_pirq_prt_entry, NULL); dsdt_line("})"); dsdt_line("Name (APRT, Package ()"); dsdt_line("{"); pci_walk_lintr(bus, pci_apic_prt_entry, NULL); dsdt_line("})"); dsdt_line("Method (_PRT, 0, NotSerialized)"); dsdt_line("{"); dsdt_line(" If (PICM)"); dsdt_line(" {"); dsdt_line(" Return (APRT)"); dsdt_line(" }"); dsdt_line(" Else"); dsdt_line(" {"); dsdt_line(" Return (PPRT)"); dsdt_line(" }"); dsdt_line("}"); dsdt_unindent(2); } } dsdt_indent(2); for (slot = 0; slot < MAXSLOTS; slot++) { si = &bi->slotinfo[slot]; for (func = 0; func < MAXFUNCS; func++) { dev = si->si_funcs[func].fi_devi; if (dev != NULL && dev->dev_ops->vdev_write_dsdt != NULL) dev->dev_ops->vdev_write_dsdt(dev); } } dsdt_unindent(2); done: dsdt_line(" }"); } ; 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: deinit_pci(struct vmctx *ctx) { struct pci_vdev_ops *ops; struct businfo *bi; struct slotinfo *si; struct funcinfo *fi; int bus, slot, func; size_t lowmem; struct mem_range mr; /* Release PCI extended config space */ bzero(&mr, sizeof(struct mem_range)); mr.name = "PCI ECFG"; mr.base = PCI_EMUL_ECFG_BASE; mr.size = PCI_EMUL_ECFG_SIZE; unregister_mem(&mr); /* Release PCI hole space */ lowmem = vm_get_lowmem_size(ctx); bzero(&mr, sizeof(struct mem_range)); mr.name = "PCI hole (32-bit)"; mr.base = lowmem; mr.size = (4ULL * 1024 * 1024 * 1024) - lowmem; unregister_mem_fallback(&mr); /* ditto for the 64-bit PCI host aperture */ bzero(&mr, sizeof(struct mem_range)); mr.name = "PCI hole (64-bit)"; mr.base = PCI_EMUL_MEMBASE64; mr.size = PCI_EMUL_MEMLIMIT64 - PCI_EMUL_MEMBASE64; unregister_mem_fallback(&mr); for (bus = 0; bus < MAXBUSES; bus++) { bi = pci_businfo[bus]; if (bi == NULL) continue; for (slot = 0; slot < MAXSLOTS; slot++) { si = &bi->slotinfo[slot]; for (func = 0; func < MAXFUNCS; func++) { fi = &si->si_funcs[func]; if (fi->fi_name == NULL) continue; ops = pci_emul_finddev(fi->fi_name); assert(ops != NULL); pr_notice("pci deinit %s\n", fi->fi_name); pci_emul_deinit(ctx, ops, bus, slot, func, fi); } } } } ; 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_lintr_assert(struct pci_vdev *dev) { assert(dev->lintr.pin > 0); pthread_mutex_lock(&dev->lintr.lock); if (dev->lintr.state == IDLE) { if (pci_lintr_permitted(dev)) { dev->lintr.state = ASSERTED; pci_irq_assert(dev); } else dev->lintr.state = PENDING; } pthread_mutex_unlock(&dev->lintr.lock); } ; 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: TPM2B_ATTEST_Marshal(TPM2B_ATTEST *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_MAX_BUFFER_Marshal(TPM2B_MAX_BUFFER *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 int http_connect(URLContext *h, const char *path, const char *local_path, const char *hoststr, const char *auth, const char *proxyauth, int *new_location) { HTTPContext *s = h->priv_data; int post, err; char headers[HTTP_HEADERS_SIZE] = ""; char *authstr = NULL, *proxyauthstr = NULL; int64_t off = s->off; int len = 0; const char *method; int send_expect_100 = 0; /* send http header */ post = h->flags & AVIO_FLAG_WRITE; if (s->post_data) { /* force POST method and disable chunked encoding when * custom HTTP post data is set */ post = 1; s->chunked_post = 0; } if (s->method) method = s->method; else method = post ? "POST" : "GET"; authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path, method); proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth, local_path, method); if (post && !s->post_data) { send_expect_100 = s->send_expect_100; /* The user has supplied authentication but we don't know the auth type, * send Expect: 100-continue to get the 401 response including the * WWW-Authenticate header, or an 100 continue if no auth actually * is needed. */ if (auth && *auth && s->auth_state.auth_type == HTTP_AUTH_NONE && s->http_code != 401) send_expect_100 = 1; } #if FF_API_HTTP_USER_AGENT if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) { av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n"); s->user_agent = av_strdup(s->user_agent_deprecated); } #endif /* set default headers if needed */ if (!has_header(s->headers, "\r\nUser-Agent: ")) len += av_strlcatf(headers + len, sizeof(headers) - len, "User-Agent: %s\r\n", s->user_agent); if (!has_header(s->headers, "\r\nAccept: ")) len += av_strlcpy(headers + len, "Accept: */*\r\n", sizeof(headers) - len); // Note: we send this on purpose even when s->off is 0 when we're probing, // since it allows us to detect more reliably if a (non-conforming) // server supports seeking by analysing the reply headers. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) { len += av_strlcatf(headers + len, sizeof(headers) - len, "Range: bytes=%"PRId64"-", s->off); if (s->end_off) len += av_strlcatf(headers + len, sizeof(headers) - len, "%"PRId64, s->end_off - 1); len += av_strlcpy(headers + len, "\r\n", sizeof(headers) - len); } if (send_expect_100 && !has_header(s->headers, "\r\nExpect: ")) len += av_strlcatf(headers + len, sizeof(headers) - len, "Expect: 100-continue\r\n"); if (!has_header(s->headers, "\r\nConnection: ")) { if (s->multiple_requests) len += av_strlcpy(headers + len, "Connection: keep-alive\r\n", sizeof(headers) - len); else len += av_strlcpy(headers + len, "Connection: close\r\n", sizeof(headers) - len); } if (!has_header(s->headers, "\r\nHost: ")) len += av_strlcatf(headers + len, sizeof(headers) - len, "Host: %s\r\n", hoststr); if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data) len += av_strlcatf(headers + len, sizeof(headers) - len, "Content-Length: %d\r\n", s->post_datalen); if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type) len += av_strlcatf(headers + len, sizeof(headers) - len, "Content-Type: %s\r\n", s->content_type); if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) { char *cookies = NULL; if (!get_cookies(s, &cookies, path, hoststr) && cookies) { len += av_strlcatf(headers + len, sizeof(headers) - len, "Cookie: %s\r\n", cookies); av_free(cookies); } } if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) len += av_strlcatf(headers + len, sizeof(headers) - len, "Icy-MetaData: %d\r\n", 1); /* now add in custom headers */ if (s->headers) av_strlcpy(headers + len, s->headers, sizeof(headers) - len); snprintf(s->buffer, sizeof(s->buffer), "%s %s HTTP/1.1\r\n" "%s" "%s" "%s" "%s%s" "\r\n", method, path, post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "", headers, authstr ? authstr : "", proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : ""); av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer); if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) goto done; if (s->post_data) if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0) goto done; /* init input buffer */ s->buf_ptr = s->buffer; s->buf_end = s->buffer; s->line_count = 0; s->off = 0; s->icy_data_read = 0; s->filesize = -1; s->willclose = 0; s->end_chunked_post = 0; s->end_header = 0; if (post && !s->post_data && !send_expect_100) { /* Pretend that it did work. We didn't read any header yet, since * we've still to send the POST data, but the code calling this * function will check http_code after we return. */ s->http_code = 200; err = 0; goto done; } /* wait for header */ err = http_read_header(h, new_location); if (err < 0) goto done; if (*new_location) s->off = off; err = (off == s->off) ? 0 : -1; done: av_freep(&authstr); av_freep(&proxyauthstr); return err; } ; 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: static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount, struct vm_area_struct *vma, struct page *check_page) { struct mm_struct *mm = vma->vm_mm; pmd_t *pmd; pte_t *pte; pte_t pteval; spinlock_t *ptl; struct page *page; unsigned long address; unsigned long mmun_start; /* For mmu_notifiers */ unsigned long mmun_end; /* For mmu_notifiers */ unsigned long end; int ret = SWAP_AGAIN; int locked_vma = 0; address = (vma->vm_start + cursor) & CLUSTER_MASK; end = address + CLUSTER_SIZE; if (address < vma->vm_start) address = vma->vm_start; if (end > vma->vm_end) end = vma->vm_end; pmd = mm_find_pmd(mm, address); if (!pmd) return ret; mmun_start = address; mmun_end = end; mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); /* * If we can acquire the mmap_sem for read, and vma is VM_LOCKED, * keep the sem while scanning the cluster for mlocking pages. */ if (down_read_trylock(&vma->vm_mm->mmap_sem)) { locked_vma = (vma->vm_flags & VM_LOCKED); if (!locked_vma) up_read(&vma->vm_mm->mmap_sem); /* don't need it */ } pte = pte_offset_map_lock(mm, pmd, address, &ptl); /* Update high watermark before we lower rss */ update_hiwater_rss(mm); for (; address < end; pte++, address += PAGE_SIZE) { if (!pte_present(*pte)) continue; page = vm_normal_page(vma, address, *pte); BUG_ON(!page || PageAnon(page)); if (locked_vma) { mlock_vma_page(page); /* no-op if already mlocked */ if (page == check_page) ret = SWAP_MLOCK; continue; /* don't unmap */ } if (ptep_clear_flush_young_notify(vma, address, pte)) continue; /* Nuke the page table entry. */ flush_cache_page(vma, address, pte_pfn(*pte)); pteval = ptep_clear_flush(vma, address, pte); /* If nonlinear, store the file page offset in the pte. */ if (page->index != linear_page_index(vma, address)) { pte_t ptfile = pgoff_to_pte(page->index); if (pte_soft_dirty(pteval)) pte_file_mksoft_dirty(ptfile); set_pte_at(mm, address, pte, ptfile); } /* Move the dirty bit to the physical page now the pte is gone. */ if (pte_dirty(pteval)) set_page_dirty(page); page_remove_rmap(page); page_cache_release(page); dec_mm_counter(mm, MM_FILEPAGES); (*mapcount)--; } pte_unmap_unlock(pte - 1, ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); if (locked_vma) up_read(&vma->vm_mm->mmap_sem); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-264'], 'message': 'mm: try_to_unmap_cluster() should lock_page() before mlocking A BUG_ON(!PageLocked) was triggered in mlock_vma_page() by Sasha Levin fuzzing with trinity. The call site try_to_unmap_cluster() does not lock the pages other than its check_page parameter (which is already locked). The BUG_ON in mlock_vma_page() is not documented and its purpose is somewhat unclear, but apparently it serializes against page migration, which could otherwise fail to transfer the PG_mlocked flag. This would not be fatal, as the page would be eventually encountered again, but NR_MLOCK accounting would become distorted nevertheless. This patch adds a comment to the BUG_ON in mlock_vma_page() and munlock_vma_page() to that effect. The call site try_to_unmap_cluster() is fixed so that for page != check_page, trylock_page() is attempted (to avoid possible deadlocks as we already have check_page locked) and mlock_vma_page() is performed only upon success. If the page lock cannot be obtained, the page is left without PG_mlocked, which is again not a problem in the whole unevictable memory design. Signed-off-by: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Bob Liu <bob.liu@oracle.com> Reported-by: Sasha Levin <sasha.levin@oracle.com> Cc: Wanpeng Li <liwanp@linux.vnet.ibm.com> Cc: Michel Lespinasse <walken@google.com> Cc: KOSAKI Motohiro <kosaki.motohiro@jp.fujitsu.com> Acked-by: Rik van Riel <riel@redhat.com> Cc: David Rientjes <rientjes@google.com> Cc: Mel Gorman <mgorman@suse.de> Cc: Hugh Dickins <hughd@google.com> Cc: Joonsoo Kim <iamjoonsoo.kim@lge.com> Cc: <stable@vger.kernel.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Status TensorSliceReader::GetTensor( const string& name, std::unique_ptr<tensorflow::Tensor>* out_tensor) const { DataType type; TensorShape shape; TensorSlice slice; { mutex_lock l(mu_); const TensorSliceSet* tss = gtl::FindPtrOrNull(tensors_, name); if (tss == nullptr) { return errors::NotFound(name, " not found in checkpoint file"); } if (tss->Slices().size() > 1) { // TODO(sherrym): Support multi-slice checkpoints. return errors::Unimplemented("Sliced checkpoints are not supported"); } type = tss->type(); shape = tss->shape(); slice = tss->Slices().begin()->second.slice; } std::unique_ptr<tensorflow::Tensor> t(new tensorflow::Tensor(type, shape)); bool success = false; #define READER_COPY(dt) \ case dt: \ success = CopySliceData(name, slice, \ t->flat<EnumToDataType<dt>::Type>().data()); \ break; switch (type) { READER_COPY(DT_FLOAT); READER_COPY(DT_DOUBLE); READER_COPY(DT_INT32); READER_COPY(DT_UINT8); READER_COPY(DT_INT16); READER_COPY(DT_INT8); READER_COPY(DT_INT64); READER_COPY(DT_STRING); default: return errors::Unimplemented("Data type not supported"); } #undef READER_COPY if (!success) { return errors::NotFound(name, " not found in checkpoint file"); } std::swap(*out_tensor, t); return Status::OK(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-345'], 'message': 'Prevent crashes when loading tensor slices with unsupported types. Also fix the `Tensor(const TensorShape&)` constructor swapping the LOG(FATAL) messages for the unset and unsupported types. PiperOrigin-RevId: 392695027 Change-Id: I4beda7db950db951d273e3259a7c8534ece49354'</s>
<s>[INST] Given the following code containing errors, provide 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_finished(SSL *s, int a, int b) { int al,i,ok; long n; unsigned char *p; /* the mac has already been generated when we received the * change cipher spec message and is in s->s3->tmp.peer_finish_md */ n=s->method->ssl_get_message(s, a, b, SSL3_MT_FINISHED, 64, /* should actually be 36+4 :-) */ &ok); if (!ok) return((int)n); /* If this occurs, we have missed a message */ if (!s->s3->change_cipher_spec) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_GOT_A_FIN_BEFORE_A_CCS); goto f_err; } s->s3->change_cipher_spec=0; p = (unsigned char *)s->init_msg; i = s->s3->tmp.peer_finish_md_len; if (i != n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_BAD_DIGEST_LENGTH); goto f_err; } if (memcmp(p, s->s3->tmp.peer_finish_md, i) != 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_FINISHED,SSL_R_DIGEST_CHECK_FAILED); goto f_err; } /* Copy the finished so we can use it for renegotiation checks */ if(s->type == SSL_ST_ACCEPT) { OPENSSL_assert(i <= EVP_MAX_MD_SIZE); memcpy(s->s3->previous_client_finished, s->s3->tmp.peer_finish_md, i); s->s3->previous_client_finished_len=i; } else { OPENSSL_assert(i <= EVP_MAX_MD_SIZE); memcpy(s->s3->previous_server_finished, s->s3->tmp.peer_finish_md, i); s->s3->previous_server_finished_len=i; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); return(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp. This change adds CRYPTO_memcmp, which compares two vectors of bytes in an amount of time that's independent of their contents. It also changes several MAC compares in the code to use this over the standard memcmp, which may leak information about the size of a matching prefix. (cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98) Conflicts: crypto/crypto.h ssl/t1_lib.c (cherry picked from commit dc406b59f3169fe191e58906df08dce97edb727c) Conflicts: crypto/crypto.h ssl/d1_pkt.c ssl/s3_pkt.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 OpenSSL_add_all_ciphers(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cfb()); EVP_add_cipher(EVP_des_cfb1()); EVP_add_cipher(EVP_des_cfb8()); EVP_add_cipher(EVP_des_ede_cfb()); EVP_add_cipher(EVP_des_ede3_cfb()); EVP_add_cipher(EVP_des_ede3_cfb1()); EVP_add_cipher(EVP_des_ede3_cfb8()); EVP_add_cipher(EVP_des_ofb()); EVP_add_cipher(EVP_des_ede_ofb()); EVP_add_cipher(EVP_des_ede3_ofb()); EVP_add_cipher(EVP_desx_cbc()); EVP_add_cipher_alias(SN_desx_cbc,"DESX"); EVP_add_cipher_alias(SN_desx_cbc,"desx"); EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher_alias(SN_des_cbc,"DES"); EVP_add_cipher_alias(SN_des_cbc,"des"); EVP_add_cipher(EVP_des_ede_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); EVP_add_cipher_alias(SN_des_ede3_cbc,"DES3"); EVP_add_cipher_alias(SN_des_ede3_cbc,"des3"); EVP_add_cipher(EVP_des_ecb()); EVP_add_cipher(EVP_des_ede()); EVP_add_cipher(EVP_des_ede3()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); EVP_add_cipher(EVP_rc4_40()); #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_ecb()); EVP_add_cipher(EVP_idea_cfb()); EVP_add_cipher(EVP_idea_ofb()); EVP_add_cipher(EVP_idea_cbc()); EVP_add_cipher_alias(SN_idea_cbc,"IDEA"); EVP_add_cipher_alias(SN_idea_cbc,"idea"); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_ecb()); EVP_add_cipher(EVP_seed_cfb()); EVP_add_cipher(EVP_seed_ofb()); EVP_add_cipher(EVP_seed_cbc()); EVP_add_cipher_alias(SN_seed_cbc,"SEED"); EVP_add_cipher_alias(SN_seed_cbc,"seed"); #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_ecb()); EVP_add_cipher(EVP_rc2_cfb()); EVP_add_cipher(EVP_rc2_ofb()); EVP_add_cipher(EVP_rc2_cbc()); EVP_add_cipher(EVP_rc2_40_cbc()); EVP_add_cipher(EVP_rc2_64_cbc()); EVP_add_cipher_alias(SN_rc2_cbc,"RC2"); EVP_add_cipher_alias(SN_rc2_cbc,"rc2"); #endif #ifndef OPENSSL_NO_BF EVP_add_cipher(EVP_bf_ecb()); EVP_add_cipher(EVP_bf_cfb()); EVP_add_cipher(EVP_bf_ofb()); EVP_add_cipher(EVP_bf_cbc()); EVP_add_cipher_alias(SN_bf_cbc,"BF"); EVP_add_cipher_alias(SN_bf_cbc,"bf"); EVP_add_cipher_alias(SN_bf_cbc,"blowfish"); #endif #ifndef OPENSSL_NO_CAST EVP_add_cipher(EVP_cast5_ecb()); EVP_add_cipher(EVP_cast5_cfb()); EVP_add_cipher(EVP_cast5_ofb()); EVP_add_cipher(EVP_cast5_cbc()); EVP_add_cipher_alias(SN_cast5_cbc,"CAST"); EVP_add_cipher_alias(SN_cast5_cbc,"cast"); EVP_add_cipher_alias(SN_cast5_cbc,"CAST-cbc"); EVP_add_cipher_alias(SN_cast5_cbc,"cast-cbc"); #endif #ifndef OPENSSL_NO_RC5 EVP_add_cipher(EVP_rc5_32_12_16_ecb()); EVP_add_cipher(EVP_rc5_32_12_16_cfb()); EVP_add_cipher(EVP_rc5_32_12_16_ofb()); EVP_add_cipher(EVP_rc5_32_12_16_cbc()); EVP_add_cipher_alias(SN_rc5_cbc,"rc5"); EVP_add_cipher_alias(SN_rc5_cbc,"RC5"); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_ecb()); EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_128_cfb()); EVP_add_cipher(EVP_aes_128_cfb1()); EVP_add_cipher(EVP_aes_128_cfb8()); EVP_add_cipher(EVP_aes_128_ofb()); #if 0 EVP_add_cipher(EVP_aes_128_ctr()); #endif EVP_add_cipher_alias(SN_aes_128_cbc,"AES128"); EVP_add_cipher_alias(SN_aes_128_cbc,"aes128"); EVP_add_cipher(EVP_aes_192_ecb()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_192_cfb()); EVP_add_cipher(EVP_aes_192_cfb1()); EVP_add_cipher(EVP_aes_192_cfb8()); EVP_add_cipher(EVP_aes_192_ofb()); #if 0 EVP_add_cipher(EVP_aes_192_ctr()); #endif EVP_add_cipher_alias(SN_aes_192_cbc,"AES192"); EVP_add_cipher_alias(SN_aes_192_cbc,"aes192"); EVP_add_cipher(EVP_aes_256_ecb()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_256_cfb()); EVP_add_cipher(EVP_aes_256_cfb1()); EVP_add_cipher(EVP_aes_256_cfb8()); EVP_add_cipher(EVP_aes_256_ofb()); #if 0 EVP_add_cipher(EVP_aes_256_ctr()); #endif EVP_add_cipher_alias(SN_aes_256_cbc,"AES256"); EVP_add_cipher_alias(SN_aes_256_cbc,"aes256"); #endif #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_128_cfb()); EVP_add_cipher(EVP_camellia_128_cfb1()); EVP_add_cipher(EVP_camellia_128_cfb8()); EVP_add_cipher(EVP_camellia_128_ofb()); EVP_add_cipher_alias(SN_camellia_128_cbc,"CAMELLIA128"); EVP_add_cipher_alias(SN_camellia_128_cbc,"camellia128"); EVP_add_cipher(EVP_camellia_192_ecb()); EVP_add_cipher(EVP_camellia_192_cbc()); EVP_add_cipher(EVP_camellia_192_cfb()); EVP_add_cipher(EVP_camellia_192_cfb1()); EVP_add_cipher(EVP_camellia_192_cfb8()); EVP_add_cipher(EVP_camellia_192_ofb()); EVP_add_cipher_alias(SN_camellia_192_cbc,"CAMELLIA192"); EVP_add_cipher_alias(SN_camellia_192_cbc,"camellia192"); EVP_add_cipher(EVP_camellia_256_ecb()); EVP_add_cipher(EVP_camellia_256_cbc()); EVP_add_cipher(EVP_camellia_256_cfb()); EVP_add_cipher(EVP_camellia_256_cfb1()); EVP_add_cipher(EVP_camellia_256_cfb8()); EVP_add_cipher(EVP_camellia_256_ofb()); EVP_add_cipher_alias(SN_camellia_256_cbc,"CAMELLIA256"); EVP_add_cipher_alias(SN_camellia_256_cbc,"camellia256"); #endif PKCS12_PBE_add(); PKCS5_PBE_add(); } ; 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: static int ssl3_get_record(SSL *s) { int ssl_major,ssl_minor,al; int enc_err,n,i,ret= -1; SSL3_RECORD *rr; SSL_SESSION *sess; unsigned char *p; unsigned char md[EVP_MAX_MD_SIZE]; short version; unsigned mac_size; int clear=0; size_t extra; rr= &(s->s3->rrec); sess=s->session; if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER) extra=SSL3_RT_MAX_EXTRA; else extra=0; if (extra != s->s3->rbuf.len - SSL3_RT_MAX_PACKET_SIZE) { /* actually likely an application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER * set after ssl3_setup_buffers() was done */ SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR); return -1; } again: /* check if we have the header */ if ( (s->rstate != SSL_ST_READ_BODY) || (s->packet_length < SSL3_RT_HEADER_LENGTH)) { n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0); if (n <= 0) return(n); /* error or non-blocking */ s->rstate=SSL_ST_READ_BODY; p=s->packet; /* Pull apart the header into the SSL3_RECORD */ rr->type= *(p++); ssl_major= *(p++); ssl_minor= *(p++); version=(ssl_major<<8)|ssl_minor; n2s(p,rr->length); /* Lets check version */ if (!s->first_packet) { if (version != s->version) { SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); if ((s->version & 0xFF00) == (version & 0xFF00)) /* Send back error using their minor version number :-) */ s->version = (unsigned short)version; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } } if ((version>>8) != SSL3_VERSION_MAJOR) { SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER); goto err; } if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG); goto f_err; } /* now s->rstate == SSL_ST_READ_BODY */ } /* s->rstate == SSL_ST_READ_BODY, get and decode the data */ if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH) { /* now s->packet_length == SSL3_RT_HEADER_LENGTH */ i=rr->length; n=ssl3_read_n(s,i,i,1); if (n <= 0) return(n); /* error or non-blocking io */ /* now n == rr->length, * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */ } s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */ /* 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[SSL3_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+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_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) { /* SSLerr() and ssl3_send_alert() have been called */ goto err; } #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 */ unsigned char *mac = NULL; unsigned char mac_tmp[EVP_MAX_MD_SIZE]; mac_size=EVP_MD_size(s->read_hash); OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE); /* orig_len is the length of the record before any padding was * removed. This is public information, as is the MAC in use, * therefore we can safely process the record in a different * amount of time if it's too short to possibly contain a MAC. */ if (rr->orig_len < mac_size || /* CBC records must have a padding length byte too. */ (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE && rr->orig_len < mac_size+1)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT); goto f_err; } if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) { /* We update the length so that the TLS header bytes * can be constructed correctly but we need to extract * the MAC in constant time from within the record, * without leaking the contents of the padding bytes. * */ mac = mac_tmp; ssl3_cbc_copy_mac(mac_tmp, rr, mac_size); rr->length -= mac_size; } else { /* In this case there's no padding, so |rec->orig_len| * equals |rec->length| and we checked that there's * enough bytes for |mac_size| above. */ rr->length -= mac_size; mac = &rr->data[rr->length]; } i=s->method->ssl3_enc->mac(s,md,0 /* not send */); if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) enc_err = -1; if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size) enc_err = -1; } if (enc_err < 0) { /* A separate 'decryption_failed' alert was introduced with TLS 1.0, * SSL 3.0 only has 'bad_record_mac'. But unless a decryption * failure is directly visible from the ciphertext anyway, * we should not reveal which kind of error occured -- this * might become visible to an attacker (e.g. via a logfile) */ al=SSL_AD_BAD_RECORD_MAC; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC); goto f_err; } /* r->length is now just compressed */ if (s->expand != NULL) { if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG); goto f_err; } if (!ssl3_do_uncompress(s)) { al=SSL_AD_DECOMPRESSION_FAILURE; SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION); goto f_err; } } if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra) { al=SSL_AD_RECORD_OVERFLOW; SSLerr(SSL_F_SSL3_GET_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; /* just read a 0 length packet */ if (rr->length == 0) goto again; return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(ret); } ; 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: char ssl3_cbc_record_digest_supported(const EVP_MD *digest) { switch (digest->type) { case NID_md5: case NID_sha1: case NID_sha224: case NID_sha256: case NID_sha384: case NID_sha512: return 1; default: return 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Timing fix mitigation for FIPS mode. We have to use EVP in FIPS mode so we can only partially mitigate timing differences. Make an extra call to HMAC_Update to hash additonal blocks to cover any timing differences caused by removal of padding.'</s>
<s>[INST] Given the following code containing errors, provide 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 tls_decrypt_ticket(SSL *s, const unsigned char *etick, int eticklen, const unsigned char *sess_id, int sesslen, SSL_SESSION **psess) { SSL_SESSION *sess; unsigned char *sdec; const unsigned char *p; int slen, mlen, renew_ticket = 0; unsigned char tick_hmac[EVP_MAX_MD_SIZE]; HMAC_CTX hctx; EVP_CIPHER_CTX ctx; SSL_CTX *tctx = s->initial_ctx; /* Need at least keyname + iv + some encrypted data */ if (eticklen < 48) goto tickerr; /* Initialize session ticket encryption and HMAC contexts */ HMAC_CTX_init(&hctx); EVP_CIPHER_CTX_init(&ctx); if (tctx->tlsext_ticket_key_cb) { unsigned char *nctick = (unsigned char *)etick; int rv = tctx->tlsext_ticket_key_cb(s, nctick, nctick + 16, &ctx, &hctx, 0); if (rv < 0) return -1; if (rv == 0) goto tickerr; if (rv == 2) renew_ticket = 1; } else { /* Check key name matches */ if (memcmp(etick, tctx->tlsext_tick_key_name, 16)) goto tickerr; HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(), NULL); EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, tctx->tlsext_tick_aes_key, etick + 16); } /* Attempt to process session ticket, first conduct sanity and * integrity checks on ticket. */ mlen = HMAC_size(&hctx); if (mlen < 0) { EVP_CIPHER_CTX_cleanup(&ctx); return -1; } eticklen -= mlen; /* Check HMAC of encrypted ticket */ HMAC_Update(&hctx, etick, eticklen); HMAC_Final(&hctx, tick_hmac, NULL); HMAC_CTX_cleanup(&hctx); if (memcmp(tick_hmac, etick + eticklen, mlen)) goto tickerr; /* Attempt to decrypt session data */ /* Move p after IV to start of encrypted ticket, update length */ p = etick + 16 + EVP_CIPHER_CTX_iv_length(&ctx); eticklen -= 16 + EVP_CIPHER_CTX_iv_length(&ctx); sdec = OPENSSL_malloc(eticklen); if (!sdec) { EVP_CIPHER_CTX_cleanup(&ctx); return -1; } EVP_DecryptUpdate(&ctx, sdec, &slen, p, eticklen); if (EVP_DecryptFinal(&ctx, sdec + slen, &mlen) <= 0) goto tickerr; slen += mlen; EVP_CIPHER_CTX_cleanup(&ctx); p = sdec; sess = d2i_SSL_SESSION(NULL, &p, slen); OPENSSL_free(sdec); if (sess) { /* The session ID if non-empty is used by some clients to * detect that the ticket has been accepted. So we copy it to * the session structure. If it is empty set length to zero * as required by standard. */ if (sesslen) memcpy(sess->session_id, sess_id, sesslen); sess->session_id_length = sesslen; *psess = sess; s->tlsext_ticket_expected = renew_ticket; return 1; } /* If session decrypt failure indicate a cache miss and set state to * send a new ticket */ tickerr: s->tlsext_ticket_expected = 1; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Add and use a constant-time memcmp. This change adds CRYPTO_memcmp, which compares two vectors of bytes in an amount of time that's independent of their contents. It also changes several MAC compares in the code to use this over the standard memcmp, which may leak information about the size of a matching prefix. (cherry picked from commit 2ee798880a246d648ecddadc5b91367bee4a5d98) Conflicts: crypto/crypto.h ssl/t1_lib.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 SSL_library_init(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_cbc()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_cbc()); /* Not actually used for SSL/TLS but this makes PKCS#12 work * if an application only calls SSL_library_init(). */ EVP_add_cipher(EVP_rc2_40_cbc()); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_256_cbc()); #endif #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_256_cbc()); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_cbc()); #endif #ifndef OPENSSL_NO_MD5 EVP_add_digest(EVP_md5()); EVP_add_digest_alias(SN_md5,"ssl2-md5"); EVP_add_digest_alias(SN_md5,"ssl3-md5"); #endif #ifndef OPENSSL_NO_SHA EVP_add_digest(EVP_sha1()); /* RSA with sha1 */ EVP_add_digest_alias(SN_sha1,"ssl3-sha1"); EVP_add_digest_alias(SN_sha1WithRSAEncryption,SN_sha1WithRSA); #endif #ifndef OPENSSL_NO_SHA256 EVP_add_digest(EVP_sha224()); EVP_add_digest(EVP_sha256()); #endif #ifndef OPENSSL_NO_SHA512 EVP_add_digest(EVP_sha384()); EVP_add_digest(EVP_sha512()); #endif #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_DSA) EVP_add_digest(EVP_dss1()); /* DSA with sha1 */ EVP_add_digest_alias(SN_dsaWithSHA1,SN_dsaWithSHA1_2); EVP_add_digest_alias(SN_dsaWithSHA1,"DSS1"); EVP_add_digest_alias(SN_dsaWithSHA1,"dss1"); #endif #ifndef OPENSSL_NO_ECDSA EVP_add_digest(EVP_ecdsa()); #endif /* If you want support for phased out ciphers, add the following */ #if 0 EVP_add_digest(EVP_sha()); EVP_add_digest(EVP_dss()); #endif #ifndef OPENSSL_NO_COMP /* This will initialise the built-in compression algorithms. The value returned is a STACK_OF(SSL_COMP), but that can be discarded safely */ (void)SSL_COMP_get_compression_methods(); #endif /* initialize cipher/digest methods table */ ssl_load_ciphers(); return(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Fixups from previous commit.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: 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; rr->orig_len=rr->length; 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': 'Update DTLS code to match CBC decoding in TLS. This change updates the DTLS code to match the constant-time CBC behaviour in the TLS. (cherry picked from commit 9f27de170d1b7bef3d46d41382dc4dafde8b3900)'</s>
<s>[INST] Given the following code containing errors, provide 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 OpenSSL_add_all_ciphers(void) { #ifndef OPENSSL_NO_DES EVP_add_cipher(EVP_des_cfb()); EVP_add_cipher(EVP_des_cfb1()); EVP_add_cipher(EVP_des_cfb8()); EVP_add_cipher(EVP_des_ede_cfb()); EVP_add_cipher(EVP_des_ede3_cfb()); EVP_add_cipher(EVP_des_ede3_cfb1()); EVP_add_cipher(EVP_des_ede3_cfb8()); EVP_add_cipher(EVP_des_ofb()); EVP_add_cipher(EVP_des_ede_ofb()); EVP_add_cipher(EVP_des_ede3_ofb()); EVP_add_cipher(EVP_desx_cbc()); EVP_add_cipher_alias(SN_desx_cbc,"DESX"); EVP_add_cipher_alias(SN_desx_cbc,"desx"); EVP_add_cipher(EVP_des_cbc()); EVP_add_cipher_alias(SN_des_cbc,"DES"); EVP_add_cipher_alias(SN_des_cbc,"des"); EVP_add_cipher(EVP_des_ede_cbc()); EVP_add_cipher(EVP_des_ede3_cbc()); EVP_add_cipher_alias(SN_des_ede3_cbc,"DES3"); EVP_add_cipher_alias(SN_des_ede3_cbc,"des3"); EVP_add_cipher(EVP_des_ecb()); EVP_add_cipher(EVP_des_ede()); EVP_add_cipher(EVP_des_ede3()); #endif #ifndef OPENSSL_NO_RC4 EVP_add_cipher(EVP_rc4()); EVP_add_cipher(EVP_rc4_40()); #ifndef OPENSSL_NO_MD5 EVP_add_cipher(EVP_rc4_hmac_md5()); #endif #endif #ifndef OPENSSL_NO_IDEA EVP_add_cipher(EVP_idea_ecb()); EVP_add_cipher(EVP_idea_cfb()); EVP_add_cipher(EVP_idea_ofb()); EVP_add_cipher(EVP_idea_cbc()); EVP_add_cipher_alias(SN_idea_cbc,"IDEA"); EVP_add_cipher_alias(SN_idea_cbc,"idea"); #endif #ifndef OPENSSL_NO_SEED EVP_add_cipher(EVP_seed_ecb()); EVP_add_cipher(EVP_seed_cfb()); EVP_add_cipher(EVP_seed_ofb()); EVP_add_cipher(EVP_seed_cbc()); EVP_add_cipher_alias(SN_seed_cbc,"SEED"); EVP_add_cipher_alias(SN_seed_cbc,"seed"); #endif #ifndef OPENSSL_NO_RC2 EVP_add_cipher(EVP_rc2_ecb()); EVP_add_cipher(EVP_rc2_cfb()); EVP_add_cipher(EVP_rc2_ofb()); EVP_add_cipher(EVP_rc2_cbc()); EVP_add_cipher(EVP_rc2_40_cbc()); EVP_add_cipher(EVP_rc2_64_cbc()); EVP_add_cipher_alias(SN_rc2_cbc,"RC2"); EVP_add_cipher_alias(SN_rc2_cbc,"rc2"); #endif #ifndef OPENSSL_NO_BF EVP_add_cipher(EVP_bf_ecb()); EVP_add_cipher(EVP_bf_cfb()); EVP_add_cipher(EVP_bf_ofb()); EVP_add_cipher(EVP_bf_cbc()); EVP_add_cipher_alias(SN_bf_cbc,"BF"); EVP_add_cipher_alias(SN_bf_cbc,"bf"); EVP_add_cipher_alias(SN_bf_cbc,"blowfish"); #endif #ifndef OPENSSL_NO_CAST EVP_add_cipher(EVP_cast5_ecb()); EVP_add_cipher(EVP_cast5_cfb()); EVP_add_cipher(EVP_cast5_ofb()); EVP_add_cipher(EVP_cast5_cbc()); EVP_add_cipher_alias(SN_cast5_cbc,"CAST"); EVP_add_cipher_alias(SN_cast5_cbc,"cast"); EVP_add_cipher_alias(SN_cast5_cbc,"CAST-cbc"); EVP_add_cipher_alias(SN_cast5_cbc,"cast-cbc"); #endif #ifndef OPENSSL_NO_RC5 EVP_add_cipher(EVP_rc5_32_12_16_ecb()); EVP_add_cipher(EVP_rc5_32_12_16_cfb()); EVP_add_cipher(EVP_rc5_32_12_16_ofb()); EVP_add_cipher(EVP_rc5_32_12_16_cbc()); EVP_add_cipher_alias(SN_rc5_cbc,"rc5"); EVP_add_cipher_alias(SN_rc5_cbc,"RC5"); #endif #ifndef OPENSSL_NO_AES EVP_add_cipher(EVP_aes_128_ecb()); EVP_add_cipher(EVP_aes_128_cbc()); EVP_add_cipher(EVP_aes_128_cfb()); EVP_add_cipher(EVP_aes_128_cfb1()); EVP_add_cipher(EVP_aes_128_cfb8()); EVP_add_cipher(EVP_aes_128_ofb()); EVP_add_cipher(EVP_aes_128_ctr()); EVP_add_cipher(EVP_aes_128_gcm()); EVP_add_cipher(EVP_aes_128_xts()); EVP_add_cipher_alias(SN_aes_128_cbc,"AES128"); EVP_add_cipher_alias(SN_aes_128_cbc,"aes128"); EVP_add_cipher(EVP_aes_192_ecb()); EVP_add_cipher(EVP_aes_192_cbc()); EVP_add_cipher(EVP_aes_192_cfb()); EVP_add_cipher(EVP_aes_192_cfb1()); EVP_add_cipher(EVP_aes_192_cfb8()); EVP_add_cipher(EVP_aes_192_ofb()); EVP_add_cipher(EVP_aes_192_ctr()); EVP_add_cipher(EVP_aes_192_gcm()); EVP_add_cipher_alias(SN_aes_192_cbc,"AES192"); EVP_add_cipher_alias(SN_aes_192_cbc,"aes192"); EVP_add_cipher(EVP_aes_256_ecb()); EVP_add_cipher(EVP_aes_256_cbc()); EVP_add_cipher(EVP_aes_256_cfb()); EVP_add_cipher(EVP_aes_256_cfb1()); EVP_add_cipher(EVP_aes_256_cfb8()); EVP_add_cipher(EVP_aes_256_ofb()); EVP_add_cipher(EVP_aes_256_ctr()); EVP_add_cipher(EVP_aes_256_gcm()); EVP_add_cipher(EVP_aes_256_xts()); EVP_add_cipher_alias(SN_aes_256_cbc,"AES256"); EVP_add_cipher_alias(SN_aes_256_cbc,"aes256"); #if 0 /* Disabled because of timing side-channel leaks. */ #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) EVP_add_cipher(EVP_aes_128_cbc_hmac_sha1()); EVP_add_cipher(EVP_aes_256_cbc_hmac_sha1()); #endif #endif #endif #ifndef OPENSSL_NO_CAMELLIA EVP_add_cipher(EVP_camellia_128_ecb()); EVP_add_cipher(EVP_camellia_128_cbc()); EVP_add_cipher(EVP_camellia_128_cfb()); EVP_add_cipher(EVP_camellia_128_cfb1()); EVP_add_cipher(EVP_camellia_128_cfb8()); EVP_add_cipher(EVP_camellia_128_ofb()); EVP_add_cipher_alias(SN_camellia_128_cbc,"CAMELLIA128"); EVP_add_cipher_alias(SN_camellia_128_cbc,"camellia128"); EVP_add_cipher(EVP_camellia_192_ecb()); EVP_add_cipher(EVP_camellia_192_cbc()); EVP_add_cipher(EVP_camellia_192_cfb()); EVP_add_cipher(EVP_camellia_192_cfb1()); EVP_add_cipher(EVP_camellia_192_cfb8()); EVP_add_cipher(EVP_camellia_192_ofb()); EVP_add_cipher_alias(SN_camellia_192_cbc,"CAMELLIA192"); EVP_add_cipher_alias(SN_camellia_192_cbc,"camellia192"); EVP_add_cipher(EVP_camellia_256_ecb()); EVP_add_cipher(EVP_camellia_256_cbc()); EVP_add_cipher(EVP_camellia_256_cfb()); EVP_add_cipher(EVP_camellia_256_cfb1()); EVP_add_cipher(EVP_camellia_256_cfb8()); EVP_add_cipher(EVP_camellia_256_ofb()); EVP_add_cipher_alias(SN_camellia_256_cbc,"CAMELLIA256"); EVP_add_cipher_alias(SN_camellia_256_cbc,"camellia256"); #endif } ; 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: rsvg_handle_set_base_uri (RsvgHandle * handle, const char *base_uri) { gchar *uri; g_return_if_fail (handle != NULL); if (base_uri == NULL) return; if (rsvg_path_is_uri (base_uri)) uri = g_strdup (base_uri); else uri = rsvg_get_base_uri_from_filename (base_uri); if (uri) { if (handle->priv->base_uri) g_free (handle->priv->base_uri); handle->priv->base_uri = uri; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'io: Implement strict load policy Allow any file to load from data:, and any resource to load from other resources. Only allow file: to load other file: URIs from below the path of the base file. Any other loads are denied. Bug #691708.'</s>
<s>[INST] Given the following code containing errors, provide 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_do_change_cipher_spec(SSL *s) { int i; const char *sender; int slen; if (s->state & SSL_ST_ACCEPT) i=SSL3_CHANGE_CIPHER_SERVER_READ; else i=SSL3_CHANGE_CIPHER_CLIENT_READ; if (s->s3->tmp.key_block == NULL) { if (s->session == NULL) { /* might happen if dtls1_read_bytes() calls this */ SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,SSL_R_CCS_RECEIVED_EARLY); return (0); } s->session->cipher=s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) return(0); } if (!s->method->ssl3_enc->change_cipher_state(s,i)) return(0); /* we have to record the message digest at * this point so we can get it before we read * the finished message */ if (s->state & SSL_ST_CONNECT) { sender=s->method->ssl3_enc->server_finished_label; slen=s->method->ssl3_enc->server_finished_label_len; } else { sender=s->method->ssl3_enc->client_finished_label; slen=s->method->ssl3_enc->client_finished_label_len; } i = s->method->ssl3_enc->final_finish_mac(s, sender,slen,s->s3->tmp.peer_finish_md); if (i == 0) { SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR); return 0; } s->s3->tmp.peer_finish_md_len = i; return(1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-326'], 'message': 'Additional CVE-2014-0224 protection. Return a fatal error if an attempt is made to use a zero length master secret.'</s>
<s>[INST] Given the following code containing errors, provide 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 (p[4] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; s->state=SSL23_ST_SR_CLNT_HELLO_B; } else if (p[4] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; /* type=2; */ /* done later to survive restarts */ s->state=SSL23_ST_SR_CLNT_HELLO_B; } else 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 (v[1] >= TLS1_2_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_2)) { s->version=TLS1_2_VERSION; type=3; } else if (v[1] >= TLS1_1_VERSION_MINOR && !(s->options & SSL_OP_NO_TLSv1_1)) { s->version=TLS1_1_VERSION; type=3; } else 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; } } if (s->version < TLS1_2_VERSION && tls1_suiteb(s)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, SSL_R_ONLY_TLS_1_2_ALLOWED_IN_SUITEB_MODE); 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 if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_VERSION_TOO_LOW); goto err; } 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) /* We can't have TLS extensions in SSL 2.0 format * Client Hello, can we? Error condition should be * '>' otherweise */ { 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; #if 0 /* copy any remaining data with may be extensions */ p = p+csl+sil+cl; while (p < s->packet+s->packet_length) { *(d++)=*(p++); } #endif 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; if (s->s3->rbuf.buf == NULL) if (!ssl3_setup_read_buffer(s)) goto err; 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_2_VERSION) s->method = TLSv1_2_server_method(); else if (s->version == TLS1_1_VERSION) s->method = TLSv1_1_server_method(); else 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': '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: long ssl3_ctrl(SSL *s, int cmd, long larg, void *parg) { int ret=0; #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_RSA) if ( #ifndef OPENSSL_NO_RSA cmd == SSL_CTRL_SET_TMP_RSA || cmd == SSL_CTRL_SET_TMP_RSA_CB || #endif #ifndef OPENSSL_NO_DSA cmd == SSL_CTRL_SET_TMP_DH || cmd == SSL_CTRL_SET_TMP_DH_CB || #endif 0) { if (!ssl_cert_inst(&s->cert)) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_MALLOC_FAILURE); return(0); } } #endif switch (cmd) { case SSL_CTRL_GET_SESSION_REUSED: ret=s->hit; break; case SSL_CTRL_GET_CLIENT_CERT_REQUEST: break; case SSL_CTRL_GET_NUM_RENEGOTIATIONS: ret=s->s3->num_renegotiations; break; case SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS: ret=s->s3->num_renegotiations; s->s3->num_renegotiations=0; break; case SSL_CTRL_GET_TOTAL_RENEGOTIATIONS: ret=s->s3->total_renegotiations; break; case SSL_CTRL_GET_FLAGS: ret=(int)(s->s3->flags); break; #ifndef OPENSSL_NO_RSA case SSL_CTRL_NEED_TMP_RSA: if ((s->cert != NULL) && (s->cert->rsa_tmp == NULL) && ((s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || (EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512/8)))) ret = 1; break; case SSL_CTRL_SET_TMP_RSA: { RSA *rsa = (RSA *)parg; if (rsa == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return(ret); } if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_RSA_LIB); return(ret); } if (s->cert->rsa_tmp != NULL) RSA_free(s->cert->rsa_tmp); s->cert->rsa_tmp = rsa; ret = 1; } break; case SSL_CTRL_SET_TMP_RSA_CB: { SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return(ret); } break; #endif #ifndef OPENSSL_NO_DH case SSL_CTRL_SET_TMP_DH: { DH *dh = (DH *)parg; if (dh == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return(ret); } if ((dh = DHparams_dup(dh)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return(ret); } if (!(s->options & SSL_OP_SINGLE_DH_USE)) { if (!DH_generate_key(dh)) { DH_free(dh); SSLerr(SSL_F_SSL3_CTRL, ERR_R_DH_LIB); return(ret); } } if (s->cert->dh_tmp != NULL) DH_free(s->cert->dh_tmp); s->cert->dh_tmp = dh; ret = 1; } break; case SSL_CTRL_SET_TMP_DH_CB: { SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return(ret); } break; #endif #ifndef OPENSSL_NO_ECDH case SSL_CTRL_SET_TMP_ECDH: { EC_KEY *ecdh = NULL; if (parg == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_PASSED_NULL_PARAMETER); return(ret); } if (!EC_KEY_up_ref((EC_KEY *)parg)) { SSLerr(SSL_F_SSL3_CTRL,ERR_R_ECDH_LIB); return(ret); } ecdh = (EC_KEY *)parg; if (!(s->options & SSL_OP_SINGLE_ECDH_USE)) { if (!EC_KEY_generate_key(ecdh)) { EC_KEY_free(ecdh); SSLerr(SSL_F_SSL3_CTRL,ERR_R_ECDH_LIB); return(ret); } } if (s->cert->ecdh_tmp != NULL) EC_KEY_free(s->cert->ecdh_tmp); s->cert->ecdh_tmp = ecdh; ret = 1; } break; case SSL_CTRL_SET_TMP_ECDH_CB: { SSLerr(SSL_F_SSL3_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return(ret); } break; #endif /* !OPENSSL_NO_ECDH */ #ifndef OPENSSL_NO_TLSEXT case SSL_CTRL_SET_TLSEXT_HOSTNAME: if (larg == TLSEXT_NAMETYPE_host_name) { if (s->tlsext_hostname != NULL) OPENSSL_free(s->tlsext_hostname); s->tlsext_hostname = NULL; ret = 1; if (parg == NULL) break; if (strlen((char *)parg) > TLSEXT_MAXLEN_host_name) { SSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME); return 0; } if ((s->tlsext_hostname = BUF_strdup((char *)parg)) == NULL) { SSLerr(SSL_F_SSL3_CTRL, ERR_R_INTERNAL_ERROR); return 0; } } else { SSLerr(SSL_F_SSL3_CTRL, SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE); return 0; } break; case SSL_CTRL_SET_TLSEXT_DEBUG_ARG: s->tlsext_debug_arg=parg; ret = 1; break; case SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE: s->tlsext_status_type=larg; ret = 1; break; case SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS: *(STACK_OF(X509_EXTENSION) **)parg = s->tlsext_ocsp_exts; ret = 1; break; case SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS: s->tlsext_ocsp_exts = parg; ret = 1; break; case SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS: *(STACK_OF(OCSP_RESPID) **)parg = s->tlsext_ocsp_ids; ret = 1; break; case SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS: s->tlsext_ocsp_ids = parg; ret = 1; break; case SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP: *(unsigned char **)parg = s->tlsext_ocsp_resp; return s->tlsext_ocsp_resplen; case SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP: if (s->tlsext_ocsp_resp) OPENSSL_free(s->tlsext_ocsp_resp); s->tlsext_ocsp_resp = parg; s->tlsext_ocsp_resplen = larg; ret = 1; break; #endif /* !OPENSSL_NO_TLSEXT */ default: break; } return(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_parse_clienthello_use_srtp_ext(SSL *s, unsigned char *d, int len,int *al) { SRTP_PROTECTION_PROFILE *cprof,*sprof; STACK_OF(SRTP_PROTECTION_PROFILE) *clnt=0,*srvr; int ct; int mki_len; int i,j; int id; int ret; /* Length value + the MKI length */ if(len < 3) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST); *al=SSL_AD_DECODE_ERROR; return 1; } /* Pull off the length of the cipher suite list */ n2s(d, ct); len -= 2; /* Check that it is even */ if(ct%2) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST); *al=SSL_AD_DECODE_ERROR; return 1; } /* Check that lengths are consistent */ if(len < (ct + 1)) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST); *al=SSL_AD_DECODE_ERROR; return 1; } clnt=sk_SRTP_PROTECTION_PROFILE_new_null(); while(ct) { n2s(d,id); ct-=2; len-=2; if(!find_profile_by_num(id,&cprof)) { sk_SRTP_PROTECTION_PROFILE_push(clnt,cprof); } else { ; /* Ignore */ } } /* Now extract the MKI value as a sanity check, but discard it for now */ mki_len = *d; d++; len--; if (mki_len != len) { SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT,SSL_R_BAD_SRTP_MKI_VALUE); *al=SSL_AD_DECODE_ERROR; return 1; } srvr=SSL_get_srtp_profiles(s); /* Pick our most preferred profile. If no profiles have been configured then the outer loop doesn't run (sk_SRTP_PROTECTION_PROFILE_num() = -1) and so we just return without doing anything */ for(i=0;i<sk_SRTP_PROTECTION_PROFILE_num(srvr);i++) { sprof=sk_SRTP_PROTECTION_PROFILE_value(srvr,i); for(j=0;j<sk_SRTP_PROTECTION_PROFILE_num(clnt);j++) { cprof=sk_SRTP_PROTECTION_PROFILE_value(clnt,j); if(cprof->id==sprof->id) { s->srtp_profile=sprof; *al=0; ret=0; goto done; } } } ret=0; done: if(clnt) sk_SRTP_PROTECTION_PROFILE_free(clnt); return ret; } ; 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: static const SSL_METHOD *ssl23_get_server_method(int ver) { #ifndef OPENSSL_NO_SSL2 if (ver == SSL2_VERSION) return(SSLv2_server_method()); #endif if (ver == SSL3_VERSION) return(SSLv3_server_method()); else if (ver == TLS1_VERSION) return(TLSv1_server_method()); else if (ver == TLS1_1_VERSION) return(TLSv1_1_server_method()); else if (ver == TLS1_2_VERSION) return(TLSv1_2_server_method()); else return(NULL); } ; 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_accept(SSL *s) { BUF_MEM *buf; unsigned long alg_k,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); } #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch (s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=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; } if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW); 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)) { BUF_MEM_free(buf); ret= -1; goto end; } s->init_buf=buf; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } s->init_num=0; s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; s->s3->flags &= ~SSL3_FLAGS_CCS_OK; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; 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: ret=ssl3_get_client_hello(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SRP s->state = SSL3_ST_SR_CLNT_HELLO_D; case SSL3_ST_SR_CLNT_HELLO_D: { int al; if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0) { /* callback indicates firther work to be done */ s->rwstate=SSL_X509_LOOKUP; goto end; } if (ret != SSL_ERROR_NONE) { ssl3_send_alert(s,SSL3_AL_FATAL,al); /* This is not really an error but the only means to for a client to detect whether srp is supported. */ if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT); ret = SSL_TLSEXT_ERR_ALERT_FATAL; ret= -1; goto end; } } #endif s->renegotiate = 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, */ /* normal PSK or KRB5 or SRP */ if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { 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: alg_k = s->s3->tmp.new_cipher->algorithm_mkey; /* clear this, it may get reset by * send_server_key_exchange */ if ((s->options & SSL_OP_EPHEMERAL_RSA) #ifndef OPENSSL_NO_KRB5 && !(alg_k & SSL_kKRB5) #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 * * PSK: may send PSK identity hints * * 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 /* PSK: send ServerKeyExchange if PSK identity * hint if provided */ #ifndef OPENSSL_NO_PSK || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) #endif #ifndef OPENSSL_NO_SRP /* SRP: send ServerKeyExchange */ || (alg_k & SSL_kSRP) #endif || (alg_k & SSL_kDHE) || (alg_k & SSL_kECDHE) || ((alg_k & 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->algorithm_auth & 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->algorithm_auth & SSL_aKRB5) || /* don't request certificate for SRP auth */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) /* With normal PSK Certificates and * Certificate Requests are omitted */ || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { /* no cert request */ skip=1; s->s3->tmp.cert_request=0; s->state=SSL3_ST_SW_SRVR_DONE_A; if (s->s3->handshake_buffer) if (!ssl3_digest_cached_records(s)) return -1; } 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: 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. * Also for GOST ciphersuites when * the client uses its key from the certificate * for key exchange. */ #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_SR_NEXT_PROTO_A; else s->state=SSL3_ST_SR_FINISHED_A; #endif s->init_num = 0; } else if (SSL_USE_SIGALGS(s)) { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; if (!s->session->peer) break; /* For sigalgs freeze the handshake buffer * at this point and digest cached records. */ if (!s->s3->handshake_buffer) { SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR); return -1; } s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; if (!ssl3_digest_cached_records(s)) return -1; } else { int offset=0; int dgst_num; 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 * FIXME - digest processing for CertificateVerify * should be generalized. But it is next step */ if (s->s3->handshake_buffer) if (!ssl3_digest_cached_records(s)) return -1; for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++) if (s->s3->handshake_dgst[dgst_num]) { int dgst_size; s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset])); dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); if (dgst_size < 0) { ret = -1; goto end; } offset+=dgst_size; } } break; case SSL3_ST_SR_CERT_VRFY_A: case SSL3_ST_SR_CERT_VRFY_B: /* * This *should* be the first time we enable CCS, but be * extra careful about surrounding code changes. We need * to set this here because we don't know if we're * expecting a CertificateVerify or not. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; /* we should decide if we expected this one */ ret=ssl3_get_cert_verify(s); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_SR_NEXT_PROTO_A; else s->state=SSL3_ST_SR_FINISHED_A; #endif s->init_num=0; break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_SR_NEXT_PROTO_A: case SSL3_ST_SR_NEXT_PROTO_B: /* * Enable CCS for resumed handshakes with NPN. * In a full handshake with NPN, we end up here through * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_next_proto(s); if (ret <= 0) goto end; s->init_num = 0; s->state=SSL3_ST_SR_FINISHED_A; break; #endif case SSL3_ST_SR_FINISHED_A: case SSL3_ST_SR_FINISHED_B: /* * Enable CCS for resumed handshakes without NPN. * In a full handshake, we end up here through * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; 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) { #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) { s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A; } else s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #endif } 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->renegotiate == 2) /* skipped if we just sent a HelloRequest */ { s->renegotiate=0; 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-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>'</s>
<s>[INST] Given the following code containing errors, provide 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_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *p,*buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (type == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } inl=i2d(data,NULL); buf_in=OPENSSL_malloc((unsigned int)inl); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } p=buf_in; i2d(data,&p); ret= EVP_VerifyInit_ex(&ctx,type, NULL) && EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } ; 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: int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) { ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'use correct function name Reviewed-by: Rich Salz <rsalz@openssl.org> Reviewed-by: Matt Caswell <matt@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) { r[ 8]=bn_mul_words( &(r[0]),a,8,b[0]); r[ 9]=bn_mul_add_words(&(r[1]),a,8,b[1]); r[10]=bn_mul_add_words(&(r[2]),a,8,b[2]); r[11]=bn_mul_add_words(&(r[3]),a,8,b[3]); r[12]=bn_mul_add_words(&(r[4]),a,8,b[4]); r[13]=bn_mul_add_words(&(r[5]),a,8,b[5]); r[14]=bn_mul_add_words(&(r[6]),a,8,b[6]); r[15]=bn_mul_add_words(&(r[7]),a,8,b[7]); } ; 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_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { r[4]=bn_mul_words( &(r[0]),a,4,b[0]); r[5]=bn_mul_add_words(&(r[1]),a,4,b[1]); r[6]=bn_mul_add_words(&(r[2]),a,4,b[2]); r[7]=bn_mul_add_words(&(r[3]),a,4,b[3]); } ; 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 ssl3_get_new_session_ticket(SSL *s) { int ok, al, ret = 0, ticklen; long n; const unsigned char *p; unsigned char *d; n = s->method->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B, SSL3_MT_NEWSESSION_TICKET, 16384, &ok); if (!ok) return ((int)n); if (n < 6) { /* need at least ticket_lifetime_hint + ticket length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH); goto f_err; } p = d = (unsigned char *)s->init_msg; n2l(p, s->session->tlsext_tick_lifetime_hint); n2s(p, ticklen); /* ticket_lifetime_hint + ticket_length + ticket */ if (ticklen + 6 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, SSL_R_LENGTH_MISMATCH); goto f_err; } if (s->session->tlsext_tick) { OPENSSL_free(s->session->tlsext_tick); s->session->tlsext_ticklen = 0; } s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) { SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->session->tlsext_tick, p, ticklen); s->session->tlsext_ticklen = ticklen; /* * There are two ways to detect a resumed ticket session. One is to set * an appropriate session ID and then the server must return a match in * ServerHello. This allows the normal client session ID matching to work * and we know much earlier that the ticket has been accepted. The * other way is to set zero length session ID when the ticket is * presented and rely on the handshake to determine session resumption. * We choose the former approach because this fits in with assumptions * elsewhere in OpenSSL. The session ID is set to the SHA256 (or SHA1 is * SHA256 is disabled) hash of the ticket. */ EVP_Digest(p, ticklen, s->session->session_id, &s->session->session_id_length, # ifndef OPENSSL_NO_SHA256 EVP_sha256(), NULL); # else EVP_sha1(), NULL); # endif ret = 1; return (ret); f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; return (-1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'Fix race condition in NewSessionTicket If a NewSessionTicket is received by a multi-threaded client when attempting to reuse a previous ticket then a race condition can occur potentially leading to a double free of the ticket data. CVE-2015-1791 This also fixes RT#3808 where a session ID is changed for a session already in the client session cache. Since the session ID is the key to the cache this breaks the cache access. Parts of this patch were inspired by this Akamai change: https://github.com/akamai/openssl/commit/c0bf69a791239ceec64509f9f19fcafb2461b0d3 Reviewed-by: Rich Salz <rsalz@openssl.org> (cherry picked from commit 27c76b9b8010b536687318739c6f631ce4194688) Conflicts: ssl/ssl.h ssl/ssl_err.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: static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx) { int flags, aclass; int ret; const unsigned char *p, *q; if (!val) return 0; flags = tt->flags; aclass = flags & ASN1_TFLG_TAG_CLASS; p = *in; q = p; if (flags & ASN1_TFLG_SK_MASK) { /* SET OF, SEQUENCE OF */ int sktag, skaclass; char sk_eoc; /* First work out expected inner tag value */ if (flags & ASN1_TFLG_IMPTAG) { sktag = tt->tag; skaclass = aclass; } else { skaclass = V_ASN1_UNIVERSAL; if (flags & ASN1_TFLG_SET_OF) sktag = V_ASN1_SET; else sktag = V_ASN1_SEQUENCE; } /* Get the tag */ ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL, &p, len, sktag, skaclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR); return 0; } else if (ret == -1) return -1; if (!*val) *val = (ASN1_VALUE *)sk_new_null(); else { /* * We've got a valid STACK: free up any items present */ STACK *sktmp = (STACK *) * val; ASN1_VALUE *vtmp; while (sk_num(sktmp) > 0) { vtmp = (ASN1_VALUE *)sk_pop(sktmp); ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item)); } } if (!*val) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE); goto err; } /* Read as many items as we can */ while (len > 0) { ASN1_VALUE *skfield; q = p; /* See if EOC found */ if (asn1_check_eoc(&p, len)) { if (!sk_eoc) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ASN1_R_UNEXPECTED_EOC); goto err; } len -= p - q; sk_eoc = 0; break; } skfield = NULL; if (!ASN1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx)) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } len -= p - q; if (!sk_push((STACK *) * val, (char *)skfield)) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE); goto err; } } if (sk_eoc) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ASN1_R_MISSING_EOC); goto err; } } else if (flags & ASN1_TFLG_IMPTAG) { /* IMPLICIT tagging */ ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; } else { /* Nothing special */ ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), -1, 0, opt, ctx); if (!ret) { ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR); goto err; } else if (ret == -1) return -1; } *in = p; return 1; err: ASN1_template_free(val, tt); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'Fix leak with ASN.1 combine. When parsing a combined structure pass a flag to the decode routine so on error a pointer to the parent structure is not zeroed as this will leak any additional components in the parent. This can leak memory in any application parsing PKCS#7 or CMS structures. CVE-2015-3195. Thanks to Adam Langley (Google/BoringSSL) for discovering this bug using libFuzzer. PR#4131 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: static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top, unsigned char *buf, int idx, int width) { size_t i, j; if (top > b->top) top = b->top; /* this works because 'buf' is explicitly * zeroed */ for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) { buf[j] = ((unsigned char *)b->d)[i]; } 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: static int rev_body(int s, int stype, unsigned char *context) { char *buf = NULL; int i; int ret = 1; SSL *con; BIO *io, *ssl_bio, *sbio; buf = app_malloc(bufsize, "server rev buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; /* lets make the output buffer a reasonable size */ if (!BIO_set_write_buffer_size(io, bufsize)) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context && !SSL_set_session_id_context(con, context, strlen((char *)context))) { ERR_print_errors(bio_err); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); #ifdef CHARSET_EBCDIC io = BIO_push(BIO_new(BIO_f_ebcdic_filter()), io); #endif if (s_debug) { BIO_set_callback(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_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_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_do_handshake(io); if (i > 0) break; if (!BIO_should_retry(io)) { BIO_puts(bio_err, "CONNECTION FAILURE\n"); ERR_print_errors(bio_err); goto end; } #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during accept\n"); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); continue; } #endif } BIO_printf(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(con); for (;;) { i = BIO_gets(io, buf, bufsize - 1); if (i < 0) { /* error */ if (!BIO_should_retry(io)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); srp_callback_parm.user = SRP_VBASE_get_by_user(srp_callback_parm.vb, srp_callback_parm.login); if (srp_callback_parm.user) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm.user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); continue; } #endif #if defined(OPENSSL_SYS_NETWARE) delay(1000); #elif !defined(OPENSSL_SYS_MSDOS) sleep(1); #endif continue; } } else if (i == 0) { /* end of input */ ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } else { char *p = buf + i - 1; while (i && (*p == '\n' || *p == '\r')) { p--; i--; } if (!s_ign_eof && (i == 5) && (strncmp(buf, "CLOSE", 5) == 0)) { ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } BUF_reverse((unsigned char *)buf, NULL, i); buf[i] = '\n'; BIO_write(io, buf, i + 1); for (;;) { i = BIO_flush(io); if (i > 0) break; if (!BIO_should_retry(io)) goto end; } } } end: /* make sure we re-use sessions */ SSL_set_shutdown(con, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); err: OPENSSL_free(buf); BIO_free_all(io); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'CVE-2016-0798: avoid memory leak in SRP The SRP user database lookup method SRP_VBASE_get_by_user had confusing memory management semantics; the returned pointer was sometimes newly allocated, and sometimes owned by the callee. The calling code has no way of distinguishing these two cases. Specifically, SRP servers that configure a secret seed to hide valid login information are vulnerable to a memory leak: an attacker connecting with an invalid username can cause a memory leak of around 300 bytes per connection. Servers that do not configure SRP, or configure SRP but do not configure a seed are not vulnerable. In Apache, the seed directive is known as SSLSRPUnknownUserSeed. To mitigate the memory leak, the seed handling in SRP_VBASE_get_by_user is now disabled even if the user has configured a seed. Applications are advised to migrate to SRP_VBASE_get1_by_user. However, note that OpenSSL makes no strong guarantees about the indistinguishability of valid and invalid logins. In particular, computations are currently not carried out in constant time. 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: doapr_outch(char **sbuffer, char **buffer, size_t *currlen, size_t *maxlen, int c) { /* If we haven't at least one buffer, someone has doe a big booboo */ assert(*sbuffer != NULL || buffer != NULL); /* |currlen| must always be <= |*maxlen| */ assert(*currlen <= *maxlen); if (buffer && *currlen == *maxlen) { *maxlen += 1024; if (*buffer == NULL) { *buffer = OPENSSL_malloc(*maxlen); if (!*buffer) { /* Panic! Can't really do anything sensible. Just return */ return; } if (*currlen > 0) { assert(*sbuffer != NULL); memcpy(*buffer, *sbuffer, *currlen); } *sbuffer = NULL; } else { *buffer = OPENSSL_realloc(*buffer, *maxlen); if (!*buffer) { /* Panic! Can't really do anything sensible. Just return */ return; } } } if (*currlen < *maxlen) { if (*sbuffer) (*sbuffer)[(*currlen)++] = (char)c; else (*buffer)[(*currlen)++] = (char)c; } 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: static int aesni_cbc_hmac_sha1_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t len) { EVP_AES_HMAC_SHA1 *key = data(ctx); unsigned int l; size_t plen = key->payload_length, iv = 0, /* explicit IV in TLS 1.1 and * later */ sha_off = 0; # if defined(STITCHED_CALL) size_t aes_off = 0, blocks; sha_off = SHA_CBLOCK - key->md.num; # endif key->payload_length = NO_PAYLOAD_LENGTH; if (len % AES_BLOCK_SIZE) return 0; if (ctx->encrypt) { if (plen == NO_PAYLOAD_LENGTH) plen = len; else if (len != ((plen + SHA_DIGEST_LENGTH + AES_BLOCK_SIZE) & -AES_BLOCK_SIZE)) return 0; else if (key->aux.tls_ver >= TLS1_1_VERSION) iv = AES_BLOCK_SIZE; # if defined(STITCHED_CALL) if (plen > (sha_off + iv) && (blocks = (plen - (sha_off + iv)) / SHA_CBLOCK)) { SHA1_Update(&key->md, in + iv, sha_off); aesni_cbc_sha1_enc(in, out, blocks, &key->ks, ctx->iv, &key->md, in + iv + sha_off); blocks *= SHA_CBLOCK; aes_off += blocks; sha_off += blocks; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else { sha_off = 0; } # endif sha_off += iv; SHA1_Update(&key->md, in + sha_off, plen - sha_off); if (plen != len) { /* "TLS" mode of operation */ if (in != out) memcpy(out + aes_off, in + aes_off, plen - aes_off); /* calculate HMAC and append it to payload */ SHA1_Final(out + plen, &key->md); key->md = key->tail; SHA1_Update(&key->md, out + plen, SHA_DIGEST_LENGTH); SHA1_Final(out + plen, &key->md); /* pad the payload|hmac */ plen += SHA_DIGEST_LENGTH; for (l = len - plen - 1; plen < len; plen++) out[plen] = l; /* encrypt HMAC|padding at once */ aesni_cbc_encrypt(out + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } else { aesni_cbc_encrypt(in + aes_off, out + aes_off, len - aes_off, &key->ks, ctx->iv, 1); } } else { union { unsigned int u[SHA_DIGEST_LENGTH / sizeof(unsigned int)]; unsigned char c[32 + SHA_DIGEST_LENGTH]; } mac, *pmac; /* arrange cache line alignment */ pmac = (void *)(((size_t)mac.c + 31) & ((size_t)0 - 32)); if (plen != NO_PAYLOAD_LENGTH) { /* "TLS" mode of operation */ size_t inp_len, mask, j, i; unsigned int res, maxpad, pad, bitlen; int ret = 1; union { unsigned int u[SHA_LBLOCK]; unsigned char c[SHA_CBLOCK]; } *data = (void *)key->md.data; # if defined(STITCHED_DECRYPT_CALL) unsigned char tail_iv[AES_BLOCK_SIZE]; int stitch = 0; # endif if ((key->aux.tls_aad[plen - 4] << 8 | key->aux.tls_aad[plen - 3]) >= TLS1_1_VERSION) { if (len < (AES_BLOCK_SIZE + SHA_DIGEST_LENGTH + 1)) return 0; /* omit explicit iv */ memcpy(ctx->iv, in, AES_BLOCK_SIZE); in += AES_BLOCK_SIZE; out += AES_BLOCK_SIZE; len -= AES_BLOCK_SIZE; } else if (len < (SHA_DIGEST_LENGTH + 1)) return 0; # if defined(STITCHED_DECRYPT_CALL) if (len >= 1024 && ctx->key_len == 32) { /* decrypt last block */ memcpy(tail_iv, in + len - 2 * AES_BLOCK_SIZE, AES_BLOCK_SIZE); aesni_cbc_encrypt(in + len - AES_BLOCK_SIZE, out + len - AES_BLOCK_SIZE, AES_BLOCK_SIZE, &key->ks, tail_iv, 0); stitch = 1; } else # endif /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); /* figure out payload length */ pad = out[len - 1]; maxpad = len - (SHA_DIGEST_LENGTH + 1); maxpad |= (255 - maxpad) >> (sizeof(maxpad) * 8 - 8); maxpad &= 255; inp_len = len - (SHA_DIGEST_LENGTH + pad + 1); mask = (0 - ((inp_len - len) >> (sizeof(inp_len) * 8 - 1))); inp_len &= mask; ret &= (int)mask; key->aux.tls_aad[plen - 2] = inp_len >> 8; key->aux.tls_aad[plen - 1] = inp_len; /* calculate HMAC */ key->md = key->head; SHA1_Update(&key->md, key->aux.tls_aad, plen); # if defined(STITCHED_DECRYPT_CALL) if (stitch) { blocks = (len - (256 + 32 + SHA_CBLOCK)) / SHA_CBLOCK; aes_off = len - AES_BLOCK_SIZE - blocks * SHA_CBLOCK; sha_off = SHA_CBLOCK - plen; aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0); SHA1_Update(&key->md, out, sha_off); aesni256_cbc_sha1_dec(in + aes_off, out + aes_off, blocks, &key->ks, ctx->iv, &key->md, out + sha_off); sha_off += blocks *= SHA_CBLOCK; out += sha_off; len -= sha_off; inp_len -= sha_off; key->md.Nl += (blocks << 3); /* at most 18 bits */ memcpy(ctx->iv, tail_iv, AES_BLOCK_SIZE); } # endif # if 1 len -= SHA_DIGEST_LENGTH; /* amend mac */ if (len >= (256 + SHA_CBLOCK)) { j = (len - (256 + SHA_CBLOCK)) & (0 - SHA_CBLOCK); j += SHA_CBLOCK - key->md.num; SHA1_Update(&key->md, out, j); out += j; len -= j; inp_len -= j; } /* but pretend as if we hashed padded payload */ bitlen = key->md.Nl + (inp_len << 3); /* at most 18 bits */ # ifdef BSWAP4 bitlen = BSWAP4(bitlen); # else mac.c[0] = 0; mac.c[1] = (unsigned char)(bitlen >> 16); mac.c[2] = (unsigned char)(bitlen >> 8); mac.c[3] = (unsigned char)bitlen; bitlen = mac.u[0]; # endif pmac->u[0] = 0; pmac->u[1] = 0; pmac->u[2] = 0; pmac->u[3] = 0; pmac->u[4] = 0; for (res = key->md.num, j = 0; j < len; j++) { size_t c = out[j]; mask = (j - inp_len) >> (sizeof(j) * 8 - 8); c &= mask; c |= 0x80 & ~mask & ~((inp_len - j) >> (sizeof(j) * 8 - 8)); data->c[res++] = (unsigned char)c; if (res != SHA_CBLOCK) continue; /* j is not incremented yet */ mask = 0 - ((inp_len + 7 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha1_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 72) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; res = 0; } for (i = res; i < SHA_CBLOCK; i++, j++) data->c[i] = 0; if (res > SHA_CBLOCK - 8) { mask = 0 - ((inp_len + 8 - j) >> (sizeof(j) * 8 - 1)); data->u[SHA_LBLOCK - 1] |= bitlen & mask; sha1_block_data_order(&key->md, data, 1); mask &= 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; memset(data, 0, SHA_CBLOCK); j += 64; } data->u[SHA_LBLOCK - 1] = bitlen; sha1_block_data_order(&key->md, data, 1); mask = 0 - ((j - inp_len - 73) >> (sizeof(j) * 8 - 1)); pmac->u[0] |= key->md.h0 & mask; pmac->u[1] |= key->md.h1 & mask; pmac->u[2] |= key->md.h2 & mask; pmac->u[3] |= key->md.h3 & mask; pmac->u[4] |= key->md.h4 & mask; # ifdef BSWAP4 pmac->u[0] = BSWAP4(pmac->u[0]); pmac->u[1] = BSWAP4(pmac->u[1]); pmac->u[2] = BSWAP4(pmac->u[2]); pmac->u[3] = BSWAP4(pmac->u[3]); pmac->u[4] = BSWAP4(pmac->u[4]); # else for (i = 0; i < 5; i++) { res = pmac->u[i]; pmac->c[4 * i + 0] = (unsigned char)(res >> 24); pmac->c[4 * i + 1] = (unsigned char)(res >> 16); pmac->c[4 * i + 2] = (unsigned char)(res >> 8); pmac->c[4 * i + 3] = (unsigned char)res; } # endif len += SHA_DIGEST_LENGTH; # else SHA1_Update(&key->md, out, inp_len); res = key->md.num; SHA1_Final(pmac->c, &key->md); { unsigned int inp_blocks, pad_blocks; /* but pretend as if we hashed padded payload */ inp_blocks = 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); res += (unsigned int)(len - inp_len); pad_blocks = res / SHA_CBLOCK; res %= SHA_CBLOCK; pad_blocks += 1 + ((SHA_CBLOCK - 9 - res) >> (sizeof(res) * 8 - 1)); for (; inp_blocks < pad_blocks; inp_blocks++) sha1_block_data_order(&key->md, data, 1); } # endif key->md = key->tail; SHA1_Update(&key->md, pmac->c, SHA_DIGEST_LENGTH); SHA1_Final(pmac->c, &key->md); /* verify HMAC */ out += inp_len; len -= inp_len; # if 1 { unsigned char *p = out + len - 1 - maxpad - SHA_DIGEST_LENGTH; size_t off = out - p; unsigned int c, cmask; maxpad += SHA_DIGEST_LENGTH; for (res = 0, i = 0, j = 0; j < maxpad; j++) { c = p[j]; cmask = ((int)(j - off - SHA_DIGEST_LENGTH)) >> (sizeof(int) * 8 - 1); res |= (c ^ pad) & ~cmask; /* ... and padding */ cmask &= ((int)(off - 1 - j)) >> (sizeof(int) * 8 - 1); res |= (c ^ pmac->c[i]) & cmask; i += 1 & cmask; } maxpad -= SHA_DIGEST_LENGTH; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; } # else for (res = 0, i = 0; i < SHA_DIGEST_LENGTH; i++) res |= out[i] ^ pmac->c[i]; res = 0 - ((0 - res) >> (sizeof(res) * 8 - 1)); ret &= (int)~res; /* verify padding */ pad = (pad & ~res) | (maxpad & res); out = out + len - 1 - pad; for (res = 0, i = 0; i < pad; i++) res |= out[i] ^ pad; res = (0 - res) >> (sizeof(res) * 8 - 1); ret &= (int)~res; # endif return ret; } else { # if defined(STITCHED_DECRYPT_CALL) if (len >= 1024 && ctx->key_len == 32) { if (sha_off %= SHA_CBLOCK) blocks = (len - 3 * SHA_CBLOCK) / SHA_CBLOCK; else blocks = (len - 2 * SHA_CBLOCK) / SHA_CBLOCK; aes_off = len - blocks * SHA_CBLOCK; aesni_cbc_encrypt(in, out, aes_off, &key->ks, ctx->iv, 0); SHA1_Update(&key->md, out, sha_off); aesni256_cbc_sha1_dec(in + aes_off, out + aes_off, blocks, &key->ks, ctx->iv, &key->md, out + sha_off); sha_off += blocks *= SHA_CBLOCK; out += sha_off; len -= sha_off; key->md.Nh += blocks >> 29; key->md.Nl += blocks <<= 3; if (key->md.Nl < (unsigned int)blocks) key->md.Nh++; } else # endif /* decrypt HMAC|padding at once */ aesni_cbc_encrypt(in, out, len, &key->ks, ctx->iv, 0); SHA1_Update(&key->md, out, len); } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-310'], 'message': 'Check that we have enough padding characters. Reviewed-by: Emilia Käsper <emilia@openssl.org> CVE-2016-2107 MR: #2572'</s>
<s>[INST] Given the following code containing errors, provide 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_mask_parse (const RsvgDefs * defs, const char *str) { char *name; name = rsvg_get_url_string (str); if (name) { RsvgNode *val; val = rsvg_defs_lookup (defs, name); g_free (name); if (val && RSVG_NODE_TYPE (val) == RSVG_NODE_TYPE_MASK) return val; } return NULL; } ; 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: CAMLprim value caml_blit_string(value s1, value ofs1, value s2, value ofs2, value n) { memmove(&Byte(s2, Long_val(ofs2)), &Byte(s1, Long_val(ofs1)), Int_val(n)); return Val_unit; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200'], 'message': 'fix PR#7003 and a few other bugs caused by misuse of Int_val git-svn-id: http://caml.inria.fr/svn/ocaml/trunk@16525 f963ae5c-01c2-4b8c-9fe0-0dff7051ff02'</s>
<s>[INST] Given the following code containing errors, provide 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_get_prev_session(SSL *s, unsigned char *session_id, int len, const unsigned char *limit) { /* This is used only by servers. */ SSL_SESSION *ret = NULL; int fatal = 0; int try_session_cache = 1; #ifndef OPENSSL_NO_TLSEXT int r; #endif if (session_id + len > limit) { fatal = 1; goto err; } if (len == 0) try_session_cache = 0; #ifndef OPENSSL_NO_TLSEXT /* sets s->tlsext_ticket_expected */ r = tls1_process_ticket(s, session_id, len, limit, &ret); switch (r) { case -1: /* Error during processing */ fatal = 1; goto err; case 0: /* No ticket found */ case 1: /* Zero length ticket found */ break; /* Ok to carry on processing session id. */ case 2: /* Ticket found but not decrypted. */ case 3: /* Ticket decrypted, *ret has been set. */ try_session_cache = 0; break; default: abort(); } #endif if (try_session_cache && ret == NULL && !(s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_LOOKUP)) { SSL_SESSION data; data.ssl_version = s->version; data.session_id_length = len; if (len == 0) return 0; memcpy(data.session_id, session_id, len); CRYPTO_r_lock(CRYPTO_LOCK_SSL_CTX); ret = lh_SSL_SESSION_retrieve(s->session_ctx->sessions, &data); if (ret != NULL) { /* don't allow other threads to steal it: */ CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); } CRYPTO_r_unlock(CRYPTO_LOCK_SSL_CTX); if (ret == NULL) s->session_ctx->stats.sess_miss++; } if (try_session_cache && ret == NULL && s->session_ctx->get_session_cb != NULL) { int copy = 1; if ((ret = s->session_ctx->get_session_cb(s, session_id, len, &copy))) { s->session_ctx->stats.sess_cb_hit++; /* * Increment reference count now if the session callback asks us * to do so (note that if the session structures returned by the * callback are shared between threads, it must handle the * reference count itself [i.e. copy == 0], or things won't be * thread-safe). */ if (copy) CRYPTO_add(&ret->references, 1, CRYPTO_LOCK_SSL_SESSION); /* * Add the externally cached session to the internal cache as * well if and only if we are supposed to. */ if (! (s->session_ctx->session_cache_mode & SSL_SESS_CACHE_NO_INTERNAL_STORE)) /* * The following should not return 1, otherwise, things are * very strange */ SSL_CTX_add_session(s->session_ctx, ret); } } if (ret == NULL) goto err; /* Now ret is non-NULL and we own one of its reference counts. */ if (ret->sid_ctx_length != s->sid_ctx_length || memcmp(ret->sid_ctx, s->sid_ctx, ret->sid_ctx_length)) { /* * We have the session requested by the client, but we don't want to * use it in this context. */ goto err; /* treat like cache miss */ } if ((s->verify_mode & SSL_VERIFY_PEER) && s->sid_ctx_length == 0) { /* * We can't be sure if this session is being used out of context, * which is especially important for SSL_VERIFY_PEER. The application * should have used SSL[_CTX]_set_session_id_context. For this error * case, we generate an error instead of treating the event like a * cache miss (otherwise it would be easy for applications to * effectively disable the session cache by accident without anyone * noticing). */ SSLerr(SSL_F_SSL_GET_PREV_SESSION, SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED); fatal = 1; goto err; } if (ret->cipher == NULL) { unsigned char buf[5], *p; unsigned long l; p = buf; l = ret->cipher_id; l2n(l, p); if ((ret->ssl_version >> 8) >= SSL3_VERSION_MAJOR) ret->cipher = ssl_get_cipher_by_char(s, &(buf[2])); else ret->cipher = ssl_get_cipher_by_char(s, &(buf[1])); if (ret->cipher == NULL) goto err; } if (ret->timeout < (long)(time(NULL) - ret->time)) { /* timeout */ s->session_ctx->stats.sess_timeout++; if (try_session_cache) { /* session was from the cache, so remove it */ SSL_CTX_remove_session(s->session_ctx, ret); } goto err; } s->session_ctx->stats.sess_hit++; if (s->session != NULL) SSL_SESSION_free(s->session); s->session = ret; s->verify_result = s->session->verify_result; return 1; err: if (ret != NULL) { SSL_SESSION_free(ret); #ifndef OPENSSL_NO_TLSEXT if (!try_session_cache) { /* * The session was from a ticket, so we should issue a ticket for * the new session */ s->tlsext_ticket_expected = 1; } #endif } if (fatal) return -1; else return 0; } ; 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: TIFFReadRawTile1(TIFF* tif, uint32 tile, void* buf, tmsize_t size, const char* module) { TIFFDirectory *td = &tif->tif_dir; if (!_TIFFFillStriles( tif )) return ((tmsize_t)(-1)); assert((tif->tif_flags&TIFF_NOREADRAW)==0); if (!isMapped(tif)) { tmsize_t cc; if (!SeekOK(tif, td->td_stripoffset[tile])) { TIFFErrorExt(tif->tif_clientdata, module, "Seek error at row %lu, col %lu, tile %lu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile); return ((tmsize_t)(-1)); } cc = TIFFReadFile(tif, buf, size); if (cc != size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned __int64) cc, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long long) cc, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } } else { tmsize_t ma,mb; tmsize_t n; ma=(tmsize_t)td->td_stripoffset[tile]; mb=ma+size; if (((uint64)ma!=td->td_stripoffset[tile])||(ma>tif->tif_size)) n=0; else if ((mb<ma)||(mb<size)||(mb>tif->tif_size)) n=tif->tif_size-ma; else n=size; if (n!=size) { #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__)) TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %I64u bytes, expected %I64u", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned __int64) n, (unsigned __int64) size); #else TIFFErrorExt(tif->tif_clientdata, module, "Read error at row %lu, col %lu, tile %lu; got %llu bytes, expected %llu", (unsigned long) tif->tif_row, (unsigned long) tif->tif_col, (unsigned long) tile, (unsigned long long) n, (unsigned long long) size); #endif return ((tmsize_t)(-1)); } _TIFFmemcpy(buf, tif->tif_base + ma, size); } return (size); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-189'], 'message': '* libtiff/tif_read.c: Fix out-of-bounds read on memory-mapped files in TIFFReadRawStrip1() and TIFFReadRawTile1() when stripoffset is beyond tmsize_t max value (reported by Mathias Svensson)'</s>
<s>[INST] Given the following code containing errors, provide 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 dtls1_clear_record_buffer(SSL *s) { pitem *item; for (item = pqueue_pop(s->d1->sent_messages); item != NULL; item = pqueue_pop(s->d1->sent_messages)) { dtls1_hm_fragment_free((hm_fragment *)item->data); pitem_free(item); } } ; 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: int ssl3_get_server_certificate(SSL *s) { int al, i, ok, ret = -1; unsigned long n, nc, llen, l; X509 *x = NULL; const unsigned char *q, *p; unsigned char *d; STACK_OF(X509) *sk = NULL; SESS_CERT *sc; EVP_PKEY *pkey = NULL; int need_cert = 1; /* VRS: 0=> will allow null cert if auth == * KRB5 */ n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B, -1, s->max_cert_list, &ok); if (!ok) return ((int)n); if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) || ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) { s->s3->tmp.reuse_message = 1; return (1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) { al = SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_BAD_MESSAGE_TYPE); goto f_err; } p = d = (unsigned char *)s->init_msg; if ((sk = sk_X509_new_null()) == NULL) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE); goto err; } n2l3(p, llen); if (llen + 3 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_LENGTH_MISMATCH); goto f_err; } for (nc = 0; nc < llen;) { n2l3(p, l); if ((l + nc + 3) > llen) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } q = p; x = d2i_X509(NULL, &q, l); if (x == NULL) { al = SSL_AD_BAD_CERTIFICATE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_ASN1_LIB); goto f_err; } if (q != (p + l)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } if (!sk_X509_push(sk, x)) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ERR_R_MALLOC_FAILURE); goto err; } x = NULL; nc += l + 3; p = q; } i = ssl_verify_cert_chain(s, sk); if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0) #ifndef OPENSSL_NO_KRB5 && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) #endif /* OPENSSL_NO_KRB5 */ ) { al = ssl_verify_alarm_type(s->verify_result); SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_CERTIFICATE_VERIFY_FAILED); goto f_err; } ERR_clear_error(); /* but we keep s->verify_result */ sc = ssl_sess_cert_new(); if (sc == NULL) goto err; if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert); s->session->sess_cert = sc; sc->cert_chain = sk; /* * Inconsistency alert: cert_chain does include the peer's certificate, * which we don't include in s3_srvr.c */ x = sk_X509_value(sk, 0); sk = NULL; /* * VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end */ pkey = X509_get_pubkey(x); /* VRS: allow null cert if auth == KRB5 */ need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) ? 0 : 1; #ifdef KSSL_DEBUG fprintf(stderr, "pkey,x = %p, %p\n", pkey, x); fprintf(stderr, "ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x, pkey)); fprintf(stderr, "cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name, s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert); #endif /* KSSL_DEBUG */ if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) { x = NULL; al = SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS); goto f_err; } i = ssl_cert_type(x, pkey); if (need_cert && i < 0) { x = NULL; al = SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto f_err; } if (need_cert) { sc->peer_cert_type = i; CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509); /* * Why would the following ever happen? We just created sc a couple * of lines ago. */ if (sc->peer_pkeys[i].x509 != NULL) X509_free(sc->peer_pkeys[i].x509); sc->peer_pkeys[i].x509 = x; sc->peer_key = &(sc->peer_pkeys[i]); if (s->session->peer != NULL) X509_free(s->session->peer); CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509); s->session->peer = x; } else { sc->peer_cert_type = i; sc->peer_key = NULL; if (s->session->peer != NULL) X509_free(s->session->peer); s->session->peer = NULL; } s->session->verify_result = s->verify_result; x = NULL; ret = 1; if (0) { f_err: ssl3_send_alert(s, SSL3_AL_FATAL, al); err: s->state = SSL_ST_ERR; } EVP_PKEY_free(pkey); X509_free(x); sk_X509_pop_free(sk, X509_free); return (ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix small OOB reads. In ssl3_get_client_certificate, ssl3_get_server_certificate and ssl3_get_certificate_request check we have enough room before reading a length. Thanks to Shi Lei (Gear Team, Qihoo 360 Inc.) for reporting these bugs. CVE-2016-6306 Reviewed-by: Richard Levitte <levitte@openssl.org> Reviewed-by: Matt Caswell <matt@openssl.org> (cherry picked from commit ff553f837172ecb2b5c8eca257ec3c5619a4b299)'</s>
<s>[INST] Given the following code containing errors, provide 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 init_common_variables() { umask(((~my_umask) & 0666)); my_decimal_set_zero(&decimal_zero); // set decimal_zero constant; tzset(); // Set tzname sf_leaking_memory= 0; // no memory leaks from now on max_system_variables.pseudo_thread_id= (ulong)~0; server_start_time= flush_status_time= my_time(0); rpl_filter= new Rpl_filter; binlog_filter= new Rpl_filter; if (!rpl_filter || !binlog_filter) { sql_perror("Could not allocate replication and binlog filters"); return 1; } if (init_thread_environment() || mysql_init_variables()) return 1; if (ignore_db_dirs_init()) return 1; #ifdef HAVE_TZNAME struct tm tm_tmp; localtime_r(&server_start_time,&tm_tmp); const char *tz_name= tzname[tm_tmp.tm_isdst != 0 ? 1 : 0]; #ifdef _WIN32 /* Time zone name may be localized and contain non-ASCII characters, Convert from ANSI encoding to UTF8. */ wchar_t wtz_name[sizeof(system_time_zone)]; mbstowcs(wtz_name, tz_name, sizeof(system_time_zone)-1); WideCharToMultiByte(CP_UTF8,0, wtz_name, -1, system_time_zone, sizeof(system_time_zone) - 1, NULL, NULL); #else strmake_buf(system_time_zone, tz_name); #endif /* _WIN32 */ #endif /* HAVE_TZNAME */ /* We set SYSTEM time zone as reasonable default and also for failure of my_tz_init() and bootstrap mode. If user explicitly set time zone with --default-time-zone option we will change this value in my_tz_init(). */ global_system_variables.time_zone= my_tz_SYSTEM; #ifdef HAVE_PSI_INTERFACE /* Complete the mysql_bin_log initialization. Instrumentation keys are known only after the performance schema initialization, and can not be set in the MYSQL_BIN_LOG constructor (called before main()). */ mysql_bin_log.set_psi_keys(key_BINLOG_LOCK_index, key_BINLOG_update_cond, key_file_binlog, key_file_binlog_index, key_BINLOG_COND_queue_busy); #endif /* Init mutexes for the global MYSQL_BIN_LOG objects. As safe_mutex depends on what MY_INIT() does, we can't init the mutexes of global MYSQL_BIN_LOGs in their constructors, because then they would be inited before MY_INIT(). So we do it here. */ mysql_bin_log.init_pthread_objects(); /* TODO: remove this when my_time_t is 64 bit compatible */ if (!IS_TIME_T_VALID_FOR_TIMESTAMP(server_start_time)) { sql_print_error("This MySQL server doesn't support dates later then 2038"); return 1; } if (gethostname(glob_hostname,sizeof(glob_hostname)) < 0) { /* Get hostname of computer (used by 'show variables') and as default basename for the pid file if --log-basename is not given. */ strmake(glob_hostname, STRING_WITH_LEN("localhost")); sql_print_warning("gethostname failed, using '%s' as hostname", glob_hostname); opt_log_basename= const_cast<char *>("mysql"); } else opt_log_basename= glob_hostname; if (!*pidfile_name) { strmake(pidfile_name, opt_log_basename, sizeof(pidfile_name)-5); strmov(fn_ext(pidfile_name),".pid"); // Add proper extension } /* The default-storage-engine entry in my_long_options should have a non-null default value. It was earlier intialized as (longlong)"MyISAM" in my_long_options but this triggered a compiler error in the Sun Studio 12 compiler. As a work-around we set the def_value member to 0 in my_long_options and initialize it to the correct value here. From MySQL 5.5 onwards, the default storage engine is InnoDB (except in the embedded server, where the default continues to be MyISAM) */ #if defined(WITH_INNOBASE_STORAGE_ENGINE) || defined(WITH_XTRADB_STORAGE_ENGINE) default_storage_engine= const_cast<char *>("InnoDB"); #else default_storage_engine= const_cast<char *>("MyISAM"); #endif /* Add server status variables to the dynamic list of status variables that is shown by SHOW STATUS. Later, in plugin_init, and mysql_install_plugin new entries could be added to that list. */ if (add_status_vars(status_vars)) return 1; // an error was already reported #ifndef DBUG_OFF /* We have few debug-only commands in com_status_vars, only visible in debug builds. for simplicity we enable the assert only in debug builds There are 8 Com_ variables which don't have corresponding SQLCOM_ values: (TODO strictly speaking they shouldn't be here, should not have Com_ prefix that is. Perhaps Stmt_ ? Comstmt_ ? Prepstmt_ ?) Com_admin_commands => com_other Com_stmt_close => com_stmt_close Com_stmt_execute => com_stmt_execute Com_stmt_fetch => com_stmt_fetch Com_stmt_prepare => com_stmt_prepare Com_stmt_reprepare => com_stmt_reprepare Com_stmt_reset => com_stmt_reset Com_stmt_send_long_data => com_stmt_send_long_data With this correction the number of Com_ variables (number of elements in the array, excluding the last element - terminator) must match the number of SQLCOM_ constants. */ compile_time_assert(sizeof(com_status_vars)/sizeof(com_status_vars[0]) - 1 == SQLCOM_END + 8); #endif if (get_options(&remaining_argc, &remaining_argv)) return 1; set_server_version(); if (!opt_help) sql_print_information("%s (mysqld %s) starting as process %lu ...", my_progname, server_version, (ulong) getpid()); #ifndef EMBEDDED_LIBRARY if (opt_abort && !opt_verbose) unireg_abort(0); #endif /*!EMBEDDED_LIBRARY*/ DBUG_PRINT("info",("%s Ver %s for %s on %s\n",my_progname, server_version, SYSTEM_TYPE,MACHINE_TYPE)); #ifdef HAVE_LARGE_PAGES /* Initialize large page size */ if (opt_large_pages && (opt_large_page_size= my_get_large_page_size())) { DBUG_PRINT("info", ("Large page set, large_page_size = %d", opt_large_page_size)); my_use_large_pages= 1; my_large_page_size= opt_large_page_size; } else { opt_large_pages= 0; /* Either not configured to use large pages or Linux haven't been compiled with large page support */ } #endif /* HAVE_LARGE_PAGES */ #ifdef HAVE_SOLARIS_LARGE_PAGES #define LARGE_PAGESIZE (4*1024*1024) /* 4MB */ #define SUPER_LARGE_PAGESIZE (256*1024*1024) /* 256MB */ if (opt_large_pages) { /* tell the kernel that we want to use 4/256MB page for heap storage and also for the stack. We use 4 MByte as default and if the super-large-page is set we increase it to 256 MByte. 256 MByte is for server installations with GBytes of RAM memory where the MySQL Server will have page caches and other memory regions measured in a number of GBytes. We use as big pages as possible which isn't bigger than the above desired page sizes. */ int nelem; size_t max_desired_page_size; if (opt_super_large_pages) max_desired_page_size= SUPER_LARGE_PAGESIZE; else max_desired_page_size= LARGE_PAGESIZE; nelem = getpagesizes(NULL, 0); if (nelem > 0) { size_t *pagesize = (size_t *) malloc(sizeof(size_t) * nelem); if (pagesize != NULL && getpagesizes(pagesize, nelem) > 0) { size_t max_page_size= 0; for (int i= 0; i < nelem; i++) { if (pagesize[i] > max_page_size && pagesize[i] <= max_desired_page_size) max_page_size= pagesize[i]; } free(pagesize); if (max_page_size > 0) { struct memcntl_mha mpss; mpss.mha_cmd= MHA_MAPSIZE_BSSBRK; mpss.mha_pagesize= max_page_size; mpss.mha_flags= 0; memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mpss, 0, 0); mpss.mha_cmd= MHA_MAPSIZE_STACK; memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mpss, 0, 0); } } } } #endif /* HAVE_SOLARIS_LARGE_PAGES */ /* connections and databases needs lots of files */ { uint files, wanted_files, max_open_files; /* MyISAM requires two file handles per table. */ wanted_files= (10 + max_connections + extra_max_connections + table_cache_size*2); /* We are trying to allocate no less than max_connections*5 file handles (i.e. we are trying to set the limit so that they will be available). In addition, we allocate no less than how much was already allocated. However below we report a warning and recompute values only if we got less file handles than were explicitly requested. No warning and re-computation occur if we can't get max_connections*5 but still got no less than was requested (value of wanted_files). */ max_open_files= max(max(wanted_files, (max_connections + extra_max_connections)*5), open_files_limit); files= my_set_max_open_files(max_open_files); if (files < wanted_files) { if (!open_files_limit) { /* If we have requested too much file handles than we bring max_connections in supported bounds. */ max_connections= (ulong) min(files-10-TABLE_OPEN_CACHE_MIN*2, max_connections); /* Decrease table_cache_size according to max_connections, but not below TABLE_OPEN_CACHE_MIN. Outer min() ensures that we never increase table_cache_size automatically (that could happen if max_connections is decreased above). */ table_cache_size= (ulong) min(max((files-10-max_connections)/2, TABLE_OPEN_CACHE_MIN), table_cache_size); DBUG_PRINT("warning", ("Changed limits: max_open_files: %u max_connections: %ld table_cache: %ld", files, max_connections, table_cache_size)); if (global_system_variables.log_warnings) sql_print_warning("Changed limits: max_open_files: %u max_connections: %ld table_cache: %ld", files, max_connections, table_cache_size); } else if (global_system_variables.log_warnings) sql_print_warning("Could not increase number of max_open_files to more than %u (request: %u)", files, wanted_files); } open_files_limit= files; } unireg_init(opt_specialflag); /* Set up extern variabels */ if (!(my_default_lc_messages= my_locale_by_name(lc_messages))) { sql_print_error("Unknown locale: '%s'", lc_messages); return 1; } global_system_variables.lc_messages= my_default_lc_messages; if (init_errmessage()) /* Read error messages from file */ return 1; init_client_errs(); mysql_library_init(unused,unused,unused); /* for replication */ lex_init(); if (item_create_init()) return 1; item_init(); #ifndef EMBEDDED_LIBRARY my_regex_init(&my_charset_latin1, check_enough_stack_size); my_string_stack_guard= check_enough_stack_size; #else my_regex_init(&my_charset_latin1, NULL); #endif /* Process a comma-separated character set list and choose the first available character set. This is mostly for test purposes, to be able to start "mysqld" even if the requested character set is not available (see bug#18743). */ for (;;) { char *next_character_set_name= strchr(default_character_set_name, ','); if (next_character_set_name) *next_character_set_name++= '\0'; if (!(default_charset_info= get_charset_by_csname(default_character_set_name, MY_CS_PRIMARY, MYF(MY_WME)))) { if (next_character_set_name) { default_character_set_name= next_character_set_name; default_collation_name= 0; // Ignore collation } else return 1; // Eof of the list } else break; } if (default_collation_name) { CHARSET_INFO *default_collation; default_collation= get_charset_by_name(default_collation_name, MYF(0)); if (!default_collation) { sql_print_error(ER_DEFAULT(ER_UNKNOWN_COLLATION), default_collation_name); return 1; } if (!my_charset_same(default_charset_info, default_collation)) { sql_print_error(ER_DEFAULT(ER_COLLATION_CHARSET_MISMATCH), default_collation_name, default_charset_info->csname); return 1; } default_charset_info= default_collation; } /* Set collactions that depends on the default collation */ global_system_variables.collation_server= default_charset_info; global_system_variables.collation_database= default_charset_info; global_system_variables.collation_connection= default_charset_info; global_system_variables.character_set_results= default_charset_info; global_system_variables.character_set_client= default_charset_info; if (!(character_set_filesystem= get_charset_by_csname(character_set_filesystem_name, MY_CS_PRIMARY, MYF(MY_WME)))) return 1; global_system_variables.character_set_filesystem= character_set_filesystem; if (!(my_default_lc_time_names= my_locale_by_name(lc_time_names_name))) { sql_print_error("Unknown locale: '%s'", lc_time_names_name); return 1; } global_system_variables.lc_time_names= my_default_lc_time_names; /* check log options and issue warnings if needed */ if (opt_log && opt_logname && *opt_logname && !(log_output_options & (LOG_FILE | LOG_NONE))) sql_print_warning("Although a path was specified for the " "--log option, log tables are used. " "To enable logging to files use the --log-output option."); if (opt_slow_log && opt_slow_logname && *opt_slow_logname && !(log_output_options & (LOG_FILE | LOG_NONE))) sql_print_warning("Although a path was specified for the " "--log-slow-queries option, log tables are used. " "To enable logging to files use the --log-output=file option."); if (!opt_logname || !*opt_logname) make_default_log_name(&opt_logname, ".log", false); if (!opt_slow_logname || !*opt_slow_logname) make_default_log_name(&opt_slow_logname, "-slow.log", false); #if defined(ENABLED_DEBUG_SYNC) /* Initialize the debug sync facility. See debug_sync.cc. */ if (debug_sync_init()) return 1; /* purecov: tested */ #endif /* defined(ENABLED_DEBUG_SYNC) */ #if (ENABLE_TEMP_POOL) if (use_temp_pool && bitmap_init(&temp_pool,0,1024,1)) return 1; #else use_temp_pool= 0; #endif if (my_dboptions_cache_init()) return 1; /* Ensure that lower_case_table_names is set on system where we have case insensitive names. If this is not done the users MyISAM tables will get corrupted if accesses with names of different case. */ DBUG_PRINT("info", ("lower_case_table_names: %d", lower_case_table_names)); lower_case_file_system= test_if_case_insensitive(mysql_real_data_home); if (!lower_case_table_names && lower_case_file_system == 1) { if (lower_case_table_names_used) { #if MYSQL_VERSION_ID < 100100 if (global_system_variables.log_warnings) sql_print_warning("You have forced lower_case_table_names to 0 through " "a command-line option, even though your file system " "'%s' is case insensitive. This means that you can " "corrupt your tables if you access them using names " "with different letter case. You should consider " "changing lower_case_table_names to 1 or 2", mysql_real_data_home); #else sql_print_error("The server option 'lower_case_table_names' is " "configured to use case sensitive table names but the " "data directory resides on a case-insensitive file system. " "Please use a case sensitive file system for your data " "directory or switch to a case-insensitive table name " "mode."); #endif return 1; } else { if (global_system_variables.log_warnings) sql_print_warning("Setting lower_case_table_names=2 because file system for %s is case insensitive", mysql_real_data_home); lower_case_table_names= 2; } } else if (lower_case_table_names == 2 && !(lower_case_file_system= (lower_case_file_system == 1))) { if (global_system_variables.log_warnings) sql_print_warning("lower_case_table_names was set to 2, even though your " "the file system '%s' is case sensitive. Now setting " "lower_case_table_names to 0 to avoid future problems.", mysql_real_data_home); lower_case_table_names= 0; } else { lower_case_file_system= (lower_case_file_system == 1); } /* Reset table_alias_charset, now that lower_case_table_names is set. */ table_alias_charset= (lower_case_table_names ? files_charset_info : &my_charset_bin); if (ignore_db_dirs_process_additions()) { sql_print_error("An error occurred while storing ignore_db_dirs to a hash."); return 1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'don't use my_copystat in the server it was supposed to be used in command-line tools only. Different fix for 4e5473862e: Bug#24388746: PRIVILEGE ESCALATION AND RACE CONDITION USING CREATE TABLE'</s>
<s>[INST] Given the following code containing errors, provide 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 writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts* dump) { uint16 bps; uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint32 tile_rowsize = TIFFTileRowSize(out); uint8* bufp = (uint8*) buf; tsize_t tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(out); unsigned char *tilebuf = NULL; if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) || !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) || !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) ) return 1; if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0) { TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero"); exit(-1); } tile_buffsize = tilesize; if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("writeBufferToContigTiles", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != tile_buffsize / tile_rowsize) { TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size"); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 1; src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth, tw, 0, spp, spp, bps, dump) > 0) { TIFFError("writeBufferToContigTiles", "Unable to extract data to tile for row %lu, col %lu", (unsigned long) row, (unsigned long)col); _TIFFfree(tilebuf); return 1; } if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0) { TIFFError("writeBufferToContigTiles", "Cannot write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(tilebuf); return 1; } } } _TIFFfree(tilebuf); return 0; } /* end writeBufferToContigTiles */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': '* tools/tiffcrop.c: fix multiple uint32 overflows in writeBufferToSeparateStrips(), writeBufferToContigTiles() and writeBufferToSeparateTiles() that could cause heap buffer overflows. Reported by Henri Salo from Nixu Corporation. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2592'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s) { TIFFPredictorState *sp = PredictorState(tif); assert(sp != NULL); assert(sp->decoderow != NULL); assert(sp->decodepfunc != NULL); if ((*sp->decoderow)(tif, op0, occ0, s)) { (*sp->decodepfunc)(tif, op0, occ0); 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: fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc) { tmsize_t stride = PredictorState(tif)->stride; uint32 bps = tif->tif_dir.td_bitspersample / 8; tmsize_t wc = cc / bps; tmsize_t count; uint8 *cp = (uint8 *) cp0; uint8 *tmp = (uint8 *)_TIFFmalloc(cc); assert((cc%(bps*stride))==0); if (!tmp) return; _TIFFmemcpy(tmp, cp0, cc); for (count = 0; count < wc; count++) { uint32 byte; for (byte = 0; byte < bps; byte++) { #if WORDS_BIGENDIAN cp[byte * wc + count] = tmp[bps * count + byte]; #else cp[(bps - byte - 1) * wc + count] = tmp[bps * count + byte]; #endif } } _TIFFfree(tmp); cp = (uint8 *) cp0; cp += cc - stride - 1; for (count = cc; count > stride; count -= stride) REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--) } ; 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: static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero"); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("readContigTilesIntoBuffer", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size."); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-125', 'CWE-787'], 'message': '* tools/tiffcrop.c: fix out-of-bound read of up to 3 bytes in readContigTilesIntoBuffer(). Reported as MSVR 35092 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: int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator, const BIGNUM *order, const BIGNUM *cofactor) { if (generator == NULL) { ECerr(EC_F_EC_GROUP_SET_GENERATOR, ERR_R_PASSED_NULL_PARAMETER); return 0 ; } if (group->generator == NULL) { group->generator = EC_POINT_new(group); if (group->generator == NULL) return 0; } if (!EC_POINT_copy(group->generator, generator)) return 0; if (order != NULL) { if (!BN_copy(&group->order, order)) return 0; } else BN_zero(&group->order); if (cofactor != NULL) { if (!BN_copy(&group->cofactor, cofactor)) return 0; } else BN_zero(&group->cofactor); return 1; } ; 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 aes_ccm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_CCM_CTX *cctx = EVP_C_DATA(EVP_AES_CCM_CTX,c); switch (type) { case EVP_CTRL_INIT: cctx->key_set = 0; cctx->iv_set = 0; cctx->L = 8; cctx->M = 12; cctx->tag_set = 0; cctx->len_set = 0; cctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); cctx->tls_aad_len = arg; { uint16_t len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_CCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= cctx->M; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return cctx->M; case EVP_CTRL_CCM_SET_IV_FIXED: /* Sanity check length */ if (arg != EVP_CCM_TLS_FIXED_IV_LEN) return 0; /* Just copy to first part of IV */ memcpy(EVP_CIPHER_CTX_iv_noconst(c), ptr, arg); return 1; case EVP_CTRL_AEAD_SET_IVLEN: arg = 15 - arg; case EVP_CTRL_CCM_SET_L: if (arg < 2 || arg > 8) return 0; cctx->L = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if ((arg & 1) || arg < 4 || arg > 16) return 0; if (EVP_CIPHER_CTX_encrypting(c) && ptr) return 0; if (ptr) { cctx->tag_set = 1; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); } cctx->M = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (!EVP_CIPHER_CTX_encrypting(c) || !cctx->tag_set) return 0; if (!CRYPTO_ccm128_tag(&cctx->ccm, ptr, (size_t)arg)) return 0; cctx->tag_set = 0; cctx->iv_set = 0; cctx->len_set = 0; return 1; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_CCM_CTX *cctx_out = EVP_C_DATA(EVP_AES_CCM_CTX,out); if (cctx->ccm.key) { if (cctx->ccm.key != &cctx->ks) return 0; cctx_out->ccm.key = &cctx_out->ks; } return 1; } default: return -1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'crypto/evp: harden AEAD ciphers. 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. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. 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: static int tls_construct_cke_ecdhe(SSL *s, unsigned char **p, int *len, int *al) { #ifndef OPENSSL_NO_EC unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; EVP_PKEY *ckey = NULL, *skey = NULL; skey = s->s3->peer_tmp; if (skey == NULL) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); return 0; } ckey = ssl_generate_pkey(skey); if (ssl_derive(s, ckey, skey) == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EVP_LIB); goto err; } /* Generate encoding of client key */ encoded_pt_len = EVP_PKEY_get1_tls_encodedpoint(ckey, &encodedPoint); if (encoded_pt_len == 0) { SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_EC_LIB); goto err; } EVP_PKEY_free(ckey); ckey = NULL; *len = encoded_pt_len; /* length of encoded point */ **p = *len; *p += 1; /* copy the point */ memcpy(*p, encodedPoint, *len); /* increment len to account for length field */ *len += 1; OPENSSL_free(encodedPoint); return 1; err: EVP_PKEY_free(ckey); return 0; #else SSLerr(SSL_F_TLS_CONSTRUCT_CKE_ECDHE, ERR_R_INTERNAL_ERROR); *al = SSL_AD_INTERNAL_ERROR; return 0; #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fix missing NULL checks in CKE processing 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: TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) { static const char module[] = "TIFFReadEncodedStrip"; TIFFDirectory *td = &tif->tif_dir; uint32 rowsperstrip; uint32 stripsperplane; uint32 stripinplane; uint16 plane; uint32 rows; tmsize_t stripsize; if (!TIFFCheckRead(tif,0)) return((tmsize_t)(-1)); if (strip>=td->td_nstrips) { TIFFErrorExt(tif->tif_clientdata,module, "%lu: Strip out of range, max %lu",(unsigned long)strip, (unsigned long)td->td_nstrips); return((tmsize_t)(-1)); } /* * Calculate the strip size according to the number of * rows in the strip (check for truncated last strip on any * of the separations). */ rowsperstrip=td->td_rowsperstrip; if (rowsperstrip>td->td_imagelength) rowsperstrip=td->td_imagelength; stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip); stripinplane=(strip%stripsperplane); plane=(uint16)(strip/stripsperplane); rows=td->td_imagelength-stripinplane*rowsperstrip; if (rows>rowsperstrip) rows=rowsperstrip; stripsize=TIFFVStripSize(tif,rows); if (stripsize==0) return((tmsize_t)(-1)); /* shortcut to avoid an extra memcpy() */ if( td->td_compression == COMPRESSION_NONE && size!=(tmsize_t)(-1) && size >= stripsize && !isMapped(tif) && ((tif->tif_flags&TIFF_NOREADRAW)==0) ) { if (TIFFReadRawStrip1(tif, strip, buf, stripsize, module) != stripsize) return ((tmsize_t)(-1)); if (!isFillOrder(tif, td->td_fillorder) && (tif->tif_flags & TIFF_NOBITREV) == 0) TIFFReverseBits(buf,stripsize); (*tif->tif_postdecode)(tif,buf,stripsize); return (stripsize); } if ((size!=(tmsize_t)(-1))&&(size<stripsize)) stripsize=size; if (!TIFFFillStrip(tif,strip)) return((tmsize_t)(-1)); if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0) return((tmsize_t)(-1)); (*tif->tif_postdecode)(tif,buf,stripsize); return(stripsize); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': '* libtiff/tif_read.c, libtiff/tiffiop.h: fix uint32 overflow in TIFFReadEncodedStrip() that caused an integer division by zero. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2596'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TIFFWriteDirectoryTagSampleformatArray(TIFF* tif, uint32* ndir, TIFFDirEntry* dir, uint16 tag, uint32 count, double* value) { static const char module[] = "TIFFWriteDirectoryTagSampleformatArray"; void* conv; uint32 i; int ok; conv = _TIFFmalloc(count*sizeof(double)); if (conv == NULL) { TIFFErrorExt(tif->tif_clientdata, module, "Out of memory"); return (0); } switch (tif->tif_dir.td_sampleformat) { case SAMPLEFORMAT_IEEEFP: if (tif->tif_dir.td_bitspersample<=32) { for (i = 0; i < count; ++i) ((float*)conv)[i] = (float)value[i]; ok = TIFFWriteDirectoryTagFloatArray(tif,ndir,dir,tag,count,(float*)conv); } else { ok = TIFFWriteDirectoryTagDoubleArray(tif,ndir,dir,tag,count,value); } break; case SAMPLEFORMAT_INT: if (tif->tif_dir.td_bitspersample<=8) { for (i = 0; i < count; ++i) ((int8*)conv)[i] = (int8)value[i]; ok = TIFFWriteDirectoryTagSbyteArray(tif,ndir,dir,tag,count,(int8*)conv); } else if (tif->tif_dir.td_bitspersample<=16) { for (i = 0; i < count; ++i) ((int16*)conv)[i] = (int16)value[i]; ok = TIFFWriteDirectoryTagSshortArray(tif,ndir,dir,tag,count,(int16*)conv); } else { for (i = 0; i < count; ++i) ((int32*)conv)[i] = (int32)value[i]; ok = TIFFWriteDirectoryTagSlongArray(tif,ndir,dir,tag,count,(int32*)conv); } break; case SAMPLEFORMAT_UINT: if (tif->tif_dir.td_bitspersample<=8) { for (i = 0; i < count; ++i) ((uint8*)conv)[i] = (uint8)value[i]; ok = TIFFWriteDirectoryTagByteArray(tif,ndir,dir,tag,count,(uint8*)conv); } else if (tif->tif_dir.td_bitspersample<=16) { for (i = 0; i < count; ++i) ((uint16*)conv)[i] = (uint16)value[i]; ok = TIFFWriteDirectoryTagShortArray(tif,ndir,dir,tag,count,(uint16*)conv); } else { for (i = 0; i < count; ++i) ((uint32*)conv)[i] = (uint32)value[i]; ok = TIFFWriteDirectoryTagLongArray(tif,ndir,dir,tag,count,(uint32*)conv); } break; default: ok = 0; } _TIFFfree(conv); return (ok); } ; 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: gaussian_blur_surface (cairo_surface_t *in, cairo_surface_t *out, gdouble sx, gdouble sy) { gboolean use_box_blur; gint width, height; cairo_format_t in_format, out_format; gint in_stride; gint out_stride; guchar *in_data, *out_data; gint bpp; gboolean out_has_data; cairo_surface_flush (in); width = cairo_image_surface_get_width (in); height = cairo_image_surface_get_height (in); g_assert (width == cairo_image_surface_get_width (out) && height == cairo_image_surface_get_height (out)); in_format = cairo_image_surface_get_format (in); out_format = cairo_image_surface_get_format (out); g_assert (in_format == out_format); g_assert (in_format == CAIRO_FORMAT_ARGB32 || in_format == CAIRO_FORMAT_A8); if (in_format == CAIRO_FORMAT_ARGB32) bpp = 4; else if (in_format == CAIRO_FORMAT_A8) bpp = 1; else { g_assert_not_reached (); return; } in_stride = cairo_image_surface_get_stride (in); out_stride = cairo_image_surface_get_stride (out); in_data = cairo_image_surface_get_data (in); out_data = cairo_image_surface_get_data (out); if (sx < 0.0) sx = 0.0; if (sy < 0.0) sy = 0.0; /* For small radiuses, use a true gaussian kernel; otherwise use three box blurs with * clever offsets. */ if (sx < 10.0 && sy < 10.0) use_box_blur = FALSE; else use_box_blur = TRUE; /* Bail out by just copying? */ if ((sx == 0.0 && sy == 0.0) || sx > 1000 || sy > 1000) { cairo_t *cr; cr = cairo_create (out); cairo_set_source_surface (cr, in, 0, 0); cairo_paint (cr); cairo_destroy (cr); return; } if (sx != 0.0) { gint box_width; gdouble *gaussian_matrix; gint gaussian_matrix_len; int y; guchar *row_buffer = NULL; guchar *row1, *row2; if (use_box_blur) { box_width = compute_box_blur_width (sx); /* twice the size so we can have "two" scratch rows */ row_buffer = g_new0 (guchar, width * bpp * 2); row1 = row_buffer; row2 = row_buffer + width * bpp; } else make_gaussian_convolution_matrix (sx, &gaussian_matrix, &gaussian_matrix_len); for (y = 0; y < height; y++) { guchar *in_row, *out_row; in_row = in_data + in_stride * y; out_row = out_data + out_stride * y; if (use_box_blur) { if (box_width % 2 != 0) { /* Odd-width box blur: repeat 3 times, centered on output pixel */ box_blur_line (box_width, 0, in_row, row1, width, bpp); box_blur_line (box_width, 0, row1, row2, width, bpp); box_blur_line (box_width, 0, row2, out_row, width, bpp); } else { /* Even-width box blur: * This method is suggested by the specification for SVG. * One pass with width n, centered between output and right pixel * One pass with width n, centered between output and left pixel * One pass with width n+1, centered on output pixel */ box_blur_line (box_width, -1, in_row, row1, width, bpp); box_blur_line (box_width, 1, row1, row2, width, bpp); box_blur_line (box_width + 1, 0, row2, out_row, width, bpp); } } else gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, in_row, out_row, width, bpp); } if (!use_box_blur) g_free (gaussian_matrix); g_free (row_buffer); out_has_data = TRUE; } else out_has_data = FALSE; if (sy != 0.0) { gint box_height; gdouble *gaussian_matrix = NULL; gint gaussian_matrix_len; guchar *col_buffer; guchar *col1, *col2; int x; /* twice the size so we can have the source pixels and the blurred pixels */ col_buffer = g_new0 (guchar, height * bpp * 2); col1 = col_buffer; col2 = col_buffer + height * bpp; if (use_box_blur) { box_height = compute_box_blur_width (sy); } else make_gaussian_convolution_matrix (sy, &gaussian_matrix, &gaussian_matrix_len); for (x = 0; x < width; x++) { if (out_has_data) get_column (col1, out_data, out_stride, bpp, height, x); else get_column (col1, in_data, in_stride, bpp, height, x); if (use_box_blur) { if (box_height % 2 != 0) { /* Odd-width box blur */ box_blur_line (box_height, 0, col1, col2, height, bpp); box_blur_line (box_height, 0, col2, col1, height, bpp); box_blur_line (box_height, 0, col1, col2, height, bpp); } else { /* Even-width box blur */ box_blur_line (box_height, -1, col1, col2, height, bpp); box_blur_line (box_height, 1, col2, col1, height, bpp); box_blur_line (box_height + 1, 0, col1, col2, height, bpp); } } else gaussian_blur_line (gaussian_matrix, gaussian_matrix_len, col1, col2, height, bpp); put_column (col2, out_data, out_stride, bpp, height, x); } g_free (gaussian_matrix); g_free (col_buffer); } cairo_surface_mark_dirty (out); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-369'], 'message': 'bgo#783835 - Don't divide by zero in box_blur_line() for gaussian blurs We were making the decision to use box blurs, instead of a true Gaussian kernel, based on the size of *both* x and y dimensions. Do them individually instead.'</s>
<s>[INST] Given the following code containing errors, provide 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_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx) { int rv; rv = asn1_item_embed_d2i(pval, in, len, it, tag, aclass, opt, ctx); if (rv <= 0) ASN1_item_ex_free(pval, it); return rv; } ; 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: Agraph_t *agroot(void* obj) { switch (AGTYPE(obj)) { case AGINEDGE: case AGOUTEDGE: return ((Agedge_t *) obj)->node->root; case AGNODE: return ((Agnode_t *) obj)->root; case AGRAPH: return ((Agraph_t *) obj)->root; default: /* actually can't occur if only 2 bit tags */ agerr(AGERR, "agroot of a bad object"); return NILgraph; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'attempted fix for null pointer deference on malformed input'</s>
<s>[INST] Given the following code containing errors, provide 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 RAND_DRBG *rand_drbg_new(int secure, int type, unsigned int flags, RAND_DRBG *parent) { RAND_DRBG *drbg = secure ? OPENSSL_secure_zalloc(sizeof(*drbg)) : OPENSSL_zalloc(sizeof(*drbg)); if (drbg == NULL) { RANDerr(RAND_F_RAND_DRBG_NEW, ERR_R_MALLOC_FAILURE); return NULL; } drbg->secure = secure && CRYPTO_secure_allocated(drbg); drbg->fork_count = rand_fork_count; drbg->parent = parent; if (parent == NULL) { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; #ifndef RAND_DRBG_GET_RANDOM_NONCE drbg->get_nonce = rand_drbg_get_nonce; drbg->cleanup_nonce = rand_drbg_cleanup_nonce; #endif drbg->reseed_interval = master_reseed_interval; drbg->reseed_time_interval = master_reseed_time_interval; } else { drbg->get_entropy = rand_drbg_get_entropy; drbg->cleanup_entropy = rand_drbg_cleanup_entropy; /* * Do not provide nonce callbacks, the child DRBGs will * obtain their nonce using random bits from the parent. */ drbg->reseed_interval = slave_reseed_interval; drbg->reseed_time_interval = slave_reseed_time_interval; } if (RAND_DRBG_set(drbg, type, flags) == 0) goto err; if (parent != NULL) { rand_drbg_lock(parent); if (drbg->strength > parent->strength) { /* * We currently don't support the algorithm from NIST SP 800-90C * 10.1.2 to use a weaker DRBG as source */ rand_drbg_unlock(parent); RANDerr(RAND_F_RAND_DRBG_NEW, RAND_R_PARENT_STRENGTH_TOO_WEAK); goto err; } rand_drbg_unlock(parent); } return drbg; err: RAND_DRBG_free(drbg); return NULL; } ; 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: static int pkcs7_decrypt_rinfo(unsigned char **pek, int *peklen, PKCS7_RECIP_INFO *ri, EVP_PKEY *pkey) { EVP_PKEY_CTX *pctx = NULL; unsigned char *ek = NULL; size_t eklen; int ret = -1; pctx = EVP_PKEY_CTX_new(pkey, NULL); if (!pctx) return -1; if (EVP_PKEY_decrypt_init(pctx) <= 0) goto err; if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_DECRYPT, EVP_PKEY_CTRL_PKCS7_DECRYPT, 0, ri) <= 0) { PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, PKCS7_R_CTRL_ERROR); goto err; } if (EVP_PKEY_decrypt(pctx, NULL, &eklen, ri->enc_key->data, ri->enc_key->length) <= 0) goto err; ek = OPENSSL_malloc(eklen); if (ek == NULL) { PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_MALLOC_FAILURE); goto err; } if (EVP_PKEY_decrypt(pctx, ek, &eklen, ri->enc_key->data, ri->enc_key->length) <= 0) { ret = 0; PKCS7err(PKCS7_F_PKCS7_DECRYPT_RINFO, ERR_R_EVP_LIB); goto err; } ret = 1; if (*pek) { OPENSSL_cleanse(*pek, *peklen); OPENSSL_free(*pek); } *pek = ek; *peklen = eklen; err: if (pctx) EVP_PKEY_CTX_free(pctx); if (!ret && ek) OPENSSL_free(ek); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-327'], 'message': 'Fix a padding oracle in PKCS7_dataDecode and CMS_decrypt_set1_pkey An attack is simple, if the first CMS_recipientInfo is valid but the second CMS_recipientInfo is chosen ciphertext. If the second recipientInfo decodes to PKCS #1 v1.5 form plaintext, the correct encryption key will be replaced by garbage, and the message cannot be decoded, but if the RSA decryption fails, the correct encryption key is used and the recipient will not notice the attack. As a work around for this potential attack the length of the decrypted key must be equal to the cipher default key length, in case the certifiate is not given and all recipientInfo are tried out. The old behaviour can be re-enabled in the CMS code by setting the CMS_DEBUG_DECRYPT flag. Reviewed-by: Matt Caswell <matt@openssl.org> (Merged from https://github.com/openssl/openssl/pull/9777) (cherry picked from commit 5840ed0cd1e6487d247efbc1a04136a41d7b3a37)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Network::FilterStatus Context::onDownstreamData(int data_length, bool end_of_stream) { if (!wasm_->onDownstreamData_) { return Network::FilterStatus::Continue; } auto result = wasm_->onDownstreamData_(this, id_, static_cast<uint32_t>(data_length), static_cast<uint32_t>(end_of_stream)); // TODO(PiotrSikora): pull Proxy-WASM's FilterStatus values. return result.u64_ == 0 ? Network::FilterStatus::Continue : Network::FilterStatus::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: Network::FilterStatus Context::onNetworkNewConnection() { onCreate(root_context_id_); if (!wasm_->onNewConnection_) { return Network::FilterStatus::Continue; } if (wasm_->onNewConnection_(this, id_).u64_ == 0) { return Network::FilterStatus::Continue; } return Network::FilterStatus::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_latin1(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>()->Length(); } else { int copied = val.As<v8::String>()->WriteOneByte(env->isolate, reinterpret_cast<uint8_t*>(buf), 0, bufsize - 1, 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: inline StreamWriteResult StreamBase::Write( uv_buf_t* bufs, size_t count, uv_stream_t* send_handle, v8::Local<v8::Object> req_wrap_obj) { Environment* env = stream_env(); int err; size_t total_bytes = 0; for (size_t i = 0; i < count; ++i) total_bytes += bufs[i].len; bytes_written_ += total_bytes; if (send_handle == nullptr) { err = DoTryWrite(&bufs, &count); if (err != 0 || count == 0) { return StreamWriteResult { false, err, nullptr, total_bytes }; } } HandleScope handle_scope(env->isolate()); if (req_wrap_obj.IsEmpty()) { req_wrap_obj = env->write_wrap_template() ->NewInstance(env->context()).ToLocalChecked(); StreamReq::ResetObject(req_wrap_obj); } AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(GetAsyncWrap()); WriteWrap* req_wrap = CreateWriteWrap(req_wrap_obj); err = DoWrite(req_wrap, bufs, count, send_handle); bool async = err == 0; if (!async) { req_wrap->Dispose(); req_wrap = nullptr; } const char* msg = Error(); if (msg != nullptr) { req_wrap_obj->Set(env->error_string(), OneByteString(env->isolate(), msg)); ClearError(); } return StreamWriteResult { async, err, req_wrap, total_bytes }; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'src: use unique_ptr for WriteWrap This commit attempts to avoid a use-after-free error by using unqiue_ptr and passing a reference to it. CVE-ID: CVE-2020-8265 Fixes: https://github.com/nodejs-private/node-private/issues/227 PR-URL: https://github.com/nodejs-private/node-private/pull/238 Reviewed-By: Michael Dawson <midawson@redhat.com> Reviewed-By: Tobias Nießen <tniessen@tnie.de> Reviewed-By: Richard Lau <rlau@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int FuzzerTestOneInput(const uint8_t *buf, size_t len) { const unsigned char *p = buf; unsigned char *der = NULL; X509 *x509 = d2i_X509(NULL, &p, len); if (x509 != NULL) { BIO *bio = BIO_new(BIO_s_null()); /* This will load and print the public key as well as extensions */ X509_print(bio, x509); BIO_free(bio); i2d_X509(x509, &der); OPENSSL_free(der); X509_free(x509); } ERR_clear_error(); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Test that X509_issuer_and_serial_hash doesn't crash Provide a certificate with a bad issuer and check that X509_issuer_and_serial_hash doesn't crash. Reviewed-by: Richard Levitte <levitte@openssl.org> 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: oauth2_jwt_body_process(const struct oauth2_settings *set, const char *alg, const char *kid, ARRAY_TYPE(oauth2_field) *fields, struct json_tree *tree, const char *const *blobs, const char **error_r) { const char *sub = get_field(tree, "sub"); int ret; int64_t t0 = time(NULL); /* default IAT and NBF to now */ int64_t iat, nbf, exp; int tz_offset ATTR_UNUSED; if (sub == NULL) { *error_r = "Missing 'sub' field"; return -1; } if ((ret = get_time_field(tree, "exp", &exp)) < 1) { *error_r = t_strdup_printf("%s 'exp' field", ret == 0 ? "Missing" : "Malformed"); return -1; } if ((ret = get_time_field(tree, "nbf", &nbf)) < 0) { *error_r = "Malformed 'nbf' field"; return -1; } else if (ret == 0 || nbf == 0) nbf = t0; if ((ret = get_time_field(tree, "iat", &iat)) < 0) { *error_r = "Malformed 'iat' field"; return -1; } else if (ret == 0 || iat == 0) iat = t0; if (nbf > t0) { *error_r = "Token is not valid yet"; return -1; } if (iat > t0) { *error_r = "Token is issued in future"; return -1; } if (exp < t0) { *error_r = "Token has expired"; return -1; } /* ensure token dates are not conflicting */ if (nbf < iat || exp < iat || exp < nbf) { *error_r = "Token time values are conflicting"; return -1; } const char *iss = get_field(tree, "iss"); if (set->issuers != NULL && *set->issuers != NULL) { if (iss == NULL) { *error_r = "Token is missing 'iss' field"; return -1; } if (!str_array_find(set->issuers, iss)) { *error_r = t_strdup_printf("Issuer '%s' is not allowed", str_sanitize_utf8(iss, 128)); return -1; } } /* see if there is azp */ const char *azp = get_field(tree, "azp"); if (azp == NULL) azp = "default"; if (oauth2_validate_signature(set, azp, alg, kid, blobs, error_r) < 0) return -1; oauth2_jwt_copy_fields(fields, tree); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-22'], 'message': 'lib-oauth2: Ensure azp is escaped too'</s>
<s>[INST] Given the following code containing errors, provide 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 Http2Stream::SubmitRstStream(const uint32_t code) { CHECK(!this->is_destroyed()); code_ = code; // If RST_STREAM frame is received and stream is not writable // because it is busy reading data, don't try force purging it. // Instead add the stream to pending stream list and process // the pending data when it is safe to do so. This is to avoid // double free error due to unwanted behavior of nghttp2. // Ref:https://github.com/nodejs/node/issues/38964 // Add stream to the pending list if it is received with scope // below in the stack. The pending list may not get processed // if RST_STREAM received is not in scope and added to the list // causing endpoint to hang. if (session_->is_in_scope() && !is_writable() && is_reading()) { session_->AddPendingRstStream(id_); return; } // If possible, force a purge of any currently pending data here to make sure // it is sent before closing the stream. If it returns non-zero then we need // to wait until the current write finishes and try again to avoid nghttp2 // behaviour where it prioritizes RstStream over everything else. if (session_->SendPendingData() != 0) { session_->AddPendingRstStream(id_); return; } FlushRstStream(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'http2: update handling of rst_stream with error code NGHTTP2_CANCEL The PR updates the handling of rst_stream frames and adds all streams to the pending list on receiving rst frames with the error code NGHTTP2_CANCEL. The changes will remove dependency on the stream state that may allow bypassing the checks in certain cases. I think a better solution is to delay streams in all cases if rst_stream is received for the cancel events. The rst_stream frames can be received for protocol/connection error as well it should be handled immediately. Adding streams to the pending list in such cases may cause errors. CVE-ID: CVE-2021-22930 Refs: https://nvd.nist.gov/vuln/detail/CVE-2021-22930 PR-URL: https://github.com/nodejs/node/pull/39622 Refs: https://github.com/nodejs/node/pull/39423 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Beth Griggs <bgriggs@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ia5casecmp(const char *s1, const char *s2) { return ia5ncasecmp(s1, s2, SIZE_MAX); } ; 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>
<s>[INST] Given the following code containing errors, provide 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_verify_cert_chain(SSL *s, STACK_OF(X509) *sk) { X509 *x; int i = 0; X509_STORE *verify_store; X509_STORE_CTX *ctx = NULL; X509_VERIFY_PARAM *param; if ((sk == NULL) || (sk_X509_num(sk) == 0)) return 0; if (s->cert->verify_store) verify_store = s->cert->verify_store; else verify_store = s->ctx->cert_store; ctx = X509_STORE_CTX_new_ex(s->ctx->libctx, s->ctx->propq); if (ctx == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE); return 0; } x = sk_X509_value(sk, 0); if (!X509_STORE_CTX_init(ctx, verify_store, x, sk)) { ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB); goto end; } param = X509_STORE_CTX_get0_param(ctx); /* * XXX: Separate @AUTHSECLEVEL and @TLSSECLEVEL would be useful at some * point, for now a single @SECLEVEL sets the same policy for TLS crypto * and PKI authentication. */ X509_VERIFY_PARAM_set_auth_level(param, SSL_get_security_level(s)); /* Set suite B flags if needed */ X509_STORE_CTX_set_flags(ctx, tls1_suiteb(s)); if (!X509_STORE_CTX_set_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s)) { goto end; } /* Verify via DANE if enabled */ if (DANETLS_ENABLED(&s->dane)) X509_STORE_CTX_set0_dane(ctx, &s->dane); /* * We need to inherit the verify parameters. These can be determined by * the context: if its a server it will verify SSL client certificates or * vice versa. */ X509_STORE_CTX_set_default(ctx, s->server ? "ssl_client" : "ssl_server"); /* * Anything non-default in "s->param" should overwrite anything in the ctx. */ X509_VERIFY_PARAM_set1(param, s->param); if (s->verify_callback) X509_STORE_CTX_set_verify_cb(ctx, s->verify_callback); if (s->ctx->app_verify_callback != NULL) i = s->ctx->app_verify_callback(ctx, s->ctx->app_verify_arg); else i = X509_verify_cert(ctx); s->verify_result = X509_STORE_CTX_get_error(ctx); sk_X509_pop_free(s->verified_chain, X509_free); s->verified_chain = NULL; if (X509_STORE_CTX_get0_chain(ctx) != NULL) { s->verified_chain = X509_STORE_CTX_get1_chain(ctx); if (s->verified_chain == NULL) { ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE); i = 0; } } /* Move peername from the store context params to the SSL handle's */ X509_VERIFY_PARAM_move_peername(s->param, param); end: X509_STORE_CTX_free(ctx); return i; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'Fix invalid handling of verify errors in libssl In the event that X509_verify() returned an internal error result then libssl would mishandle this and set rwstate to SSL_RETRY_VERIFY. This subsequently causes SSL_get_error() to return SSL_ERROR_WANT_RETRY_VERIFY. That return code is supposed to only ever be returned if an application is using an app verify callback to complete replace the use of X509_verify(). Applications may not be written to expect that return code and could therefore crash (or misbehave in some other way) as a result. CVE-2021-4044 Reviewed-by: Tomas Mraz <tomas@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 X509Certificate::InfoAccess(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); X509Certificate* cert; ASSIGN_OR_RETURN_UNWRAP(&cert, args.Holder()); BIOPointer bio(BIO_new(BIO_s_mem())); Local<Value> ret; if (GetInfoString<NID_info_access>(env, bio, cert->get()).ToLocal(&ret)) args.GetReturnValue().Set(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-295'], 'message': 'crypto,tls: implement safe x509 GeneralName format This change introduces JSON-compatible escaping rules for strings that include X.509 GeneralName components (see RFC 5280). This non-standard format avoids ambiguities and prevents injection attacks that could previously lead to X.509 certificates being accepted even though they were not valid for the target hostname. These changes affect the format of subject alternative names and the format of authority information access. The checkServerIdentity function has been modified to safely handle the new format, eliminating the possibility of injecting subject alternative names into the verification logic. Because each subject alternative name is only encoded as a JSON string literal if necessary for security purposes, this change will only be visible in rare cases. This addresses CVE-2021-44532. CVE-ID: CVE-2021-44532 PR-URL: https://github.com/nodejs-private/node-private/pull/300 Reviewed-By: Michael Dawson <midawson@redhat.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 bool fix_vcol_expr(THD *thd, Virtual_column_info *vcol) { DBUG_ENTER("fix_vcol_expr"); const enum enum_column_usage saved_column_usage= thd->column_usage; thd->column_usage= COLUMNS_WRITE; int error= vcol->expr->fix_fields(thd, &vcol->expr); thd->column_usage= saved_column_usage; if (unlikely(error)) { StringBuffer<MAX_FIELD_WIDTH> str; vcol->print(&str); my_error(ER_ERROR_EVALUATING_EXPRESSION, MYF(0), str.c_ptr_safe()); DBUG_RETURN(1); } DBUG_RETURN(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-24176 Preparations 1. moved fix_vcol_exprs() call to open_table() mysql_alter_table() doesn't do lock_tables() so it cannot win from fix_vcol_exprs() from there. Tests affected: main.default_session 2. Vanilla cleanups and comments.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static bool check_vcol_forward_refs(Field *field, Virtual_column_info *vcol, bool check_constraint) { bool res; uint32 flags= field->flags; if (check_constraint) { /* Check constraints can refer it itself */ field->flags|= NO_DEFAULT_VALUE_FLAG; } res= (vcol && vcol->expr->walk(&Item::check_field_expression_processor, 0, field)); field->flags= flags; return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-24176 Preparations 1. moved fix_vcol_exprs() call to open_table() mysql_alter_table() doesn't do lock_tables() so it cannot win from fix_vcol_exprs() from there. Tests affected: main.default_session 2. Vanilla cleanups and comments.'</s>
<s>[INST] Given the following code containing errors, provide 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 TABLE::update_default_fields(bool ignore_errors) { Query_arena backup_arena; Field **field_ptr; int res= 0; DBUG_ENTER("TABLE::update_default_fields"); DBUG_ASSERT(default_field); in_use->set_n_backup_active_arena(expr_arena, &backup_arena); /* Iterate over fields with default functions in the table */ for (field_ptr= default_field; *field_ptr ; field_ptr++) { Field *field= (*field_ptr); /* If an explicit default value for a field overrides the default, do not update the field with its automatic default value. */ if (!field->has_explicit_value()) { if (field->default_value && (field->default_value->flags || field->flags & BLOB_FLAG)) res|= (field->default_value->expr->save_in_field(field, 0) < 0); if (!ignore_errors && res) { my_error(ER_CALCULATING_DEFAULT_VALUE, MYF(0), field->field_name.str); break; } res= 0; } } in_use->restore_active_arena(expr_arena, &backup_arena); DBUG_RETURN(res); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-703'], 'message': 'MDEV-24176 Server crashes after insert in the table with virtual column generated using date_format() and if() vcol_info->expr is allocated on expr_arena at parsing stage. Since expr item is allocated on expr_arena all its containee items must be allocated on expr_arena too. Otherwise fix_session_expr() will encounter prematurely freed item. When table is reopened from cache vcol_info contains stale expression. We refresh expression via TABLE::vcol_fix_exprs() but first we must prepare a proper context (Vcol_expr_context) which meets some requirements: 1. As noted above expr update must be done on expr_arena as there may be new items created. It was a bug in fix_session_expr_for_read() and was just not reproduced because of no second refix. Now refix is done for more cases so it does reproduce. Tests affected: vcol.binlog 2. Also name resolution context must be narrowed to the single table. Tested by: vcol.update main.default vcol.vcol_syntax gcol.gcol_bugfixes 3. sql_mode must be clean and not fail expr update. sql_mode such as MODE_NO_BACKSLASH_ESCAPES, MODE_NO_ZERO_IN_DATE, etc must not affect vcol expression update. If the table was created successfully any further evaluation must not fail. Tests affected: main.func_like Reviewed by: Sergei Golubchik <serg@mariadb.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: Table_arena(MEM_ROOT *mem_root, enum enum_state state_arg) : Query_arena(mem_root, state_arg){} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'MDEV-26281 ASAN use-after-poison when complex conversion is involved in blob the bug was that in_vector array in Item_func_in was allocated in the statement arena, not in the table->expr_arena. revert part of the 5acd391e8b2d. Instead, change the arena correctly in fix_all_session_vcol_exprs(). Remove TABLE_ARENA, that was introduced in 5acd391e8b2d to force item tree changes to be rolled back (because they were allocated in the wrong arena and didn't persist. now they do)'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Field_new_decimal::Field_new_decimal(uchar *ptr_arg, uint32 len_arg, uchar *null_ptr_arg, uchar null_bit_arg, enum utype unireg_check_arg, const char *field_name_arg, uint8 dec_arg,bool zero_arg, bool unsigned_arg) :Field_num(ptr_arg, len_arg, null_ptr_arg, null_bit_arg, unireg_check_arg, field_name_arg, dec_arg, zero_arg, unsigned_arg) { precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg); set_if_smaller(precision, DECIMAL_MAX_PRECISION); DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) && (dec <= DECIMAL_MAX_SCALE)); bin_size= my_decimal_get_binary_size(precision, dec); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120'], 'message': 'MDEV-25317 Assertion `scale <= precision' failed in decimal_bin_size And Assertion `scale >= 0 && precision > 0 && scale <= precision' failed in decimal_bin_size_inline/decimal_bin_size. Precision should be kept below DECIMAL_MAX_SCALE for computations. It can be bigger in Item_decimal. I'd fix this too but it changes the existing behaviour so problemmatic to ix.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xbstream_open(ds_ctxt_t *ctxt, const char *path, MY_STAT *mystat) { ds_file_t *file; ds_stream_file_t *stream_file; ds_stream_ctxt_t *stream_ctxt; ds_ctxt_t *dest_ctxt; xb_wstream_t *xbstream; xb_wstream_file_t *xbstream_file; xb_ad(ctxt->pipe_ctxt != NULL); dest_ctxt = ctxt->pipe_ctxt; stream_ctxt = (ds_stream_ctxt_t *) ctxt->ptr; pthread_mutex_lock(&stream_ctxt->mutex); if (stream_ctxt->dest_file == NULL) { stream_ctxt->dest_file = ds_open(dest_ctxt, path, mystat); if (stream_ctxt->dest_file == NULL) { return NULL; } } pthread_mutex_unlock(&stream_ctxt->mutex); file = (ds_file_t *) my_malloc(sizeof(ds_file_t) + sizeof(ds_stream_file_t), MYF(MY_FAE)); stream_file = (ds_stream_file_t *) (file + 1); xbstream = stream_ctxt->xbstream; xbstream_file = xb_stream_write_open(xbstream, path, mystat, stream_ctxt, my_xbstream_write_callback); if (xbstream_file == NULL) { msg("xb_stream_write_open() failed."); goto err; } stream_file->xbstream_file = xbstream_file; stream_file->stream_ctxt = stream_ctxt; file->ptr = stream_file; file->path = stream_ctxt->dest_file->path; return file; err: if (stream_ctxt->dest_file) { ds_close(stream_ctxt->dest_file); stream_ctxt->dest_file = NULL; } my_free(file); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-667'], 'message': 'MDEV-26574 An improper locking bug due to unreleased lock in the ds_xbstream.cc release lock in all as cases n xbstream_open, also fix the case where malloc would return NULL.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: zfs_fastaccesschk_execute(znode_t *zdp, cred_t *cr) { boolean_t owner = B_FALSE; boolean_t groupmbr = B_FALSE; boolean_t is_attr; uid_t uid = crgetuid(cr); if (zdp->z_pflags & ZFS_AV_QUARANTINED) return (1); is_attr = ((zdp->z_pflags & ZFS_XATTR) && (ZTOV(zdp)->v_type == VDIR)); if (is_attr) return (1); if (zdp->z_pflags & ZFS_NO_EXECS_DENIED) return (0); mutex_enter(&zdp->z_acl_lock); if (FUID_INDEX(zdp->z_uid) != 0 || FUID_INDEX(zdp->z_gid) != 0) { goto out_slow; } if (uid == zdp->z_uid) { owner = B_TRUE; if (zdp->z_mode & S_IXUSR) { goto out; } else { goto out_slow; } } if (groupmember(zdp->z_gid, cr)) { groupmbr = B_TRUE; if (zdp->z_mode & S_IXGRP) { goto out; } else { goto out_slow; } } if (!owner && !groupmbr) { if (zdp->z_mode & S_IXOTH) { goto out; } } out: mutex_exit(&zdp->z_acl_lock); return (0); out_slow: mutex_exit(&zdp->z_acl_lock); return (1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-732'], 'message': 'FreeBSD: Fix UNIX permissions checking Reviewed-by: Ryan Moeller <ryan@iXsystems.com> Reviewed-by: Brian Behlendorf <behlendorf1@llnl.gov> Signed-off-by: Matt Macy <mmacy@FreeBSD.org> Closes #10727'</s>
<s>[INST] Given the following code containing errors, provide 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 st_select_lex_node* get_slave() { return slave; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703'], 'message': 'MDEV-22001: Server crashes in st_select_lex_unit::exclude_level upon execution of SP Running some statements that use IN subqueries outside context of a regular query could result in server abnormal termination. The reason for failure is that internal structures SELECT_LEX/SELECT_LEX_UNIT created on behalf of parsed query were initialized incorrectly. Incorrect initialization of the structures SELECT_LEX/SELECT_LEX_UNIT was introduced by the commit de745ecf29721795710910a19bd0ea3389da804c (MDEV-11953: support of brackets in UNION/EXCEPT/INTERSECT operations) pushed into 10.4, that is the reason this bug report is not reproduced in 10.3. To fix the issue the method SLECTE_LEX::register_unit is used for proper initialization of the data structures SELECT_LEX/SELECT_LEX_UNIT. Additionally, the method SELECT_LEX::get_slave() was removed from the source code base since for those use cases where it is used it can be replaced by the method first_inner_unit().'</s>
<s>[INST] Given the following code containing errors, provide 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_write_bytes(SSL *s, int type, const void *buf_, int len) { const unsigned char *buf = buf_; int tot; unsigned int n, split_send_fragment, maxpipes; #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK unsigned int max_send_fragment, nw; unsigned int u_len = (unsigned int)len; #endif SSL3_BUFFER *wb = &s->rlayer.wbuf[0]; int i; if (len < 0) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_NEGATIVE_LENGTH); return -1; } s->rwstate = SSL_NOTHING; tot = s->rlayer.wnum; /* * ensure that if we end up with a smaller value of data to write out * than the the original len from a write which didn't complete for * non-blocking I/O and also somehow ended up avoiding the check for * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be * possible to end up with (len-tot) as a large number that will then * promptly send beyond the end of the users buffer ... so we trap and * report the error in a way the user will notice */ if ((unsigned int)len < s->rlayer.wnum) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH); return -1; } s->rlayer.wnum = 0; if (SSL_in_init(s) && !ossl_statem_get_in_handshake(s)) { i = s->handshake_func(s); if (i < 0) return (i); if (i == 0) { SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE); return -1; } } /* * first check if there is a SSL3_BUFFER still being written out. This * will happen with non blocking IO */ if (wb->left != 0) { i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->rlayer.wnum = tot; return i; } tot += i; /* this might be last fragment */ } #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK /* * Depending on platform multi-block can deliver several *times* * better performance. Downside is that it has to allocate * jumbo buffer to accommodate up to 8 records, but the * compromise is considered worthy. */ if (type == SSL3_RT_APPLICATION_DATA && u_len >= 4 * (max_send_fragment = s->max_send_fragment) && s->compress == NULL && s->msg_callback == NULL && !SSL_USE_ETM(s) && SSL_USE_EXPLICIT_IV(s) && EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) { unsigned char aad[13]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; int packlen; /* minimize address aliasing conflicts */ if ((max_send_fragment & 0xfff) == 0) max_send_fragment -= 512; if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */ ssl3_release_write_buffer(s); packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE, max_send_fragment, NULL); if (u_len >= 8 * max_send_fragment) packlen *= 8; else packlen *= 4; if (!ssl3_setup_write_buffer(s, 1, packlen)) { SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_MALLOC_FAILURE); return -1; } } else if (tot == len) { /* done? */ /* free jumbo buffer */ ssl3_release_write_buffer(s); return tot; } n = (len - tot); for (;;) { if (n < 4 * max_send_fragment) { /* free jumbo buffer */ ssl3_release_write_buffer(s); break; } if (s->s3->alert_dispatch) { i = s->method->ssl_dispatch_alert(s); if (i <= 0) { s->rlayer.wnum = tot; return i; } } if (n >= 8 * max_send_fragment) nw = max_send_fragment * (mb_param.interleave = 8); else nw = max_send_fragment * (mb_param.interleave = 4); memcpy(aad, s->rlayer.write_sequence, 8); aad[8] = type; aad[9] = (unsigned char)(s->version >> 8); aad[10] = (unsigned char)(s->version); aad[11] = 0; aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = nw; packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen <= 0 || packlen > (int)wb->len) { /* never happens */ /* free jumbo buffer */ ssl3_release_write_buffer(s); break; } mb_param.out = wb->buf; mb_param.inp = &buf[tot]; mb_param.len = nw; if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param) <= 0) return -1; s->rlayer.write_sequence[7] += mb_param.interleave; if (s->rlayer.write_sequence[7] < mb_param.interleave) { int j = 6; while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ; } wb->offset = 0; wb->left = packlen; s->rlayer.wpend_tot = nw; s->rlayer.wpend_buf = &buf[tot]; s->rlayer.wpend_type = type; s->rlayer.wpend_ret = nw; i = ssl3_write_pending(s, type, &buf[tot], nw); if (i <= 0) { if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) { /* free jumbo buffer */ ssl3_release_write_buffer(s); } s->rlayer.wnum = tot; return i; } if (i == (int)n) { /* free jumbo buffer */ ssl3_release_write_buffer(s); return tot + i; } n -= i; tot += i; } } else #endif if (tot == len) { /* done? */ if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot; } n = (len - tot); split_send_fragment = s->split_send_fragment; /* * If max_pipelines is 0 then this means "undefined" and we default to * 1 pipeline. Similarly if the cipher does not support pipelined * processing then we also only use 1 pipeline, or if we're not using * explicit IVs */ maxpipes = s->max_pipelines; if (maxpipes > SSL_MAX_PIPELINES) { /* * We should have prevented this when we set max_pipelines so we * shouldn't get here */ SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR); return -1; } if (maxpipes == 0 || s->enc_write_ctx == NULL || !(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) & EVP_CIPH_FLAG_PIPELINE) || !SSL_USE_EXPLICIT_IV(s)) maxpipes = 1; if (s->max_send_fragment == 0 || split_send_fragment > s->max_send_fragment || split_send_fragment == 0) { /* * We should have prevented this when we set the split and max send * fragments so we shouldn't get here */ SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR); return -1; } for (;;) { unsigned int pipelens[SSL_MAX_PIPELINES], tmppipelen, remain; unsigned int numpipes, j; if (n == 0) numpipes = 1; else numpipes = ((n - 1) / split_send_fragment) + 1; if (numpipes > maxpipes) numpipes = maxpipes; if (n / numpipes >= s->max_send_fragment) { /* * We have enough data to completely fill all available * pipelines */ for (j = 0; j < numpipes; j++) { pipelens[j] = s->max_send_fragment; } } else { /* We can partially fill all available pipelines */ tmppipelen = n / numpipes; remain = n % numpipes; for (j = 0; j < numpipes; j++) { pipelens[j] = tmppipelen; if (j < remain) pipelens[j]++; } } i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0); if (i <= 0) { /* XXX should we ssl3_release_write_buffer if i<0? */ s->rlayer.wnum = tot; return i; } if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA && (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) { /* * next chunk of data should get another prepended empty fragment * in ciphersuites with known-IV weakness: */ s->s3->empty_fragment_done = 0; if ((i == (int)n) && s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) ssl3_release_write_buffer(s); return tot + i; } n -= i; tot += i; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 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: passdb_preinit(pool_t pool, const struct auth_passdb_settings *set) { static unsigned int auth_passdb_id = 0; struct passdb_module_interface *iface; struct passdb_module *passdb; unsigned int idx; iface = passdb_interface_find(set->driver); if (iface == NULL || iface->verify_plain == NULL) { /* maybe it's a plugin. try to load it. */ auth_module_load(t_strconcat("authdb_", set->driver, NULL)); iface = passdb_interface_find(set->driver); } if (iface == NULL) i_fatal("Unknown passdb driver '%s'", set->driver); if (iface->verify_plain == NULL) { i_fatal("Support not compiled in for passdb driver '%s'", set->driver); } if (iface->preinit == NULL && iface->init == NULL && *set->args != '\0') { i_fatal("passdb %s: No args are supported: %s", set->driver, set->args); } passdb = passdb_find(set->driver, set->args, &idx); if (passdb != NULL) return passdb; if (iface->preinit == NULL) passdb = p_new(pool, struct passdb_module, 1); else passdb = iface->preinit(pool, set->args); passdb->id = ++auth_passdb_id; passdb->iface = *iface; passdb->args = p_strdup(pool, set->args); if (*set->mechanisms == '\0') { passdb->mechanisms = NULL; } else if (strcasecmp(set->mechanisms, "none") == 0) { passdb->mechanisms = (const char *const[]){NULL}; } else { passdb->mechanisms = (const char* const*)p_strsplit_spaces(pool, set->mechanisms, " ,"); } if (*set->username_filter == '\0') { passdb->username_filter = NULL; } else { passdb->username_filter = (const char* const*)p_strsplit_spaces(pool, set->username_filter, " ,"); } array_push_back(&passdb_modules, &passdb); return passdb; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'auth: Fix handling passdbs with identical driver/args but different mechanisms/username_filter The passdb was wrongly deduplicated in this situation, causing wrong mechanisms or username_filter setting to be used. This would be a rather unlikely configuration though. Fixed by moving mechanisms and username_filter from struct passdb_module to struct auth_passdb, which is where they should have been in the first place.'</s>
<s>[INST] Given the following code containing errors, provide 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 php_sqlite3_collation_callback(void *context, int string1_len, const void *string1, int string2_len, const void *string2) { int ret; zval *zstring1, *zstring2; zval **zargs[2]; zval *retval = NULL; struct pdo_sqlite_collation *collation = (struct pdo_sqlite_collation*) context; TSRMLS_FETCH(); collation->fc.fci.size = sizeof(collation->fc.fci); collation->fc.fci.function_table = EG(function_table); collation->fc.fci.function_name = collation->callback; collation->fc.fci.symbol_table = NULL; collation->fc.fci.object_ptr = NULL; collation->fc.fci.retval_ptr_ptr = &retval; // Prepare the arguments. MAKE_STD_ZVAL(zstring1); ZVAL_STRINGL(zstring1, (char *) string1, string1_len, 1); zargs[0] = &zstring1; MAKE_STD_ZVAL(zstring2); ZVAL_STRINGL(zstring2, (char *) string2, string2_len, 1); zargs[1] = &zstring2; collation->fc.fci.param_count = 2; collation->fc.fci.params = zargs; if ((ret = zend_call_function(&collation->fc.fci, &collation->fc.fcc TSRMLS_CC)) == FAILURE) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An error occurred while invoking the callback"); } else if (retval) { if (Z_TYPE_P(retval) != IS_LONG) { convert_to_long_ex(&retval); } ret = 0; if (Z_LVAL_P(retval) > 0) { ret = 1; } else if (Z_LVAL_P(retval) < 0) { ret = -1; } zval_ptr_dtor(&retval); } zval_ptr_dtor(zargs[0]); zval_ptr_dtor(zargs[1]); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'</s>
<s>[INST] Given the following code containing errors, provide 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 PHP_METHOD(SQLite, sqliteCreateAggregate) { struct pdo_sqlite_func *func; zval *step_callback, *fini_callback; char *func_name; int func_name_len; long argc = -1; char *cbname = NULL; pdo_dbh_t *dbh; pdo_sqlite_db_handle *H; int ret; if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szz|l", &func_name, &func_name_len, &step_callback, &fini_callback, &argc)) { RETURN_FALSE; } dbh = zend_object_store_get_object(getThis() TSRMLS_CC); PDO_CONSTRUCT_CHECK; if (!zend_is_callable(step_callback, 0, &cbname TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "function '%s' is not callable", cbname); efree(cbname); RETURN_FALSE; } efree(cbname); if (!zend_is_callable(fini_callback, 0, &cbname TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "function '%s' is not callable", cbname); efree(cbname); RETURN_FALSE; } efree(cbname); H = (pdo_sqlite_db_handle *)dbh->driver_data; func = (struct pdo_sqlite_func*)ecalloc(1, sizeof(*func)); ret = sqlite3_create_function(H->db, func_name, argc, SQLITE_UTF8, func, NULL, php_sqlite3_func_step_callback, php_sqlite3_func_final_callback); if (ret == SQLITE_OK) { func->funcname = estrdup(func_name); MAKE_STD_ZVAL(func->step); MAKE_COPY_ZVAL(&step_callback, func->step); MAKE_STD_ZVAL(func->fini); MAKE_COPY_ZVAL(&fini_callback, func->fini); func->argc = argc; func->next = H->funcs; H->funcs = func; RETURN_TRUE; } efree(func); RETURN_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'</s>
<s>[INST] Given the following code containing errors, provide 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 PHP_METHOD(SQLite, sqliteCreateFunction) { struct pdo_sqlite_func *func; zval *callback; char *func_name; int func_name_len; long argc = -1; char *cbname = NULL; pdo_dbh_t *dbh; pdo_sqlite_db_handle *H; int ret; if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|l", &func_name, &func_name_len, &callback, &argc)) { RETURN_FALSE; } dbh = zend_object_store_get_object(getThis() TSRMLS_CC); PDO_CONSTRUCT_CHECK; if (!zend_is_callable(callback, 0, &cbname TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "function '%s' is not callable", cbname); efree(cbname); RETURN_FALSE; } efree(cbname); H = (pdo_sqlite_db_handle *)dbh->driver_data; func = (struct pdo_sqlite_func*)ecalloc(1, sizeof(*func)); ret = sqlite3_create_function(H->db, func_name, argc, SQLITE_UTF8, func, php_sqlite3_func_callback, NULL, NULL); if (ret == SQLITE_OK) { func->funcname = estrdup(func_name); MAKE_STD_ZVAL(func->func); MAKE_COPY_ZVAL(&callback, func->func); func->argc = argc; func->next = H->funcs; H->funcs = func; RETURN_TRUE; } efree(func); RETURN_FALSE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-264'], 'message': 'Improve check for :memory: pseudo-filename in SQlite'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_8)(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { int x,y; uint8_t p; dstpitch -= bltwidth; srcpitch -= bltwidth; for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x++) { p = *dst; ROP_OP(p, *src); if (p != s->gr[0x34]) *dst = p; dst++; src++; } dst += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2007-1320 - Cirrus LGD-54XX "bitblt" heap overflow I have just noticed that patch for CVE-2007-1320 has never been applied to the QEMU CVS. Please find it below. | Multiple heap-based buffer overflows in the cirrus_invalidate_region | function in the Cirrus VGA extension in QEMU 0.8.2, as used in Xen and | possibly other products, might allow local users to execute arbitrary | code via unspecified vectors related to "attempting to mark | non-existent regions as dirty," aka the "bitblt" heap overflow. git-svn-id: svn://svn.savannah.nongnu.org/qemu/trunk@4340 c046a42c-6fe2-441c-8c8c-71466251a162'</s>