text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rfbBool HandleCursorShape(rfbClient* client,int xhot, int yhot, int width, int height, uint32_t enc) { int bytesPerPixel; size_t bytesPerRow, bytesMaskData; rfbXCursorColors rgb; uint32_t colors[2]; char *buf; uint8_t *ptr; int x, y, b; bytesPerPixel = client->format.bitsPerPixel / 8; bytesPerRow = (width + 7) / 8; bytesMaskData = bytesPerRow * height; if (width * height == 0) return TRUE; /* Allocate memory for pixel data and temporary mask data. */ if(client->rcSource) free(client->rcSource); client->rcSource = malloc(width * height * bytesPerPixel); if (client->rcSource == NULL) return FALSE; buf = malloc(bytesMaskData); if (buf == NULL) { free(client->rcSource); client->rcSource = NULL; return FALSE; } /* Read and decode cursor pixel data, depending on the encoding type. */ if (enc == rfbEncodingXCursor) { /* Read and convert background and foreground colors. */ if (!ReadFromRFBServer(client, (char *)&rgb, sz_rfbXCursorColors)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } colors[0] = RGB24_TO_PIXEL(32, rgb.backRed, rgb.backGreen, rgb.backBlue); colors[1] = RGB24_TO_PIXEL(32, rgb.foreRed, rgb.foreGreen, rgb.foreBlue); /* Read 1bpp pixel data into a temporary buffer. */ if (!ReadFromRFBServer(client, buf, bytesMaskData)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } /* Convert 1bpp data to byte-wide color indices. */ ptr = client->rcSource; for (y = 0; y < height; y++) { for (x = 0; x < width / 8; x++) { for (b = 7; b >= 0; b--) { *ptr = buf[y * bytesPerRow + x] >> b & 1; ptr += bytesPerPixel; } } for (b = 7; b > 7 - width % 8; b--) { *ptr = buf[y * bytesPerRow + x] >> b & 1; ptr += bytesPerPixel; } } /* Convert indices into the actual pixel values. */ switch (bytesPerPixel) { case 1: for (x = 0; x < width * height; x++) client->rcSource[x] = (uint8_t)colors[client->rcSource[x]]; break; case 2: for (x = 0; x < width * height; x++) ((uint16_t *)client->rcSource)[x] = (uint16_t)colors[client->rcSource[x * 2]]; break; case 4: for (x = 0; x < width * height; x++) ((uint32_t *)client->rcSource)[x] = colors[client->rcSource[x * 4]]; break; } } else { /* enc == rfbEncodingRichCursor */ if (!ReadFromRFBServer(client, (char *)client->rcSource, width * height * bytesPerPixel)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } } /* Read and decode mask data. */ if (!ReadFromRFBServer(client, buf, bytesMaskData)) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } client->rcMask = malloc(width * height); if (client->rcMask == NULL) { free(client->rcSource); client->rcSource = NULL; free(buf); return FALSE; } ptr = client->rcMask; for (y = 0; y < height; y++) { for (x = 0; x < width / 8; x++) { for (b = 7; b >= 0; b--) { *ptr++ = buf[y * bytesPerRow + x] >> b & 1; } } for (b = 7; b > 7 - width % 8; b--) { *ptr++ = buf[y * bytesPerRow + x] >> b & 1; } } if (client->GotCursorShape != NULL) { client->GotCursorShape(client, xhot, yhot, width, height, bytesPerPixel); } free(buf); return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'libvncclient/cursor: limit width/height input values Avoids a possible heap overflow reported by Pavel Cheremushkin <Pavel.Cheremushkin@kaspersky.com>. re #275'</s>
<s>[INST] Given the following code containing errors, provide 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 RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; string expires = get_s3_expiration_header(s, lastmod); if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); dump_header_if_nonempty(s, "x-amz-expiration", expires); if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) { dump_header(s, "x-rgw-object-type", "Appendable"); dump_header(s, "x-rgw-next-append-position", s->obj_size); } else { dump_header(s, "x-rgw-object-type", "Normal"); } if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ size_t len = iter->second.length(); string s(iter->second.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } response_attrs[aiter->second] = s; } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type_str = rgw_bl_str(iter->second); content_type = content_type_str.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ auto it = iter->second.cbegin(); obj_tags.decode(it); } catch (buffer::error &err) { ldpp_dout(this,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){ RGWObjectRetention retention; try { decode(retention, iter->second); dump_header(s, "x-amz-object-lock-mode", retention.get_mode()); dump_time_header(s, "x-amz-object-lock-retain-until-date", retention.get_retain_until_date()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl; } } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) { RGWObjectLegalHold legal_hold; try { decode(legal_hold, iter->second); dump_header(s, "x-amz-object-lock-legal-hold",legal_hold.get_status()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl; } } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: reject unauthenticated response-header actions Signed-off-by: Matt Benjamin <mbenjamin@redhat.com> Reviewed-by: Casey Bodley <cbodley@redhat.com> (cherry picked from commit d8dd5e513c0c62bbd7d3044d7e2eddcd897bd400)'</s>
<s>[INST] Given the following code containing errors, provide 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 RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; string expires = get_s3_expiration_header(s, lastmod); if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldpp_dout(this, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); dump_header_if_nonempty(s, "x-amz-expiration", expires); if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) { dump_header(s, "x-rgw-object-type", "Appendable"); dump_header(s, "x-rgw-next-append-position", s->obj_size); } else { dump_header(s, "x-rgw-object-type", "Normal"); } if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { /* reject unauthenticated response header manipulation, see * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */ if (s->auth.identity->is_anonymous()) { return -ERR_INVALID_REQUEST; } if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ size_t len = iter->second.length(); string s(iter->second.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } response_attrs[aiter->second] = s; } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type_str = rgw_bl_str(iter->second); content_type = content_type_str.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ auto it = iter->second.cbegin(); obj_tags.decode(it); } catch (buffer::error &err) { ldpp_dout(this,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){ RGWObjectRetention retention; try { decode(retention, iter->second); dump_header(s, "x-amz-object-lock-mode", retention.get_mode()); dump_time_header(s, "x-amz-object-lock-retain-until-date", retention.get_retain_until_date()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl; } } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) { RGWObjectLegalHold legal_hold; try { decode(legal_hold, iter->second); dump_header(s, "x-amz-object-lock-legal-hold",legal_hold.get_status()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl; } } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: reject control characters in response-header actions S3 GetObject permits overriding response header values, but those inputs need to be validated to insure only characters that are valid in an HTTP header value are present. Credit: Initial vulnerability discovery by William Bowling (@wcbowling) Credit: Further vulnerability discovery by Robin H. Johnson <rjohnson@digitalocean.com> Signed-off-by: Robin H. Johnson <rjohnson@digitalocean.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 RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); if (attrs.find(RGW_ATTR_APPEND_PART_NUM) != attrs.end()) { dump_header(s, "x-rgw-object-type", "Appendable"); dump_header(s, "x-rgw-next-append-position", s->obj_size); } else { dump_header(s, "x-rgw-object-type", "Normal"); } if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { /* reject unauthenticated response header manipulation, see * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */ if (s->auth.identity->is_anonymous()) { return -EPERM; } if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ size_t len = iter->second.length(); string s(iter->second.c_str(), len); while (len && !s[len - 1]) { --len; s.resize(len); } response_attrs[aiter->second] = s; } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type_str = rgw_bl_str(iter->second); content_type = content_type_str.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ auto it = iter->second.cbegin(); obj_tags.decode(it); } catch (buffer::error &err) { ldout(s->cct,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } else if (iter->first.compare(RGW_ATTR_OBJECT_RETENTION) == 0 && get_retention){ RGWObjectRetention retention; try { decode(retention, iter->second); dump_header(s, "x-amz-object-lock-mode", retention.get_mode()); dump_time_header(s, "x-amz-object-lock-retain-until-date", retention.get_retain_until_date()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectRetention" << dendl; } } else if (iter->first.compare(RGW_ATTR_OBJECT_LEGAL_HOLD) == 0 && get_legal_hold) { RGWObjectLegalHold legal_hold; try { decode(legal_hold, iter->second); dump_header(s, "x-amz-object-lock-legal-hold",legal_hold.get_status()); } catch (buffer::error& err) { ldpp_dout(this, 0) << "ERROR: failed to decode RGWObjectLegalHold" << dendl; } } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: EPERM to ERR_INVALID_REQUEST As per Robin's comments and S3 spec Signed-off-by: Abhishek Lekshmanan <abhishek@suse.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 RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ response_attrs[aiter->second] = iter->second.c_str(); } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type = iter->second.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ bufferlist::iterator it = iter->second.begin(); obj_tags.decode(it); } catch (buffer::error &err) { ldout(s->cct,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: reject unauthenticated response-header actions Signed-off-by: Matt Benjamin <mbenjamin@redhat.com> Reviewed-by: Casey Bodley <cbodley@redhat.com> (cherry picked from commit d8dd5e513c0c62bbd7d3044d7e2eddcd897bd400)'</s>
<s>[INST] Given the following code containing errors, provide 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 RGWGetObj_ObjStore_S3::send_response_data(bufferlist& bl, off_t bl_ofs, off_t bl_len) { const char *content_type = NULL; string content_type_str; map<string, string> response_attrs; map<string, string>::iterator riter; bufferlist metadata_bl; if (sent_header) goto send_data; if (custom_http_ret) { set_req_state_err(s, 0); dump_errno(s, custom_http_ret); } else { set_req_state_err(s, (partial_content && !op_ret) ? STATUS_PARTIAL_CONTENT : op_ret); dump_errno(s); } if (op_ret) goto done; if (range_str) dump_range(s, start, end, s->obj_size); if (s->system_request && s->info.args.exists(RGW_SYS_PARAM_PREFIX "prepend-metadata")) { dump_header(s, "Rgwx-Object-Size", (long long)total_len); if (rgwx_stat) { /* * in this case, we're not returning the object's content, only the prepended * extra metadata */ total_len = 0; } /* JSON encode object metadata */ JSONFormatter jf; jf.open_object_section("obj_metadata"); encode_json("attrs", attrs, &jf); utime_t ut(lastmod); encode_json("mtime", ut, &jf); jf.close_section(); stringstream ss; jf.flush(ss); metadata_bl.append(ss.str()); dump_header(s, "Rgwx-Embedded-Metadata-Len", metadata_bl.length()); total_len += metadata_bl.length(); } if (s->system_request && !real_clock::is_zero(lastmod)) { /* we end up dumping mtime in two different methods, a bit redundant */ dump_epoch_header(s, "Rgwx-Mtime", lastmod); uint64_t pg_ver = 0; int r = decode_attr_bl_single_value(attrs, RGW_ATTR_PG_VER, &pg_ver, (uint64_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } dump_header(s, "Rgwx-Obj-PG-Ver", pg_ver); uint32_t source_zone_short_id = 0; r = decode_attr_bl_single_value(attrs, RGW_ATTR_SOURCE_ZONE, &source_zone_short_id, (uint32_t)0); if (r < 0) { ldout(s->cct, 0) << "ERROR: failed to decode pg ver attr, ignoring" << dendl; } if (source_zone_short_id != 0) { dump_header(s, "Rgwx-Source-Zone-Short-Id", source_zone_short_id); } } for (auto &it : crypt_http_responses) dump_header(s, it.first, it.second); dump_content_length(s, total_len); dump_last_modified(s, lastmod); dump_header_if_nonempty(s, "x-amz-version-id", version_id); if (! op_ret) { if (! lo_etag.empty()) { /* Handle etag of Swift API's large objects (DLO/SLO). It's entirerly * legit to perform GET on them through S3 API. In such situation, * a client should receive the composited content with corresponding * etag value. */ dump_etag(s, lo_etag); } else { auto iter = attrs.find(RGW_ATTR_ETAG); if (iter != attrs.end()) { dump_etag(s, iter->second.to_str()); } } for (struct response_attr_param *p = resp_attr_params; p->param; p++) { bool exists; string val = s->info.args.get(p->param, &exists); if (exists) { /* reject unauthenticated response header manipulation, see * https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html */ if (s->auth.identity->is_anonymous()) { return -ERR_INVALID_REQUEST; } if (strcmp(p->param, "response-content-type") != 0) { response_attrs[p->http_attr] = val; } else { content_type_str = val; content_type = content_type_str.c_str(); } } } for (auto iter = attrs.begin(); iter != attrs.end(); ++iter) { const char *name = iter->first.c_str(); map<string, string>::iterator aiter = rgw_to_http_attrs.find(name); if (aiter != rgw_to_http_attrs.end()) { if (response_attrs.count(aiter->second) == 0) { /* Was not already overridden by a response param. */ response_attrs[aiter->second] = iter->second.c_str(); } } else if (iter->first.compare(RGW_ATTR_CONTENT_TYPE) == 0) { /* Special handling for content_type. */ if (!content_type) { content_type = iter->second.c_str(); } } else if (strcmp(name, RGW_ATTR_SLO_UINDICATOR) == 0) { // this attr has an extra length prefix from encode() in prior versions dump_header(s, "X-Object-Meta-Static-Large-Object", "True"); } else if (strncmp(name, RGW_ATTR_META_PREFIX, sizeof(RGW_ATTR_META_PREFIX)-1) == 0) { /* User custom metadata. */ name += sizeof(RGW_ATTR_PREFIX) - 1; dump_header(s, name, iter->second); } else if (iter->first.compare(RGW_ATTR_TAGS) == 0) { RGWObjTags obj_tags; try{ bufferlist::iterator it = iter->second.begin(); obj_tags.decode(it); } catch (buffer::error &err) { ldout(s->cct,0) << "Error caught buffer::error couldn't decode TagSet " << dendl; } dump_header(s, RGW_AMZ_TAG_COUNT, obj_tags.count()); } } } done: for (riter = response_attrs.begin(); riter != response_attrs.end(); ++riter) { dump_header(s, riter->first, riter->second); } if (op_ret == -ERR_NOT_MODIFIED) { end_header(s, this); } else { if (!content_type) content_type = "binary/octet-stream"; end_header(s, this, content_type); } if (metadata_bl.length()) { dump_body(s, metadata_bl); } sent_header = true; send_data: if (get_data && !op_ret) { int r = dump_body(s, bl.c_str() + bl_ofs, bl_len); if (r < 0) return r; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'rgw: reject control characters in response-header actions S3 GetObject permits overriding response header values, but those inputs need to be validated to insure only characters that are valid in an HTTP header value are present. Credit: Initial vulnerability discovery by William Bowling (@wcbowling) Credit: Further vulnerability discovery by Robin H. Johnson <rjohnson@digitalocean.com> Signed-off-by: Robin H. Johnson <rjohnson@digitalocean.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 MagickBooleanType ReadHEICImageByID(const ImageInfo *image_info, Image *image,struct heif_context *heif_context,heif_item_id image_id, ExceptionInfo *exception) { const char *option; int stride_y, stride_cb, stride_cr; MagickBooleanType status; ssize_t y; struct heif_decoding_options *decode_options; struct heif_error error; struct heif_image *heif_image; struct heif_image_handle *image_handle; const uint8_t *p_y, *p_cb, *p_cr; error=heif_context_get_image_handle(heif_context,image_id,&image_handle); if (IsHeifSuccess(&error,image,exception) == MagickFalse) return(MagickFalse); if (ReadHEICColorProfile(image,image_handle,exception) == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } if (ReadHEICExifProfile(image,image_handle,exception) == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } /* Set image size. */ image->depth=8; image->columns=(size_t) heif_image_handle_get_width(image_handle); image->rows=(size_t) heif_image_handle_get_height(image_handle); if (image_info->ping != MagickFalse) { image->colorspace=YCbCrColorspace; heif_image_handle_release(image_handle); return(MagickTrue); } if (HEICSkipImage(image_info,image) != MagickFalse) { heif_image_handle_release(image_handle); return(MagickTrue); } status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } /* Copy HEIF image into ImageMagick data structures. */ (void) SetImageColorspace(image,YCbCrColorspace,exception); decode_options=(struct heif_decoding_options *) NULL; option=GetImageOption(image_info,"heic:preserve-orientation"); if (IsStringTrue(option) == MagickTrue) { decode_options=heif_decoding_options_alloc(); decode_options->ignore_transformations=1; } else (void) SetImageProperty(image,"exif:Orientation","1",exception); error=heif_decode_image(image_handle,&heif_image,heif_colorspace_YCbCr, heif_chroma_420,decode_options); if (IsHeifSuccess(&error,image,exception) == MagickFalse) { heif_image_handle_release(image_handle); return(MagickFalse); } if (decode_options != (struct heif_decoding_options *) NULL) { /* Correct the width and height of the image. */ image->columns=(size_t) heif_image_get_width(heif_image,heif_channel_Y); image->rows=(size_t) heif_image_get_height(heif_image,heif_channel_Y); status=SetImageExtent(image,image->columns,image->rows,exception); heif_decoding_options_free(decode_options); if (status == MagickFalse) { heif_image_release(heif_image); heif_image_handle_release(image_handle); return(MagickFalse); } } p_y=heif_image_get_plane_readonly(heif_image,heif_channel_Y,&stride_y); p_cb=heif_image_get_plane_readonly(heif_image,heif_channel_Cb,&stride_cb); p_cr=heif_image_get_plane_readonly(heif_image,heif_channel_Cr,&stride_cr); for (y=0; y < (ssize_t) image->rows; y++) { Quantum *q; register ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum((unsigned char) p_y[y* stride_y+x]),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) p_cb[(y/2)* stride_cb+x/2]),q); SetPixelBlue(image,ScaleCharToQuantum((unsigned char) p_cr[(y/2)* stride_cr+x/2]),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } heif_image_release(heif_image); heif_image_handle_release(image_handle); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Always correct the width and height of the image (#1859).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ses_handle(struct waited *wp, enum wait_event ev, vtim_real now) { struct sess *sp; struct pool *pp; struct pool_task *tp; const struct transport *xp; CHECK_OBJ_NOTNULL(wp, WAITED_MAGIC); CAST_OBJ_NOTNULL(sp, wp->priv1, SESS_MAGIC); CAST_OBJ_NOTNULL(xp, (const void*)wp->priv2, TRANSPORT_MAGIC); AN(wp->priv2); assert((void *)sp->ws->f == wp); wp->magic = 0; wp = NULL; WS_Release(sp->ws, 0); switch (ev) { case WAITER_TIMEOUT: SES_Delete(sp, SC_RX_TIMEOUT, now); break; case WAITER_REMCLOSE: SES_Delete(sp, SC_REM_CLOSE, now); break; case WAITER_ACTION: pp = sp->pool; CHECK_OBJ_NOTNULL(pp, POOL_MAGIC); assert(sizeof *tp <= WS_ReserveSize(sp->ws, sizeof *tp)); tp = (void*)sp->ws->f; tp->func = xp->unwait; tp->priv = sp; if (Pool_Task(pp, tp, TASK_QUEUE_REQ)) SES_Delete(sp, SC_OVERLOAD, now); break; case WAITER_CLOSE: WRONG("Should not see WAITER_CLOSE on client side"); break; default: WRONG("Wrong event in ses_handle"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-617'], 'message': 'Take sizeof pool_task into account when reserving WS in SES_Wait The assert on WS_ReserveSize() in ses_handle() can not trip because sizeof (struct pool_task) is less than sizeof (struct waited). But to safe guard against future problems if that were to change, this patch makes sure that the session workspace can hold the largest of them before entering the waiter, erroring out if not.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE1(brk, unsigned long, brk) { unsigned long retval; unsigned long newbrk, oldbrk, origbrk; struct mm_struct *mm = current->mm; struct vm_area_struct *next; unsigned long min_brk; bool populate; bool downgraded = false; LIST_HEAD(uf); brk = untagged_addr(brk); if (down_write_killable(&mm->mmap_sem)) return -EINTR; origbrk = mm->brk; #ifdef CONFIG_COMPAT_BRK /* * CONFIG_COMPAT_BRK can still be overridden by setting * randomize_va_space to 2, which will still cause mm->start_brk * to be arbitrarily shifted */ if (current->brk_randomized) min_brk = mm->start_brk; else min_brk = mm->end_data; #else min_brk = mm->start_brk; #endif if (brk < min_brk) goto out; /* * Check against rlimit here. If this check is done later after the test * of oldbrk with newbrk then it can escape the test and let the data * segment grow beyond its set limit the in case where the limit is * not page aligned -Ram Gupta */ if (check_data_rlimit(rlimit(RLIMIT_DATA), brk, mm->start_brk, mm->end_data, mm->start_data)) goto out; newbrk = PAGE_ALIGN(brk); oldbrk = PAGE_ALIGN(mm->brk); if (oldbrk == newbrk) { mm->brk = brk; goto success; } /* * Always allow shrinking brk. * __do_munmap() may downgrade mmap_sem to read. */ if (brk <= mm->brk) { int ret; /* * mm->brk must to be protected by write mmap_sem so update it * before downgrading mmap_sem. When __do_munmap() fails, * mm->brk will be restored from origbrk. */ mm->brk = brk; ret = __do_munmap(mm, newbrk, oldbrk-newbrk, &uf, true); if (ret < 0) { mm->brk = origbrk; goto out; } else if (ret == 1) { downgraded = true; } goto success; } /* Check against existing mmap mappings. */ next = find_vma(mm, oldbrk); if (next && newbrk + PAGE_SIZE > vm_start_gap(next)) goto out; /* Ok, looks good - let it rip. */ if (do_brk_flags(oldbrk, newbrk-oldbrk, 0, &uf) < 0) goto out; mm->brk = brk; success: populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0; if (downgraded) up_read(&mm->mmap_sem); else up_write(&mm->mmap_sem); userfaultfd_unmap_complete(mm, &uf); if (populate) mm_populate(oldbrk, newbrk - oldbrk); return brk; out: retval = origbrk; up_write(&mm->mmap_sem); return retval; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'mm: Avoid creating virtual address aliases in brk()/mmap()/mremap() Currently the arm64 kernel ignores the top address byte passed to brk(), mmap() and mremap(). When the user is not aware of the 56-bit address limit or relies on the kernel to return an error, untagging such pointers has the potential to create address aliases in user-space. Passing a tagged address to munmap(), madvise() is permitted since the tagged pointer is expected to be inside an existing mapping. The current behaviour breaks the existing glibc malloc() implementation which relies on brk() with an address beyond 56-bit to be rejected by the kernel. Remove untagging in the above functions by partially reverting commit ce18d171cb73 ("mm: untag user pointers in mmap/munmap/mremap/brk"). In addition, update the arm64 tagged-address-abi.rst document accordingly. Link: https://bugzilla.redhat.com/1797052 Fixes: ce18d171cb73 ("mm: untag user pointers in mmap/munmap/mremap/brk") Cc: <stable@vger.kernel.org> # 5.4.x- Cc: Florian Weimer <fweimer@redhat.com> Reviewed-by: Andrew Morton <akpm@linux-foundation.org> Reported-by: Victor Stinner <vstinner@redhat.com> Acked-by: Will Deacon <will@kernel.org> Acked-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Catalin Marinas <catalin.marinas@arm.com> Signed-off-by: Will Deacon <will@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len, unsigned long, new_len, unsigned long, flags, unsigned long, new_addr) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; unsigned long ret = -EINVAL; unsigned long charged = 0; bool locked = false; bool downgraded = false; struct vm_userfaultfd_ctx uf = NULL_VM_UFFD_CTX; LIST_HEAD(uf_unmap_early); LIST_HEAD(uf_unmap); addr = untagged_addr(addr); new_addr = untagged_addr(new_addr); if (flags & ~(MREMAP_FIXED | MREMAP_MAYMOVE)) return ret; if (flags & MREMAP_FIXED && !(flags & MREMAP_MAYMOVE)) return ret; if (offset_in_page(addr)) return ret; old_len = PAGE_ALIGN(old_len); new_len = PAGE_ALIGN(new_len); /* * We allow a zero old-len as a special case * for DOS-emu "duplicate shm area" thing. But * a zero new-len is nonsensical. */ if (!new_len) return ret; if (down_write_killable(&current->mm->mmap_sem)) return -EINTR; if (flags & MREMAP_FIXED) { ret = mremap_to(addr, old_len, new_addr, new_len, &locked, &uf, &uf_unmap_early, &uf_unmap); goto out; } /* * Always allow a shrinking remap: that just unmaps * the unnecessary pages.. * __do_munmap does all the needed commit accounting, and * downgrades mmap_sem to read if so directed. */ if (old_len >= new_len) { int retval; retval = __do_munmap(mm, addr+new_len, old_len - new_len, &uf_unmap, true); if (retval < 0 && old_len != new_len) { ret = retval; goto out; /* Returning 1 indicates mmap_sem is downgraded to read. */ } else if (retval == 1) downgraded = true; ret = addr; goto out; } /* * Ok, we need to grow.. */ vma = vma_to_resize(addr, old_len, new_len, &charged); if (IS_ERR(vma)) { ret = PTR_ERR(vma); goto out; } /* old_len exactly to the end of the area.. */ if (old_len == vma->vm_end - addr) { /* can we just expand the current mapping? */ if (vma_expandable(vma, new_len - old_len)) { int pages = (new_len - old_len) >> PAGE_SHIFT; if (vma_adjust(vma, vma->vm_start, addr + new_len, vma->vm_pgoff, NULL)) { ret = -ENOMEM; goto out; } vm_stat_account(mm, vma->vm_flags, pages); if (vma->vm_flags & VM_LOCKED) { mm->locked_vm += pages; locked = true; new_addr = addr; } ret = addr; goto out; } } /* * We weren't able to just expand or shrink the area, * we need to create a new one and move it.. */ ret = -ENOMEM; if (flags & MREMAP_MAYMOVE) { unsigned long map_flags = 0; if (vma->vm_flags & VM_MAYSHARE) map_flags |= MAP_SHARED; new_addr = get_unmapped_area(vma->vm_file, 0, new_len, vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT), map_flags); if (IS_ERR_VALUE(new_addr)) { ret = new_addr; goto out; } ret = move_vma(vma, addr, old_len, new_len, new_addr, &locked, &uf, &uf_unmap); } out: if (offset_in_page(ret)) { vm_unacct_memory(charged); locked = 0; } if (downgraded) up_read(&current->mm->mmap_sem); else up_write(&current->mm->mmap_sem); if (locked && new_len > old_len) mm_populate(new_addr + old_len, new_len - old_len); userfaultfd_unmap_complete(mm, &uf_unmap_early); mremap_userfaultfd_complete(&uf, addr, new_addr, old_len); userfaultfd_unmap_complete(mm, &uf_unmap); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'mm: Avoid creating virtual address aliases in brk()/mmap()/mremap() Currently the arm64 kernel ignores the top address byte passed to brk(), mmap() and mremap(). When the user is not aware of the 56-bit address limit or relies on the kernel to return an error, untagging such pointers has the potential to create address aliases in user-space. Passing a tagged address to munmap(), madvise() is permitted since the tagged pointer is expected to be inside an existing mapping. The current behaviour breaks the existing glibc malloc() implementation which relies on brk() with an address beyond 56-bit to be rejected by the kernel. Remove untagging in the above functions by partially reverting commit ce18d171cb73 ("mm: untag user pointers in mmap/munmap/mremap/brk"). In addition, update the arm64 tagged-address-abi.rst document accordingly. Link: https://bugzilla.redhat.com/1797052 Fixes: ce18d171cb73 ("mm: untag user pointers in mmap/munmap/mremap/brk") Cc: <stable@vger.kernel.org> # 5.4.x- Cc: Florian Weimer <fweimer@redhat.com> Reviewed-by: Andrew Morton <akpm@linux-foundation.org> Reported-by: Victor Stinner <vstinner@redhat.com> Acked-by: Will Deacon <will@kernel.org> Acked-by: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Catalin Marinas <catalin.marinas@arm.com> Signed-off-by: Will Deacon <will@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int mod_session_init (void *instance, eap_handler_t *handler) { pwd_session_t *session; eap_pwd_t *inst = (eap_pwd_t *)instance; VALUE_PAIR *vp; pwd_id_packet_t *packet; if (!inst || !handler) { ERROR("rlm_eap_pwd: Initiate, NULL data provided"); return 0; } /* * make sure the server's been configured properly */ if (!inst->server_id) { ERROR("rlm_eap_pwd: Server ID is not configured"); return 0; } switch (inst->group) { case 19: case 20: case 21: case 25: case 26: break; default: ERROR("rlm_eap_pwd: Group is not supported"); return 0; } if ((session = talloc_zero(handler, pwd_session_t)) == NULL) return 0; talloc_set_destructor(session, _free_pwd_session); /* * set things up so they can be free'd reliably */ session->group_num = inst->group; session->private_value = NULL; session->peer_scalar = NULL; session->my_scalar = NULL; session->k = NULL; session->my_element = NULL; session->peer_element = NULL; session->group = NULL; session->pwe = NULL; session->order = NULL; session->prime = NULL; /* * The admin can dynamically change the MTU. */ session->mtu = inst->fragment_size; vp = fr_pair_find_by_num(handler->request->packet->vps, PW_FRAMED_MTU, 0, TAG_ANY); /* * session->mtu is *our* MTU. We need to subtract off the EAP * overhead. * * 9 = 4 (EAPOL header) + 4 (EAP header) + 1 (EAP type) * * The fragmentation code deals with the included length * so we don't need to subtract that here. */ if (vp && (vp->vp_integer > 100) && (vp->vp_integer < session->mtu)) { session->mtu = vp->vp_integer - 9; } session->state = PWD_STATE_ID_REQ; session->in = NULL; session->out_pos = 0; handler->opaque = session; /* * construct an EAP-pwd-ID/Request */ session->out_len = sizeof(pwd_id_packet_t) + strlen(inst->server_id); if ((session->out = talloc_zero_array(session, uint8_t, session->out_len)) == NULL) { return 0; } packet = (pwd_id_packet_t *)session->out; packet->group_num = htons(session->group_num); packet->random_function = EAP_PWD_DEF_RAND_FUN; packet->prf = EAP_PWD_DEF_PRF; session->token = fr_rand(); memcpy(packet->token, (char *)&session->token, 4); packet->prep = EAP_PWD_PREP_NONE; memcpy(packet->identity, inst->server_id, session->out_len - sizeof(pwd_id_packet_t) ); handler->stage = PROCESS; return send_pwd_request(session, handler->eap_ds); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'EAP-pwd: fix DoS due to multithreaded BN_CTX access The EAP-pwd module created one global OpenSSL BN_CTX instance, and used this instance in all incoming requests. This means that different threads used the same BN_CTX instance, which can result in a crash. An adversary can trigger these crashes by concurrently initiating multiple EAP-pwd handshakes from different clients. Fix this bug by creating a separate BN_CTX instance for each request.'</s>
<s>[INST] Given the following code containing errors, provide 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_instantiate (CONF_SECTION *cs, void **instance) { eap_pwd_t *inst; *instance = inst = talloc_zero(cs, eap_pwd_t); if (!inst) return -1; if (cf_section_parse(cs, inst, pwd_module_config) < 0) { return -1; } if (inst->fragment_size < 100) { cf_log_err_cs(cs, "Fragment size is too small"); return -1; } if ((inst->bnctx = BN_CTX_new()) == NULL) { cf_log_err_cs(cs, "Failed to get BN context"); return -1; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'EAP-pwd: fix DoS due to multithreaded BN_CTX access The EAP-pwd module created one global OpenSSL BN_CTX instance, and used this instance in all incoming requests. This means that different threads used the same BN_CTX instance, which can result in a crash. An adversary can trigger these crashes by concurrently initiating multiple EAP-pwd handshakes from different clients. Fix this bug by creating a separate BN_CTX instance for each request.'</s>
<s>[INST] Given the following code containing errors, provide 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_process(void *arg, eap_handler_t *handler) { pwd_session_t *session; pwd_hdr *hdr; pwd_id_packet_t *packet; eap_packet_t *response; REQUEST *request, *fake; VALUE_PAIR *pw, *vp; EAP_DS *eap_ds; size_t in_len; int ret = 0; eap_pwd_t *inst = (eap_pwd_t *)arg; uint16_t offset; uint8_t exch, *in, *ptr, msk[MSK_EMSK_LEN], emsk[MSK_EMSK_LEN]; uint8_t peer_confirm[SHA256_DIGEST_LENGTH]; if (((eap_ds = handler->eap_ds) == NULL) || !inst) return 0; session = (pwd_session_t *)handler->opaque; request = handler->request; response = handler->eap_ds->response; hdr = (pwd_hdr *)response->type.data; /* * The header must be at least one byte. */ if (!hdr || (response->type.length < sizeof(pwd_hdr))) { RDEBUG("Packet with insufficient data"); return 0; } in = hdr->data; in_len = response->type.length - sizeof(pwd_hdr); /* * see if we're fragmenting, if so continue until we're done */ if (session->out_pos) { if (in_len) RDEBUG2("pwd got something more than an ACK for a fragment"); return send_pwd_request(session, eap_ds); } /* * the first fragment will have a total length, make a * buffer to hold all the fragments */ if (EAP_PWD_GET_LENGTH_BIT(hdr)) { if (session->in) { RDEBUG2("pwd already alloced buffer for fragments"); return 0; } if (in_len < 2) { RDEBUG("Invalid packet: length bit set, but no length field"); return 0; } session->in_len = ntohs(in[0] * 256 | in[1]); if ((session->in = talloc_zero_array(session, uint8_t, session->in_len)) == NULL) { RDEBUG2("pwd cannot allocate %zd buffer to hold fragments", session->in_len); return 0; } memset(session->in, 0, session->in_len); session->in_pos = 0; in += sizeof(uint16_t); in_len -= sizeof(uint16_t); } /* * all fragments, including the 1st will have the M(ore) bit set, * buffer those fragments! */ if (EAP_PWD_GET_MORE_BIT(hdr)) { if (!session->in) { RDEBUG2("Unexpected fragment."); return 0; } if ((session->in_pos + in_len) > session->in_len) { RDEBUG2("Fragment overflows packet."); return 0; } memcpy(session->in + session->in_pos, in, in_len); session->in_pos += in_len; /* * send back an ACK for this fragment */ exch = EAP_PWD_GET_EXCHANGE(hdr); eap_ds->request->code = PW_EAP_REQUEST; eap_ds->request->type.num = PW_EAP_PWD; eap_ds->request->type.length = sizeof(pwd_hdr); if ((eap_ds->request->type.data = talloc_array(eap_ds->request, uint8_t, sizeof(pwd_hdr))) == NULL) { return 0; } hdr = (pwd_hdr *)eap_ds->request->type.data; EAP_PWD_SET_EXCHANGE(hdr, exch); return 1; } if (session->in) { /* * the last fragment... */ if ((session->in_pos + in_len) > session->in_len) { RDEBUG2("pwd will not overflow a fragment buffer. Nope, not prudent"); return 0; } memcpy(session->in + session->in_pos, in, in_len); in = session->in; in_len = session->in_len; } switch (session->state) { case PWD_STATE_ID_REQ: { BIGNUM *x = NULL, *y = NULL; if (EAP_PWD_GET_EXCHANGE(hdr) != EAP_PWD_EXCH_ID) { RDEBUG2("pwd exchange is incorrect: not ID"); return 0; } packet = (pwd_id_packet_t *) in; if (in_len < sizeof(*packet)) { RDEBUG("Packet is too small (%zd < %zd).", in_len, sizeof(*packet)); return 0; } if ((packet->prf != EAP_PWD_DEF_PRF) || (packet->random_function != EAP_PWD_DEF_RAND_FUN) || (packet->prep != EAP_PWD_PREP_NONE) || (CRYPTO_memcmp(packet->token, &session->token, 4)) || (packet->group_num != ntohs(session->group_num))) { RDEBUG2("pwd id response is invalid"); return 0; } /* * we've agreed on the ciphersuite, record it... */ ptr = (uint8_t *)&session->ciphersuite; memcpy(ptr, (char *)&packet->group_num, sizeof(uint16_t)); ptr += sizeof(uint16_t); *ptr = EAP_PWD_DEF_RAND_FUN; ptr += sizeof(uint8_t); *ptr = EAP_PWD_DEF_PRF; session->peer_id_len = in_len - sizeof(pwd_id_packet_t); if (session->peer_id_len >= sizeof(session->peer_id)) { RDEBUG2("pwd id response is malformed"); return 0; } memcpy(session->peer_id, packet->identity, session->peer_id_len); session->peer_id[session->peer_id_len] = '\0'; /* * make fake request to get the password for the usable ID */ if ((fake = request_alloc_fake(handler->request)) == NULL) { RDEBUG("pwd unable to create fake request!"); return 0; } fake->username = fr_pair_afrom_num(fake->packet, PW_USER_NAME, 0); if (!fake->username) { RDEBUG("Failed creating pair for peer id"); talloc_free(fake); return 0; } fr_pair_value_bstrncpy(fake->username, session->peer_id, session->peer_id_len); fr_pair_add(&fake->packet->vps, fake->username); if ((vp = fr_pair_find_by_num(request->config, PW_VIRTUAL_SERVER, 0, TAG_ANY)) != NULL) { fake->server = vp->vp_strvalue; } else if (inst->virtual_server) { fake->server = inst->virtual_server; } /* else fake->server == request->server */ RDEBUG("Sending tunneled request"); rdebug_pair_list(L_DBG_LVL_1, request, fake->packet->vps, NULL); if (fake->server) { RDEBUG("server %s {", fake->server); } else { RDEBUG("server {"); } /* * Call authorization recursively, which will * get the password. */ RINDENT(); process_authorize(0, fake); REXDENT(); /* * Note that we don't do *anything* with the reply * attributes. */ if (fake->server) { RDEBUG("} # server %s", fake->server); } else { RDEBUG("}"); } RDEBUG("Got tunneled reply code %d", fake->reply->code); rdebug_pair_list(L_DBG_LVL_1, request, fake->reply->vps, NULL); if ((pw = fr_pair_find_by_num(fake->config, PW_CLEARTEXT_PASSWORD, 0, TAG_ANY)) == NULL) { DEBUG2("failed to find password for %s to do pwd authentication", session->peer_id); talloc_free(fake); return 0; } if (compute_password_element(session, session->group_num, pw->data.strvalue, strlen(pw->data.strvalue), inst->server_id, strlen(inst->server_id), session->peer_id, strlen(session->peer_id), &session->token)) { DEBUG2("failed to obtain password element"); talloc_free(fake); return 0; } TALLOC_FREE(fake); /* * compute our scalar and element */ if (compute_scalar_element(session, inst->bnctx)) { DEBUG2("failed to compute server's scalar and element"); return 0; } MEM(x = BN_new()); MEM(y = BN_new()); /* * element is a point, get both coordinates: x and y */ if (!EC_POINT_get_affine_coordinates_GFp(session->group, session->my_element, x, y, inst->bnctx)) { DEBUG2("server point assignment failed"); BN_clear_free(x); BN_clear_free(y); return 0; } /* * construct request */ session->out_len = BN_num_bytes(session->order) + (2 * BN_num_bytes(session->prime)); if ((session->out = talloc_array(session, uint8_t, session->out_len)) == NULL) { return 0; } memset(session->out, 0, session->out_len); ptr = session->out; offset = BN_num_bytes(session->prime) - BN_num_bytes(x); BN_bn2bin(x, ptr + offset); BN_clear_free(x); ptr += BN_num_bytes(session->prime); offset = BN_num_bytes(session->prime) - BN_num_bytes(y); BN_bn2bin(y, ptr + offset); BN_clear_free(y); ptr += BN_num_bytes(session->prime); offset = BN_num_bytes(session->order) - BN_num_bytes(session->my_scalar); BN_bn2bin(session->my_scalar, ptr + offset); session->state = PWD_STATE_COMMIT; ret = send_pwd_request(session, eap_ds); } break; case PWD_STATE_COMMIT: if (EAP_PWD_GET_EXCHANGE(hdr) != EAP_PWD_EXCH_COMMIT) { RDEBUG2("pwd exchange is incorrect: not commit!"); return 0; } /* * process the peer's commit and generate the shared key, k */ if (process_peer_commit(session, in, in_len, inst->bnctx)) { RDEBUG2("failed to process peer's commit"); return 0; } /* * compute our confirm blob */ if (compute_server_confirm(session, session->my_confirm, inst->bnctx)) { ERROR("rlm_eap_pwd: failed to compute confirm!"); return 0; } /* * construct a response...which is just our confirm blob */ session->out_len = SHA256_DIGEST_LENGTH; if ((session->out = talloc_array(session, uint8_t, session->out_len)) == NULL) { return 0; } memset(session->out, 0, session->out_len); memcpy(session->out, session->my_confirm, SHA256_DIGEST_LENGTH); session->state = PWD_STATE_CONFIRM; ret = send_pwd_request(session, eap_ds); break; case PWD_STATE_CONFIRM: if (in_len < SHA256_DIGEST_LENGTH) { RDEBUG("Peer confirm is too short (%zd < %d)", in_len, SHA256_DIGEST_LENGTH); return 0; } if (EAP_PWD_GET_EXCHANGE(hdr) != EAP_PWD_EXCH_CONFIRM) { RDEBUG2("pwd exchange is incorrect: not commit!"); return 0; } if (compute_peer_confirm(session, peer_confirm, inst->bnctx)) { RDEBUG2("pwd exchange cannot compute peer's confirm"); return 0; } if (CRYPTO_memcmp(peer_confirm, in, SHA256_DIGEST_LENGTH)) { RDEBUG2("pwd exchange fails: peer confirm is incorrect!"); return 0; } if (compute_keys(session, peer_confirm, msk, emsk)) { RDEBUG2("pwd exchange cannot generate (E)MSK!"); return 0; } eap_ds->request->code = PW_EAP_SUCCESS; /* * return the MSK (in halves) */ eap_add_reply(handler->request, "MS-MPPE-Recv-Key", msk, MPPE_KEY_LEN); eap_add_reply(handler->request, "MS-MPPE-Send-Key", msk + MPPE_KEY_LEN, MPPE_KEY_LEN); ret = 1; break; default: RDEBUG2("unknown PWD state"); return 0; } /* * we processed the buffered fragments, get rid of them */ if (session->in) { talloc_free(session->in); session->in = NULL; } return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'EAP-pwd: fix DoS due to multithreaded BN_CTX access The EAP-pwd module created one global OpenSSL BN_CTX instance, and used this instance in all incoming requests. This means that different threads used the same BN_CTX instance, which can result in a crash. An adversary can trigger these crashes by concurrently initiating multiple EAP-pwd handshakes from different clients. Fix this bug by creating a separate BN_CTX instance for each request.'</s>
<s>[INST] Given the following code containing errors, provide 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 hpack_dht_insert(struct hpack_dht *dht, struct ist name, struct ist value) { unsigned int used; unsigned int head; unsigned int prev; unsigned int wrap; unsigned int tail; uint32_t headroom, tailroom; if (!hpack_dht_make_room(dht, name.len + value.len)) return 0; /* Now there is enough room in the table, that's guaranteed by the * protocol, but not necessarily where we need it. */ used = dht->used; if (!used) { /* easy, the table was empty */ dht->front = dht->head = 0; dht->wrap = dht->used = 1; dht->total = 0; head = 0; dht->dte[head].addr = dht->size - (name.len + value.len); goto copy; } /* compute the new head, used and wrap position */ prev = head = dht->head; wrap = dht->wrap; tail = hpack_dht_get_tail(dht); used++; head++; if (head >= wrap) { /* head is leading the entries, we either need to push the * table further or to loop back to released entries. We could * force to loop back when at least half of the allocatable * entries are free but in practice it never happens. */ if ((sizeof(*dht) + (wrap + 1) * sizeof(dht->dte[0]) <= dht->dte[dht->front].addr)) wrap++; else if (head >= used) /* there's a hole at the beginning */ head = 0; else { /* no more room, head hits tail and the index cannot be * extended, we have to realign the whole table. */ if (!hpack_dht_defrag(dht)) return -1; wrap = dht->wrap + 1; head = dht->head + 1; prev = head - 1; tail = 0; } } else if (used >= wrap) { /* we've hit the tail, we need to reorganize the index so that * the head is at the end (but not necessarily move the data). */ if (!hpack_dht_defrag(dht)) return -1; wrap = dht->wrap + 1; head = dht->head + 1; prev = head - 1; tail = 0; } /* Now we have updated head, used and wrap, we know that there is some * available room at least from the protocol's perspective. This space * is split in two areas : * * 1: if the previous head was the front cell, the space between the * end of the index table and the front cell's address. * 2: if the previous head was the front cell, the space between the * end of the tail and the end of the table ; or if the previous * head was not the front cell, the space between the end of the * tail and the head's address. */ if (prev == dht->front) { /* the area was contiguous */ headroom = dht->dte[dht->front].addr - (sizeof(*dht) + wrap * sizeof(dht->dte[0])); tailroom = dht->size - dht->dte[tail].addr - dht->dte[tail].nlen - dht->dte[tail].vlen; } else { /* it's already wrapped so we can't store anything in the headroom */ headroom = 0; tailroom = dht->dte[prev].addr - dht->dte[tail].addr - dht->dte[tail].nlen - dht->dte[tail].vlen; } /* We can decide to stop filling the headroom as soon as there's enough * room left in the tail to suit the protocol, but tests show that in * practice it almost never happens in other situations so the extra * test is useless and we simply fill the headroom as long as it's * available. */ if (headroom >= name.len + value.len) { /* install upfront and update ->front */ dht->dte[head].addr = dht->dte[dht->front].addr - (name.len + value.len); dht->front = head; } else if (tailroom >= name.len + value.len) { dht->dte[head].addr = dht->dte[tail].addr + dht->dte[tail].nlen + dht->dte[tail].vlen + tailroom - (name.len + value.len); } else { /* need to defragment the table before inserting upfront */ dht = hpack_dht_defrag(dht); wrap = dht->wrap + 1; head = dht->head + 1; dht->dte[head].addr = dht->dte[dht->front].addr - (name.len + value.len); dht->front = head; } dht->wrap = wrap; dht->head = head; dht->used = used; copy: dht->total += name.len + value.len; dht->dte[head].nlen = name.len; dht->dte[head].vlen = value.len; memcpy((void *)dht + dht->dte[head].addr, name.ptr, name.len); memcpy((void *)dht + dht->dte[head].addr + name.len, value.ptr, value.len); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'BUG/CRITICAL: hpack: never index a header into the headroom after wrapping The HPACK header table is implemented as a wrapping list inside a contigous area. Headers names and values are stored from right to left while indexes are stored from left to right. When there's no more room to store a new one, we wrap to the right again, or possibly defragment it if needed. The condition do use the right part (called tailroom) or the left part (called headroom) depends on the location of the last inserted header. After wrapping happens, the code forces to stick to tailroom by pretending there's no more headroom, so that the size fit test always fails. The problem is that nothing prevents from storing a header with an empty name and empty value, resulting in a total size of zero bytes, which satisfies the condition to use the headroom. Doing this in a wrapped buffer results in changing the "front" header index and causing miscalculations on the available size and the addresses of the next headers. This may even allow to overwrite some parts of the index, opening the possibility to perform arbitrary writes into a 32-bit relative address space. This patch fixes the issue by making sure the headroom is considered only when the buffer does not wrap, instead of relying on the zero size. This must be backported to all versions supporting H2, which is as far as 1.8. Many thanks to Felix Wilhelm of Google Project Zero for responsibly reporting this problem with a reproducer and a detailed analysis. CVE-2020-11100 was assigned to this issue.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static ssize_t mon_text_read_u(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct mon_reader_text *rp = file->private_data; struct mon_event_text *ep; struct mon_text_ptr ptr; ep = mon_text_read_wait(rp, file); if (IS_ERR(ep)) return PTR_ERR(ep); mutex_lock(&rp->printf_lock); ptr.cnt = 0; ptr.pbuf = rp->printf_buf; ptr.limit = rp->printf_size; mon_text_read_head_u(rp, &ptr, ep); if (ep->type == 'E') { mon_text_read_statset(rp, &ptr, ep); } else if (ep->xfertype == USB_ENDPOINT_XFER_ISOC) { mon_text_read_isostat(rp, &ptr, ep); mon_text_read_isodesc(rp, &ptr, ep); } else if (ep->xfertype == USB_ENDPOINT_XFER_INT) { mon_text_read_intstat(rp, &ptr, ep); } else { mon_text_read_statset(rp, &ptr, ep); } ptr.cnt += snprintf(ptr.pbuf + ptr.cnt, ptr.limit - ptr.cnt, " %d", ep->length); mon_text_read_data(rp, &ptr, ep); if (copy_to_user(buf, rp->printf_buf, ptr.cnt)) ptr.cnt = -EFAULT; mutex_unlock(&rp->printf_lock); kmem_cache_free(rp->e_slab, ep); return ptr.cnt; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'usb: usbmon: Read text within supplied buffer size This change fixes buffer overflows and silent data corruption with the usbmon device driver text file read operations. Signed-off-by: Fredrik Noring <noring@nocrew.org> Signed-off-by: Pete Zaitcev <zaitcev@redhat.com> Cc: stable <stable@vger.kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MagickPathExtent]; FILE *file; Image *image, *next; int status, unique_file; ssize_t n; SVGInfo *svg_info; unsigned char message[MagickPathExtent]; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if ((fabs(image->resolution.x) < MagickEpsilon) || (fabs(image->resolution.y) < MagickEpsilon)) { GeometryInfo geometry_info; int flags; flags=ParseGeometry(SVGDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (LocaleCompare(image_info->magick,"MSVG") != 0) { Image *svg_image; svg_image=RenderSVGImage(image_info,image,exception); if (svg_image != (Image *) NULL) { image=DestroyImageList(image); return(svg_image); } { #if defined(MAGICKCORE_RSVG_DELEGATE) #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface_t *cairo_surface; cairo_t *cairo_image; MagickBooleanType apply_density; MemoryInfo *pixel_info; register unsigned char *p; RsvgDimensionData dimension_info; unsigned char *pixels; #else GdkPixbuf *pixel_buffer; register const guchar *p; #endif GError *error; PixelInfo fill_color; register ssize_t x; register Quantum *q; RsvgHandle *svg_handle; ssize_t y; svg_handle=rsvg_handle_new(); if (svg_handle == (RsvgHandle *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); rsvg_handle_set_base_uri(svg_handle,image_info->filename); if ((fabs(image->resolution.x) > MagickEpsilon) && (fabs(image->resolution.y) > MagickEpsilon)) rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x, image->resolution.y); while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0) { message[n]='\0'; error=(GError *) NULL; (void) rsvg_handle_write(svg_handle,message,n,&error); if (error != (GError *) NULL) g_error_free(error); } error=(GError *) NULL; rsvg_handle_close(svg_handle,&error); if (error != (GError *) NULL) g_error_free(error); #if defined(MAGICKCORE_CAIRO_DELEGATE) apply_density=MagickTrue; rsvg_handle_get_dimensions(svg_handle,&dimension_info); if ((image->resolution.x > 0.0) && (image->resolution.y > 0.0)) { RsvgDimensionData dpi_dimension_info; /* We should not apply the density when the internal 'factor' is 'i'. This can be checked by using the trick below. */ rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x*256, image->resolution.y*256); rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info); if ((dpi_dimension_info.width != dimension_info.width) || (dpi_dimension_info.height != dimension_info.height)) apply_density=MagickFalse; rsvg_handle_set_dpi_x_y(svg_handle,image->resolution.x, image->resolution.y); } if (image_info->size != (char *) NULL) { (void) GetGeometry(image_info->size,(ssize_t *) NULL, (ssize_t *) NULL,&image->columns,&image->rows); if ((image->columns != 0) || (image->rows != 0)) { image->resolution.x=DefaultSVGDensity*image->columns/ dimension_info.width; image->resolution.y=DefaultSVGDensity*image->rows/ dimension_info.height; if (fabs(image->resolution.x) < MagickEpsilon) image->resolution.x=image->resolution.y; else if (fabs(image->resolution.y) < MagickEpsilon) image->resolution.y=image->resolution.x; else image->resolution.x=image->resolution.y=MagickMin( image->resolution.x,image->resolution.y); apply_density=MagickTrue; } } if (apply_density != MagickFalse) { image->columns=image->resolution.x*dimension_info.width/ DefaultSVGDensity; image->rows=image->resolution.y*dimension_info.height/ DefaultSVGDensity; } else { image->columns=dimension_info.width; image->rows=dimension_info.height; } pixel_info=(MemoryInfo *) NULL; #else pixel_buffer=rsvg_handle_get_pixbuf(svg_handle); rsvg_handle_free(svg_handle); image->columns=gdk_pixbuf_get_width(pixel_buffer); image->rows=gdk_pixbuf_get_height(pixel_buffer); #endif image->alpha_trait=BlendPixelTrait; if (image_info->ping == MagickFalse) { #if defined(MAGICKCORE_CAIRO_DELEGATE) size_t stride; #endif status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { #if !defined(MAGICKCORE_CAIRO_DELEGATE) g_object_unref(G_OBJECT(pixel_buffer)); #endif g_object_unref(svg_handle); ThrowReaderException(MissingDelegateError, "NoDecodeDelegateForThisImageFormat"); } #if defined(MAGICKCORE_CAIRO_DELEGATE) stride=4*image->columns; #if defined(MAGICKCORE_PANGOCAIRO_DELEGATE) stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, (int) image->columns); #endif pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); #endif (void) SetImageBackgroundColor(image,exception); #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface=cairo_image_surface_create_for_data(pixels, CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int) stride); if ((cairo_surface == (cairo_surface_t *) NULL) || (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS)) { if (cairo_surface != (cairo_surface_t *) NULL) cairo_surface_destroy(cairo_surface); pixel_info=RelinquishVirtualMemory(pixel_info); g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } cairo_image=cairo_create(cairo_surface); cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR); cairo_paint(cairo_image); cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER); if (apply_density != MagickFalse) cairo_scale(cairo_image,image->resolution.x/DefaultSVGDensity, image->resolution.y/DefaultSVGDensity); rsvg_handle_render_cairo(svg_handle,cairo_image); cairo_destroy(cairo_image); cairo_surface_destroy(cairo_surface); g_object_unref(svg_handle); p=pixels; #else p=gdk_pixbuf_get_pixels(pixel_buffer); #endif GetPixelInfo(image,&fill_color); for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { #if defined(MAGICKCORE_CAIRO_DELEGATE) fill_color.blue=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.red=ScaleCharToQuantum(*p++); #else fill_color.red=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.blue=ScaleCharToQuantum(*p++); #endif fill_color.alpha=ScaleCharToQuantum(*p++); #if defined(MAGICKCORE_CAIRO_DELEGATE) { double gamma; gamma=QuantumScale*fill_color.alpha; gamma=PerceptibleReciprocal(gamma); fill_color.blue*=gamma; fill_color.green*=gamma; fill_color.red*=gamma; } #endif CompositePixelOver(image,&fill_color,fill_color.alpha,q,(double) GetPixelAlpha(image,q),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } #if defined(MAGICKCORE_CAIRO_DELEGATE) if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); #else g_object_unref(G_OBJECT(pixel_buffer)); #endif (void) CloseBlob(image); for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } return(GetFirstImageInList(image)); #endif } } /* Open draw file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"w"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) CopyMagickString(image->filename,filename,MagickPathExtent); ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Parse SVG file. */ svg_info=AcquireSVGInfo(); if (svg_info == (SVGInfo *) NULL) { (void) fclose(file); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } svg_info->file=file; svg_info->exception=exception; svg_info->image=image; svg_info->image_info=image_info; svg_info->bounds.width=image->columns; svg_info->bounds.height=image->rows; svg_info->svgDepth=0; if (image_info->size != (char *) NULL) (void) CloneString(&svg_info->size,image_info->size); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"begin SAX"); xmlInitParser(); (void) xmlSubstituteEntitiesDefault(1); (void) memset(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=SVGInternalSubset; sax_modules.isStandalone=SVGIsStandalone; sax_modules.hasInternalSubset=SVGHasInternalSubset; sax_modules.hasExternalSubset=SVGHasExternalSubset; sax_modules.resolveEntity=SVGResolveEntity; sax_modules.getEntity=SVGGetEntity; sax_modules.entityDecl=SVGEntityDeclaration; sax_modules.notationDecl=SVGNotationDeclaration; sax_modules.attributeDecl=SVGAttributeDeclaration; sax_modules.elementDecl=SVGElementDeclaration; sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration; sax_modules.setDocumentLocator=SVGSetDocumentLocator; sax_modules.startDocument=SVGStartDocument; sax_modules.endDocument=SVGEndDocument; sax_modules.startElement=SVGStartElement; sax_modules.endElement=SVGEndElement; sax_modules.reference=SVGReference; sax_modules.characters=SVGCharacters; sax_modules.ignorableWhitespace=SVGIgnorableWhitespace; sax_modules.processingInstruction=SVGProcessingInstructions; sax_modules.comment=SVGComment; sax_modules.warning=SVGWarning; sax_modules.error=SVGError; sax_modules.fatalError=SVGError; sax_modules.getParameterEntity=SVGGetParameterEntity; sax_modules.cdataBlock=SVGCDataBlock; sax_modules.externalSubset=SVGExternalSubset; sax_handler=(&sax_modules); n=ReadBlob(image,MagickPathExtent-1,message); message[n]='\0'; if (n > 0) { svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *) message,n,image->filename); (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE); while ((n=ReadBlob(image,MagickPathExtent-1,message)) != 0) { message[n]='\0'; status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0); if (status != 0) break; } } (void) xmlParseChunk(svg_info->parser,(char *) message,0,1); SVGEndDocument(svg_info); xmlFreeParserCtxt(svg_info->parser); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); (void) fclose(file); (void) CloseBlob(image); image->columns=svg_info->width; image->rows=svg_info->height; if (exception->severity >= ErrorException) { svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); image=DestroyImage(image); return((Image *) NULL); } if (image_info->ping == MagickFalse) { ImageInfo *read_info; /* Draw image. */ image=DestroyImage(image); image=(Image *) NULL; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MagickPathExtent,"mvg:%s", filename); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) (void) CopyMagickString(image->filename,image_info->filename, MagickPathExtent); } /* Relinquish resources. */ if (image != (Image *) NULL) { if (svg_info->title != (char *) NULL) (void) SetImageProperty(image,"svg:title",svg_info->title,exception); if (svg_info->comment != (char *) NULL) (void) SetImageProperty(image,"svg:comment",svg_info->comment, exception); } for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-674', 'CWE-787'], 'message': '[FG-VD-19-136] ImageMagick Convert SVG MacOS Denial Of Service'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadSVGImage(const ImageInfo *image_info,ExceptionInfo *exception) { char filename[MaxTextExtent]; FILE *file; Image *image, *next; int status, unique_file; ssize_t n; SVGInfo *svg_info; unsigned char message[MaxTextExtent]; xmlSAXHandler sax_modules; xmlSAXHandlerPtr sax_handler; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if ((fabs(image->x_resolution) < MagickEpsilon) || (fabs(image->y_resolution) < MagickEpsilon)) { GeometryInfo geometry_info; int flags; flags=ParseGeometry(SVGDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (LocaleCompare(image_info->magick,"MSVG") != 0) { Image *svg_image; svg_image=RenderSVGImage(image_info,image,exception); if (svg_image != (Image *) NULL) { image=DestroyImageList(image); return(svg_image); } { #if defined(MAGICKCORE_RSVG_DELEGATE) #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface_t *cairo_surface; cairo_t *cairo_image; MagickBooleanType apply_density; MemoryInfo *pixel_info; register unsigned char *p; RsvgDimensionData dimension_info; unsigned char *pixels; #else GdkPixbuf *pixel_buffer; register const guchar *p; #endif GError *error; PixelPacket fill_color; register ssize_t x; register PixelPacket *q; RsvgHandle *svg_handle; ssize_t y; svg_handle=rsvg_handle_new(); if (svg_handle == (RsvgHandle *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); rsvg_handle_set_base_uri(svg_handle,image_info->filename); if ((fabs(image->x_resolution) > MagickEpsilon) && (fabs(image->y_resolution) > MagickEpsilon)) rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution, image->y_resolution); while ((n=ReadBlob(image,MaxTextExtent-1,message)) != 0) { message[n]='\0'; error=(GError *) NULL; (void) rsvg_handle_write(svg_handle,message,n,&error); if (error != (GError *) NULL) g_error_free(error); } error=(GError *) NULL; rsvg_handle_close(svg_handle,&error); if (error != (GError *) NULL) g_error_free(error); #if defined(MAGICKCORE_CAIRO_DELEGATE) apply_density=MagickTrue; rsvg_handle_get_dimensions(svg_handle,&dimension_info); if ((image->x_resolution > 0.0) && (image->y_resolution > 0.0)) { RsvgDimensionData dpi_dimension_info; /* We should not apply the density when the internal 'factor' is 'i'. This can be checked by using the trick below. */ rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution*256, image->y_resolution*256); rsvg_handle_get_dimensions(svg_handle,&dpi_dimension_info); if ((dpi_dimension_info.width != dimension_info.width) || (dpi_dimension_info.height != dimension_info.height)) apply_density=MagickFalse; rsvg_handle_set_dpi_x_y(svg_handle,image->x_resolution, image->y_resolution); } if (image_info->size != (char *) NULL) { (void) GetGeometry(image_info->size,(ssize_t *) NULL, (ssize_t *) NULL,&image->columns,&image->rows); if ((image->columns != 0) || (image->rows != 0)) { image->x_resolution=DefaultSVGDensity*image->columns/ dimension_info.width; image->y_resolution=DefaultSVGDensity*image->rows/ dimension_info.height; if (fabs(image->x_resolution) < MagickEpsilon) image->x_resolution=image->y_resolution; else if (fabs(image->y_resolution) < MagickEpsilon) image->y_resolution=image->x_resolution; else image->x_resolution=image->y_resolution=MagickMin( image->x_resolution,image->y_resolution); apply_density=MagickTrue; } } if (apply_density != MagickFalse) { image->columns=image->x_resolution*dimension_info.width/ DefaultSVGDensity; image->rows=image->y_resolution*dimension_info.height/ DefaultSVGDensity; } else { image->columns=dimension_info.width; image->rows=dimension_info.height; } pixel_info=(MemoryInfo *) NULL; #else pixel_buffer=rsvg_handle_get_pixbuf(svg_handle); rsvg_handle_free(svg_handle); image->columns=gdk_pixbuf_get_width(pixel_buffer); image->rows=gdk_pixbuf_get_height(pixel_buffer); #endif image->matte=MagickTrue; if (image_info->ping == MagickFalse) { #if defined(MAGICKCORE_CAIRO_DELEGATE) size_t stride; #endif status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { #if !defined(MAGICKCORE_CAIRO_DELEGATE) g_object_unref(G_OBJECT(pixel_buffer)); #endif g_object_unref(svg_handle); InheritException(exception,&image->exception); ThrowReaderException(MissingDelegateError, "NoDecodeDelegateForThisImageFormat"); } #if defined(MAGICKCORE_CAIRO_DELEGATE) stride=4*image->columns; #if defined(MAGICKCORE_PANGOCAIRO_DELEGATE) stride=(size_t) cairo_format_stride_for_width(CAIRO_FORMAT_ARGB32, (int) image->columns); #endif pixel_info=AcquireVirtualMemory(stride,image->rows*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); #endif (void) SetImageBackgroundColor(image); #if defined(MAGICKCORE_CAIRO_DELEGATE) cairo_surface=cairo_image_surface_create_for_data(pixels, CAIRO_FORMAT_ARGB32,(int) image->columns,(int) image->rows,(int) stride); if ((cairo_surface == (cairo_surface_t *) NULL) || (cairo_surface_status(cairo_surface) != CAIRO_STATUS_SUCCESS)) { if (cairo_surface != (cairo_surface_t *) NULL) cairo_surface_destroy(cairo_surface); pixel_info=RelinquishVirtualMemory(pixel_info); g_object_unref(svg_handle); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } cairo_image=cairo_create(cairo_surface); cairo_set_operator(cairo_image,CAIRO_OPERATOR_CLEAR); cairo_paint(cairo_image); cairo_set_operator(cairo_image,CAIRO_OPERATOR_OVER); if (apply_density != MagickFalse) cairo_scale(cairo_image,image->x_resolution/DefaultSVGDensity, image->y_resolution/DefaultSVGDensity); rsvg_handle_render_cairo(svg_handle,cairo_image); cairo_destroy(cairo_image); cairo_surface_destroy(cairo_surface); g_object_unref(svg_handle); p=pixels; #else p=gdk_pixbuf_get_pixels(pixel_buffer); #endif for (y=0; y < (ssize_t) image->rows; y++) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { #if defined(MAGICKCORE_CAIRO_DELEGATE) fill_color.blue=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.red=ScaleCharToQuantum(*p++); #else fill_color.red=ScaleCharToQuantum(*p++); fill_color.green=ScaleCharToQuantum(*p++); fill_color.blue=ScaleCharToQuantum(*p++); #endif fill_color.opacity=QuantumRange-ScaleCharToQuantum(*p++); #if defined(MAGICKCORE_CAIRO_DELEGATE) { double gamma; gamma=1.0-QuantumScale*fill_color.opacity; gamma=PerceptibleReciprocal(gamma); fill_color.blue*=gamma; fill_color.green*=gamma; fill_color.red*=gamma; } #endif MagickCompositeOver(&fill_color,fill_color.opacity,q, (MagickRealType) q->opacity,q); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } } #if defined(MAGICKCORE_CAIRO_DELEGATE) if (pixel_info != (MemoryInfo *) NULL) pixel_info=RelinquishVirtualMemory(pixel_info); #else g_object_unref(G_OBJECT(pixel_buffer)); #endif (void) CloseBlob(image); for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } return(GetFirstImageInList(image)); #endif } } /* Open draw file. */ file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"w"); if ((unique_file == -1) || (file == (FILE *) NULL)) { (void) CopyMagickString(image->filename,filename,MaxTextExtent); ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Parse SVG file. */ svg_info=AcquireSVGInfo(); if (svg_info == (SVGInfo *) NULL) { (void) fclose(file); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } svg_info->file=file; svg_info->exception=exception; svg_info->image=image; svg_info->image_info=image_info; svg_info->bounds.width=image->columns; svg_info->bounds.height=image->rows; svg_info->svgDepth=0; if (image_info->size != (char *) NULL) (void) CloneString(&svg_info->size,image_info->size); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"begin SAX"); xmlInitParser(); (void) xmlSubstituteEntitiesDefault(1); (void) memset(&sax_modules,0,sizeof(sax_modules)); sax_modules.internalSubset=SVGInternalSubset; sax_modules.isStandalone=SVGIsStandalone; sax_modules.hasInternalSubset=SVGHasInternalSubset; sax_modules.hasExternalSubset=SVGHasExternalSubset; sax_modules.resolveEntity=SVGResolveEntity; sax_modules.getEntity=SVGGetEntity; sax_modules.entityDecl=SVGEntityDeclaration; sax_modules.notationDecl=SVGNotationDeclaration; sax_modules.attributeDecl=SVGAttributeDeclaration; sax_modules.elementDecl=SVGElementDeclaration; sax_modules.unparsedEntityDecl=SVGUnparsedEntityDeclaration; sax_modules.setDocumentLocator=SVGSetDocumentLocator; sax_modules.startDocument=SVGStartDocument; sax_modules.endDocument=SVGEndDocument; sax_modules.startElement=SVGStartElement; sax_modules.endElement=SVGEndElement; sax_modules.reference=SVGReference; sax_modules.characters=SVGCharacters; sax_modules.ignorableWhitespace=SVGIgnorableWhitespace; sax_modules.processingInstruction=SVGProcessingInstructions; sax_modules.comment=SVGComment; sax_modules.warning=SVGWarning; sax_modules.error=SVGError; sax_modules.fatalError=SVGError; sax_modules.getParameterEntity=SVGGetParameterEntity; sax_modules.cdataBlock=SVGCDataBlock; sax_modules.externalSubset=SVGExternalSubset; sax_handler=(&sax_modules); n=ReadBlob(image,MaxTextExtent-1,message); message[n]='\0'; if (n > 0) { svg_info->parser=xmlCreatePushParserCtxt(sax_handler,svg_info,(char *) message,n,image->filename); (void) xmlCtxtUseOptions(svg_info->parser,XML_PARSE_HUGE); while ((n=ReadBlob(image,MaxTextExtent-1,message)) != 0) { message[n]='\0'; status=xmlParseChunk(svg_info->parser,(char *) message,(int) n,0); if (status != 0) break; } } (void) xmlParseChunk(svg_info->parser,(char *) message,0,1); SVGEndDocument(svg_info); xmlFreeParserCtxt(svg_info->parser); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"end SAX"); (void) fclose(file); (void) CloseBlob(image); image->columns=svg_info->width; image->rows=svg_info->height; if (exception->severity >= ErrorException) { svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); image=DestroyImage(image); return((Image *) NULL); } if (image_info->ping == MagickFalse) { ImageInfo *read_info; /* Draw image. */ image=DestroyImage(image); image=(Image *) NULL; read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); (void) FormatLocaleString(read_info->filename,MaxTextExtent,"mvg:%s", filename); image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (image != (Image *) NULL) (void) CopyMagickString(image->filename,image_info->filename, MaxTextExtent); } /* Relinquish resources. */ if (image != (Image *) NULL) { if (svg_info->title != (char *) NULL) (void) SetImageProperty(image,"svg:title",svg_info->title); if (svg_info->comment != (char *) NULL) (void) SetImageProperty(image,"svg:comment",svg_info->comment); } svg_info=DestroySVGInfo(svg_info); (void) RelinquishUniqueFileResource(filename); for (next=GetFirstImageInList(image); next != (Image *) NULL; ) { (void) CopyMagickString(next->filename,image->filename,MaxTextExtent); (void) CopyMagickString(next->magick,image->magick,MaxTextExtent); next=GetNextImageInList(next); } return(GetFirstImageInList(image)); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': '[FG-VD-19-136] ImageMagick Convert SVG MacOS Denial Of Service'</s>
<s>[INST] Given the following code containing errors, provide 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 exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF alignment marker"); return; } /* Check the next two values for correctness. */ if (length < 8) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if (exif_value_2a != 0x2a || offset_of_ifd < 0x08) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid TIFF start (1)"); return; } if (offset_of_ifd > length) { exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, "Invalid IFD start"); return; } ImageInfo->sections_found |= FOUND_IFD0; /* First directory starts at offset 8. Offsets starts at 0. */ exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, length/*-14*/, displacement, SECTION_IFD0, 0); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process TIFF in JPEG done"); #endif /* Compute the CCD width, in millimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed bug #79282'</s>
<s>[INST] Given the following code containing errors, provide 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 tulip_tx(TULIPState *s, struct tulip_descriptor *desc) { if (s->tx_frame_len) { if ((s->csr[6] >> CSR6_OM_SHIFT) & CSR6_OM_MASK) { /* Internal or external Loopback */ tulip_receive(s, s->tx_frame, s->tx_frame_len); } else { qemu_send_packet(qemu_get_queue(s->nic), s->tx_frame, s->tx_frame_len); } } if (desc->control & TDES1_IC) { s->csr[5] |= CSR5_TI; tulip_update_int(s); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'net: tulip: check frame size and r/w data length Tulip network driver while copying tx/rx buffers does not check frame size against r/w data length. This may lead to OOB buffer access. Add check to avoid it. Limit iterations over descriptors to avoid potential infinite loop issue in tulip_xmit_list_update. Reported-by: Li Qiang <pangpei.lq@antfin.com> Reported-by: Ziming Zhang <ezrakiez@gmail.com> Reported-by: Jason Wang <jasowang@redhat.com> Tested-by: Li Qiang <liq3ea@gmail.com> Reviewed-by: Li Qiang <liq3ea@gmail.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Jason Wang <jasowang@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 void tulip_xmit_list_update(TULIPState *s) { struct tulip_descriptor desc; if (tulip_ts(s) != CSR5_TS_SUSPENDED) { return; } for (;;) { tulip_desc_read(s, s->current_tx_desc, &desc); tulip_dump_tx_descriptor(s, &desc); if (!(desc.status & TDES0_OWN)) { tulip_update_ts(s, CSR5_TS_SUSPENDED); s->csr[5] |= CSR5_TU; tulip_update_int(s); return; } if (desc.control & TDES1_SET) { tulip_setup_frame(s, &desc); } else { if (desc.control & TDES1_FS) { s->tx_frame_len = 0; } tulip_copy_tx_buffers(s, &desc); if (desc.control & TDES1_LS) { tulip_tx(s, &desc); } } tulip_desc_write(s, s->current_tx_desc, &desc); tulip_next_tx_descriptor(s, &desc); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'net: tulip: check frame size and r/w data length Tulip network driver while copying tx/rx buffers does not check frame size against r/w data length. This may lead to OOB buffer access. Add check to avoid it. Limit iterations over descriptors to avoid potential infinite loop issue in tulip_xmit_list_update. Reported-by: Li Qiang <pangpei.lq@antfin.com> Reported-by: Ziming Zhang <ezrakiez@gmail.com> Reported-by: Jason Wang <jasowang@redhat.com> Tested-by: Li Qiang <liq3ea@gmail.com> Reviewed-by: Li Qiang <liq3ea@gmail.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Jason Wang <jasowang@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 void tulip_copy_rx_bytes(TULIPState *s, struct tulip_descriptor *desc) { int len1 = (desc->control >> RDES1_BUF1_SIZE_SHIFT) & RDES1_BUF1_SIZE_MASK; int len2 = (desc->control >> RDES1_BUF2_SIZE_SHIFT) & RDES1_BUF2_SIZE_MASK; int len; if (s->rx_frame_len && len1) { if (s->rx_frame_len > len1) { len = len1; } else { len = s->rx_frame_len; } pci_dma_write(&s->dev, desc->buf_addr1, s->rx_frame + (s->rx_frame_size - s->rx_frame_len), len); s->rx_frame_len -= len; } if (s->rx_frame_len && len2) { if (s->rx_frame_len > len2) { len = len2; } else { len = s->rx_frame_len; } pci_dma_write(&s->dev, desc->buf_addr2, s->rx_frame + (s->rx_frame_size - s->rx_frame_len), len); s->rx_frame_len -= len; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'net: tulip: check frame size and r/w data length Tulip network driver while copying tx/rx buffers does not check frame size against r/w data length. This may lead to OOB buffer access. Add check to avoid it. Limit iterations over descriptors to avoid potential infinite loop issue in tulip_xmit_list_update. Reported-by: Li Qiang <pangpei.lq@antfin.com> Reported-by: Ziming Zhang <ezrakiez@gmail.com> Reported-by: Jason Wang <jasowang@redhat.com> Tested-by: Li Qiang <liq3ea@gmail.com> Reviewed-by: Li Qiang <liq3ea@gmail.com> Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Jason Wang <jasowang@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: bool do_notify_parent(struct task_struct *tsk, int sig) { struct kernel_siginfo info; unsigned long flags; struct sighand_struct *psig; bool autoreap = false; u64 utime, stime; BUG_ON(sig == -1); /* do_notify_parent_cldstop should have been called instead. */ BUG_ON(task_is_stopped_or_traced(tsk)); BUG_ON(!tsk->ptrace && (tsk->group_leader != tsk || !thread_group_empty(tsk))); /* Wake up all pidfd waiters */ do_notify_pidfd(tsk); if (sig != SIGCHLD) { /* * This is only possible if parent == real_parent. * Check if it has changed security domain. */ if (tsk->parent_exec_id != tsk->parent->self_exec_id) sig = SIGCHLD; } clear_siginfo(&info); info.si_signo = sig; info.si_errno = 0; /* * We are under tasklist_lock here so our parent is tied to * us and cannot change. * * task_active_pid_ns will always return the same pid namespace * until a task passes through release_task. * * write_lock() currently calls preempt_disable() which is the * same as rcu_read_lock(), but according to Oleg, this is not * correct to rely on this */ rcu_read_lock(); info.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent)); info.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns), task_uid(tsk)); rcu_read_unlock(); task_cputime(tsk, &utime, &stime); info.si_utime = nsec_to_clock_t(utime + tsk->signal->utime); info.si_stime = nsec_to_clock_t(stime + tsk->signal->stime); info.si_status = tsk->exit_code & 0x7f; if (tsk->exit_code & 0x80) info.si_code = CLD_DUMPED; else if (tsk->exit_code & 0x7f) info.si_code = CLD_KILLED; else { info.si_code = CLD_EXITED; info.si_status = tsk->exit_code >> 8; } psig = tsk->parent->sighand; spin_lock_irqsave(&psig->siglock, flags); if (!tsk->ptrace && sig == SIGCHLD && (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN || (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) { /* * We are exiting and our parent doesn't care. POSIX.1 * defines special semantics for setting SIGCHLD to SIG_IGN * or setting the SA_NOCLDWAIT flag: we should be reaped * automatically and not left for our parent's wait4 call. * Rather than having the parent do it as a magic kind of * signal handler, we just set this to tell do_exit that we * can be cleaned up without becoming a zombie. Note that * we still call __wake_up_parent in this case, because a * blocked sys_wait4 might now return -ECHILD. * * Whether we send SIGCHLD or not for SA_NOCLDWAIT * is implementation-defined: we do (if you don't want * it, just use SIG_IGN instead). */ autoreap = true; if (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN) sig = 0; } if (valid_signal(sig) && sig) __group_send_sig_info(sig, &info, tsk->parent); __wake_up_parent(tsk, tsk->parent); spin_unlock_irqrestore(&psig->siglock, flags); return autoreap; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'signal: Extend exec_id to 64bits Replace the 32bit exec_id with a 64bit exec_id to make it impossible to wrap the exec_id counter. With care an attacker can cause exec_id wrap and send arbitrary signals to a newly exec'd parent. This bypasses the signal sending checks if the parent changes their credentials during exec. The severity of this problem can been seen that in my limited testing of a 32bit exec_id it can take as little as 19s to exec 65536 times. Which means that it can take as little as 14 days to wrap a 32bit exec_id. Adam Zabrocki has succeeded wrapping the self_exe_id in 7 days. Even my slower timing is in the uptime of a typical server. Which means self_exec_id is simply a speed bump today, and if exec gets noticably faster self_exec_id won't even be a speed bump. Extending self_exec_id to 64bits introduces a problem on 32bit architectures where reading self_exec_id is no longer atomic and can take two read instructions. Which means that is is possible to hit a window where the read value of exec_id does not match the written value. So with very lucky timing after this change this still remains expoiltable. I have updated the update of exec_id on exec to use WRITE_ONCE and the read of exec_id in do_notify_parent to use READ_ONCE to make it clear that there is no locking between these two locations. Link: https://lore.kernel.org/kernel-hardening/20200324215049.GA3710@pi3.com.pl Fixes: 2.3.23pre2 Cc: stable@vger.kernel.org Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int input_default_setkeycode(struct input_dev *dev, const struct input_keymap_entry *ke, unsigned int *old_keycode) { unsigned int index; int error; int i; if (!dev->keycodesize) return -EINVAL; if (ke->flags & INPUT_KEYMAP_BY_INDEX) { index = ke->index; } else { error = input_scancode_to_scalar(ke, &index); if (error) return error; } if (index >= dev->keycodemax) return -EINVAL; if (dev->keycodesize < sizeof(ke->keycode) && (ke->keycode >> (dev->keycodesize * 8))) return -EINVAL; switch (dev->keycodesize) { case 1: { u8 *k = (u8 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } case 2: { u16 *k = (u16 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } default: { u32 *k = (u32 *)dev->keycode; *old_keycode = k[index]; k[index] = ke->keycode; break; } } __clear_bit(*old_keycode, dev->keybit); __set_bit(ke->keycode, dev->keybit); for (i = 0; i < dev->keycodemax; i++) { if (input_fetch_keycode(dev, i) == *old_keycode) { __set_bit(*old_keycode, dev->keybit); break; /* Setting the bit twice is useless, so break */ } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-787'], 'message': 'Input: add safety guards to input_set_keycode() If we happen to have a garbage in input device's keycode table with values too big we'll end up doing clear_bit() with offset way outside of our bitmaps, damaging other objects within an input device or even outside of it. Let's add sanity checks to the returned old keycodes. Reported-by: syzbot+c769968809f9359b07aa@syzkaller.appspotmail.com Reported-by: syzbot+76f3a30e88d256644c78@syzkaller.appspotmail.com Link: https://lore.kernel.org/r/20191207212757.GA245964@dtor-ws Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cit_get_packet_size(struct gspca_dev *gspca_dev) { struct usb_host_interface *alt; struct usb_interface *intf; intf = usb_ifnum_to_if(gspca_dev->dev, gspca_dev->iface); alt = usb_altnum_to_altsetting(intf, gspca_dev->alt); if (!alt) { pr_err("Couldn't get altsetting\n"); return -EIO; } return le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'media: xirlink_cit: add missing descriptor sanity checks Make sure to check that we have two alternate settings and at least one endpoint before accessing the second altsetting structure and dereferencing the endpoint arrays. This specifically avoids dereferencing NULL-pointers or corrupting memory when a device does not have the expected descriptors. Note that the sanity check in cit_get_packet_size() is not redundant as the driver is mixing looking up altsettings by index and by number, which may not coincide. Fixes: 659fefa0eb17 ("V4L/DVB: gspca_xirlink_cit: Add support for camera with a bcd version of 0.01") Fixes: 59f8b0bf3c12 ("V4L/DVB: gspca_xirlink_cit: support bandwidth changing for devices with 1 alt setting") Cc: stable <stable@vger.kernel.org> # 2.6.37 Cc: Hans de Goede <hdegoede@redhat.com> Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int mpol_parse_str(char *str, struct mempolicy **mpol) { struct mempolicy *new = NULL; unsigned short mode_flags; nodemask_t nodes; char *nodelist = strchr(str, ':'); char *flags = strchr(str, '='); int err = 1, mode; if (flags) *flags++ = '\0'; /* terminate mode string */ if (nodelist) { /* NUL-terminate mode or flags string */ *nodelist++ = '\0'; if (nodelist_parse(nodelist, nodes)) goto out; if (!nodes_subset(nodes, node_states[N_MEMORY])) goto out; } else nodes_clear(nodes); mode = match_string(policy_modes, MPOL_MAX, str); if (mode < 0) goto out; switch (mode) { case MPOL_PREFERRED: /* * Insist on a nodelist of one node only */ if (nodelist) { char *rest = nodelist; while (isdigit(*rest)) rest++; if (*rest) goto out; } break; case MPOL_INTERLEAVE: /* * Default to online nodes with memory if no nodelist */ if (!nodelist) nodes = node_states[N_MEMORY]; break; case MPOL_LOCAL: /* * Don't allow a nodelist; mpol_new() checks flags */ if (nodelist) goto out; mode = MPOL_PREFERRED; break; case MPOL_DEFAULT: /* * Insist on a empty nodelist */ if (!nodelist) err = 0; goto out; case MPOL_BIND: /* * Insist on a nodelist */ if (!nodelist) goto out; } mode_flags = 0; if (flags) { /* * Currently, we only support two mutually exclusive * mode flags. */ if (!strcmp(flags, "static")) mode_flags |= MPOL_F_STATIC_NODES; else if (!strcmp(flags, "relative")) mode_flags |= MPOL_F_RELATIVE_NODES; else goto out; } new = mpol_new(mode, mode_flags, &nodes); if (IS_ERR(new)) goto out; /* * Save nodes for mpol_to_str() to show the tmpfs mount options * for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo. */ if (mode != MPOL_PREFERRED) new->v.nodes = nodes; else if (nodelist) new->v.preferred_node = first_node(nodes); else new->flags |= MPOL_F_LOCAL; /* * Save nodes for contextualization: this will be used to "clone" * the mempolicy in a specific context [cpuset] at a later time. */ new->w.user_nodemask = nodes; err = 0; out: /* Restore string for error message */ if (nodelist) *--nodelist = ':'; if (flags) *--flags = '='; if (!err) *mpol = new; return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'mm: mempolicy: require at least one nodeid for MPOL_PREFERRED Using an empty (malformed) nodelist that is not caught during mount option parsing leads to a stack-out-of-bounds access. The option string that was used was: "mpol=prefer:,". However, MPOL_PREFERRED requires a single node number, which is not being provided here. Add a check that 'nodes' is not empty after parsing for MPOL_PREFERRED's nodeid. Fixes: 095f1fc4ebf3 ("mempolicy: rework shmem mpol parsing and display") Reported-by: Entropy Moe <3ntr0py1337@gmail.com> Reported-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com Signed-off-by: Randy Dunlap <rdunlap@infradead.org> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Tested-by: syzbot+b055b1a6b2b958707a21@syzkaller.appspotmail.com Cc: Lee Schermerhorn <lee.schermerhorn@hp.com> Link: http://lkml.kernel.org/r/89526377-7eb6-b662-e1d8-4430928abde9@infradead.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void slc_bump(struct slcan *sl) { struct sk_buff *skb; struct can_frame cf; int i, tmp; u32 tmpid; char *cmd = sl->rbuff; cf.can_id = 0; switch (*cmd) { case 'r': cf.can_id = CAN_RTR_FLAG; /* fallthrough */ case 't': /* store dlc ASCII value and terminate SFF CAN ID string */ cf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN]; sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN] = 0; /* point to payload data behind the dlc */ cmd += SLC_CMD_LEN + SLC_SFF_ID_LEN + 1; break; case 'R': cf.can_id = CAN_RTR_FLAG; /* fallthrough */ case 'T': cf.can_id |= CAN_EFF_FLAG; /* store dlc ASCII value and terminate EFF CAN ID string */ cf.can_dlc = sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN]; sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN] = 0; /* point to payload data behind the dlc */ cmd += SLC_CMD_LEN + SLC_EFF_ID_LEN + 1; break; default: return; } if (kstrtou32(sl->rbuff + SLC_CMD_LEN, 16, &tmpid)) return; cf.can_id |= tmpid; /* get can_dlc from sanitized ASCII value */ if (cf.can_dlc >= '0' && cf.can_dlc < '9') cf.can_dlc -= '0'; else return; *(u64 *) (&cf.data) = 0; /* clear payload */ /* RTR frames may have a dlc > 0 but they never have any data bytes */ if (!(cf.can_id & CAN_RTR_FLAG)) { for (i = 0; i < cf.can_dlc; i++) { tmp = hex_to_bin(*cmd++); if (tmp < 0) return; cf.data[i] = (tmp << 4); tmp = hex_to_bin(*cmd++); if (tmp < 0) return; cf.data[i] |= tmp; } } skb = dev_alloc_skb(sizeof(struct can_frame) + sizeof(struct can_skb_priv)); if (!skb) return; skb->dev = sl->dev; skb->protocol = htons(ETH_P_CAN); skb->pkt_type = PACKET_BROADCAST; skb->ip_summed = CHECKSUM_UNNECESSARY; can_skb_reserve(skb); can_skb_prv(skb)->ifindex = sl->dev->ifindex; can_skb_prv(skb)->skbcnt = 0; skb_put_data(skb, &cf, sizeof(struct can_frame)); sl->dev->stats.rx_packets++; sl->dev->stats.rx_bytes += cf.can_dlc; netif_rx_ni(skb); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-909', 'CWE-908'], 'message': 'slcan: Don't transmit uninitialized stack data in padding struct can_frame contains some padding which is not explicitly zeroed in slc_bump. This uninitialized data will then be transmitted if the stack initialization hardening feature is not enabled (CONFIG_INIT_STACK_ALL). This commit just zeroes the whole struct including the padding. Signed-off-by: Richard Palethorpe <rpalethorpe@suse.com> Fixes: a1044e36e457 ("can: add slcan driver for serial/USB-serial CAN adapters") Reviewed-by: Kees Cook <keescook@chromium.org> Cc: linux-can@vger.kernel.org Cc: netdev@vger.kernel.org Cc: security@kernel.org Cc: wg@grandegger.com Cc: mkl@pengutronix.de Cc: davem@davemloft.net Acked-by: Marc Kleine-Budde <mkl@pengutronix.de> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int RGWPostObj_ObjStore_S3::get_tags() { string tags_str; if (part_str(parts, "tagging", &tags_str)) { RGWObjTagsXMLParser parser; if (!parser.init()){ ldout(s->cct, 0) << "Couldn't init RGWObjTags XML parser" << dendl; err_msg = "Server couldn't process the request"; return -EINVAL; // TODO: This class of errors in rgw code should be a 5XX error } if (!parser.parse(tags_str.c_str(), tags_str.size(), 1)) { ldout(s->cct,0 ) << "Invalid Tagging XML" << dendl; err_msg = "Invalid Tagging XML"; return -EINVAL; } RGWObjTagSet_S3 *obj_tags_s3; RGWObjTagging_S3 *tagging; tagging = static_cast<RGWObjTagging_S3 *>(parser.find_first("Tagging")); obj_tags_s3 = static_cast<RGWObjTagSet_S3 *>(tagging->find_first("TagSet")); if(!obj_tags_s3){ return -ERR_MALFORMED_XML; } RGWObjTags obj_tags; int r = obj_tags_s3->rebuild(obj_tags); if (r < 0) return r; bufferlist tags_bl; obj_tags.encode(tags_bl); ldout(s->cct, 20) << "Read " << obj_tags.count() << "tags" << dendl; attrs[RGW_ATTR_TAGS] = tags_bl; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'rgw: check for tagging element in POST Obj requests Check for null element when reading the tagging field from POST obj XML Fixes: https://tracker.ceph.com/issues/44967 Signed-off-by: Abhishek Lekshmanan <abhishek@suse.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: vhost_user_check_and_alloc_queue_pair(struct virtio_net *dev, struct VhostUserMsg *msg) { uint16_t vring_idx; switch (msg->request.master) { case VHOST_USER_SET_VRING_KICK: case VHOST_USER_SET_VRING_CALL: case VHOST_USER_SET_VRING_ERR: vring_idx = msg->payload.u64 & VHOST_USER_VRING_IDX_MASK; break; case VHOST_USER_SET_VRING_NUM: case VHOST_USER_SET_VRING_BASE: case VHOST_USER_SET_VRING_ENABLE: vring_idx = msg->payload.state.index; break; case VHOST_USER_SET_VRING_ADDR: vring_idx = msg->payload.addr.index; break; default: return 0; } if (vring_idx >= VHOST_MAX_VRING) { VHOST_LOG_CONFIG(ERR, "invalid vring index: %u\n", vring_idx); return -1; } if (dev->virtqueue[vring_idx]) return 0; return alloc_vring_queue(dev, vring_idx); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'vhost: fix vring index check vhost_user_check_and_alloc_queue_pair() is used to extract a vring index from a payload. This function validates the index and is called early on in when performing message handling. Most message handlers depend on it correctly validating the vring index. Depending on the message type the vring index is in different parts of the payload. The function contains a switch/case for each type and copies the index. This is stored in a uint16. This index is then validated. Depending on the message, the source index is an unsigned int. If integer truncation occurs (uint->uint16) the top 16 bits of the index are never validated. When they are used later on (e.g. in vhost_user_set_vring_num() or vhost_user_set_vring_addr()) it can lead to out of bound indexing. The out of bound indexed data gets written to, and hence this can cause memory corruption. This patch fixes this vulnerability by declaring vring index as an unsigned int in vhost_user_check_and_alloc_queue_pair(). CVE-2020-10723 Fixes: 160cbc815b41 ("vhost: remove a hack on queue allocation") Cc: stable@dpdk.org Reported-by: Ilja Van Sprundel <ivansprundel@ioactive.com> Signed-off-by: Maxime Coquelin <maxime.coquelin@redhat.com> Reviewed-by: Xiaolong Ye <xiaolong.ye@intel.com> Reviewed-by: Ilja Van Sprundel <ivansprundel@ioactive.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: transform_chain_param(struct rte_crypto_sym_xform *xforms, VhostUserCryptoSessionParam *param) { struct rte_crypto_sym_xform *xform_cipher, *xform_auth; int ret; switch (param->chaining_dir) { case VIRTIO_CRYPTO_SYM_ALG_CHAIN_ORDER_HASH_THEN_CIPHER: xform_auth = xforms; xform_cipher = xforms->next; xform_cipher->cipher.op = RTE_CRYPTO_CIPHER_OP_DECRYPT; xform_auth->auth.op = RTE_CRYPTO_AUTH_OP_VERIFY; break; case VIRTIO_CRYPTO_SYM_ALG_CHAIN_ORDER_CIPHER_THEN_HASH: xform_cipher = xforms; xform_auth = xforms->next; xform_cipher->cipher.op = RTE_CRYPTO_CIPHER_OP_ENCRYPT; xform_auth->auth.op = RTE_CRYPTO_AUTH_OP_GENERATE; break; default: return -VIRTIO_CRYPTO_BADMSG; } /* cipher */ ret = cipher_algo_transform(param->cipher_algo, &xform_cipher->cipher.algo); if (unlikely(ret < 0)) return ret; xform_cipher->type = RTE_CRYPTO_SYM_XFORM_CIPHER; xform_cipher->cipher.key.length = param->cipher_key_len; xform_cipher->cipher.key.data = param->cipher_key_buf; ret = get_iv_len(xform_cipher->cipher.algo); if (unlikely(ret < 0)) return ret; xform_cipher->cipher.iv.length = (uint16_t)ret; xform_cipher->cipher.iv.offset = IV_OFFSET; /* auth */ xform_auth->type = RTE_CRYPTO_SYM_XFORM_AUTH; ret = auth_algo_transform(param->hash_algo, &xform_auth->auth.algo); if (unlikely(ret < 0)) return ret; xform_auth->auth.digest_length = param->digest_len; xform_auth->auth.key.length = param->auth_key_len; xform_auth->auth.key.data = param->auth_key_buf; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'vhost/crypto: validate keys lengths transform_cipher_param() and transform_chain_param() handle the payload data for the VHOST_USER_CRYPTO_CREATE_SESS message. These payloads have to be validated, since it could come from untrusted sources. Two buffers and their lengths are defined in this payload, one the the auth key and one for the cipher key. But above functions do not validate the key length inputs, which could lead to read out of bounds, as buffers have static sizes of 64 bytes for the cipher key and 512 bytes for the auth key. This patch adds necessary checks on the key length field before being used. CVE-2020-10724 Fixes: e80a98708166 ("vhost/crypto: add session message handler") Cc: stable@dpdk.org Reported-by: Ilja Van Sprundel <ivansprundel@ioactive.com> Signed-off-by: Maxime Coquelin <maxime.coquelin@redhat.com> Reviewed-by: Xiaolong Ye <xiaolong.ye@intel.com> Reviewed-by: Ilja Van Sprundel <ivansprundel@ioactive.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: virtio_dev_rx_batch_packed(struct virtio_net *dev, struct vhost_virtqueue *vq, struct rte_mbuf **pkts) { bool wrap_counter = vq->avail_wrap_counter; struct vring_packed_desc *descs = vq->desc_packed; uint16_t avail_idx = vq->last_avail_idx; uint64_t desc_addrs[PACKED_BATCH_SIZE]; struct virtio_net_hdr_mrg_rxbuf *hdrs[PACKED_BATCH_SIZE]; uint32_t buf_offset = dev->vhost_hlen; uint64_t lens[PACKED_BATCH_SIZE]; uint16_t ids[PACKED_BATCH_SIZE]; uint16_t i; if (unlikely(avail_idx & PACKED_BATCH_MASK)) return -1; if (unlikely((avail_idx + PACKED_BATCH_SIZE) > vq->size)) return -1; vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) { if (unlikely(pkts[i]->next != NULL)) return -1; if (unlikely(!desc_is_avail(&descs[avail_idx + i], wrap_counter))) return -1; } rte_smp_rmb(); vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) lens[i] = descs[avail_idx + i].len; vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) { if (unlikely(pkts[i]->pkt_len > (lens[i] - buf_offset))) return -1; } vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) desc_addrs[i] = vhost_iova_to_vva(dev, vq, descs[avail_idx + i].addr, &lens[i], VHOST_ACCESS_RW); vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) { if (unlikely(lens[i] != descs[avail_idx + i].len)) return -1; } vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) { rte_prefetch0((void *)(uintptr_t)desc_addrs[i]); hdrs[i] = (struct virtio_net_hdr_mrg_rxbuf *) (uintptr_t)desc_addrs[i]; lens[i] = pkts[i]->pkt_len + dev->vhost_hlen; } vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) virtio_enqueue_offload(pkts[i], &hdrs[i]->hdr); vq_inc_last_avail_packed(vq, PACKED_BATCH_SIZE); vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) { rte_memcpy((void *)(uintptr_t)(desc_addrs[i] + buf_offset), rte_pktmbuf_mtod_offset(pkts[i], void *, 0), pkts[i]->pkt_len); } vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) vhost_log_cache_write_iova(dev, vq, descs[avail_idx + i].addr, lens[i]); vhost_for_each_try_unroll(i, 0, PACKED_BATCH_SIZE) ids[i] = descs[avail_idx + i].id; vhost_flush_enqueue_batch_packed(dev, vq, lens, ids); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-665'], 'message': 'vhost: fix translated address not checked Malicious guest can construct desc with invalid address and zero buffer length. That will request vhost to check both translated address and translated data length. This patch will add missed address check. CVE-2020-10725 Fixes: 75ed51697820 ("vhost: add packed ring batch dequeue") Fixes: ef861692c398 ("vhost: add packed ring batch enqueue") Cc: stable@dpdk.org Signed-off-by: Marvin Liu <yong.liu@intel.com> Reviewed-by: Maxime Coquelin <maxime.coquelin@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: vhost_user_get_inflight_fd(struct virtio_net **pdev, VhostUserMsg *msg, int main_fd __rte_unused) { struct rte_vhost_inflight_info_packed *inflight_packed; uint64_t pervq_inflight_size, mmap_size; uint16_t num_queues, queue_size; struct virtio_net *dev = *pdev; int fd, i, j; void *addr; if (msg->size != sizeof(msg->payload.inflight)) { VHOST_LOG_CONFIG(ERR, "invalid get_inflight_fd message size is %d\n", msg->size); return RTE_VHOST_MSG_RESULT_ERR; } if (dev->inflight_info == NULL) { dev->inflight_info = calloc(1, sizeof(struct inflight_mem_info)); if (!dev->inflight_info) { VHOST_LOG_CONFIG(ERR, "failed to alloc dev inflight area\n"); return RTE_VHOST_MSG_RESULT_ERR; } } num_queues = msg->payload.inflight.num_queues; queue_size = msg->payload.inflight.queue_size; VHOST_LOG_CONFIG(INFO, "get_inflight_fd num_queues: %u\n", msg->payload.inflight.num_queues); VHOST_LOG_CONFIG(INFO, "get_inflight_fd queue_size: %u\n", msg->payload.inflight.queue_size); if (vq_is_packed(dev)) pervq_inflight_size = get_pervq_shm_size_packed(queue_size); else pervq_inflight_size = get_pervq_shm_size_split(queue_size); mmap_size = num_queues * pervq_inflight_size; addr = inflight_mem_alloc("vhost-inflight", mmap_size, &fd); if (!addr) { VHOST_LOG_CONFIG(ERR, "failed to alloc vhost inflight area\n"); msg->payload.inflight.mmap_size = 0; return RTE_VHOST_MSG_RESULT_ERR; } memset(addr, 0, mmap_size); dev->inflight_info->addr = addr; dev->inflight_info->size = msg->payload.inflight.mmap_size = mmap_size; dev->inflight_info->fd = msg->fds[0] = fd; msg->payload.inflight.mmap_offset = 0; msg->fd_num = 1; if (vq_is_packed(dev)) { for (i = 0; i < num_queues; i++) { inflight_packed = (struct rte_vhost_inflight_info_packed *)addr; inflight_packed->used_wrap_counter = 1; inflight_packed->old_used_wrap_counter = 1; for (j = 0; j < queue_size; j++) inflight_packed->desc[j].next = j + 1; addr = (void *)((char *)addr + pervq_inflight_size); } } VHOST_LOG_CONFIG(INFO, "send inflight mmap_size: %"PRIu64"\n", msg->payload.inflight.mmap_size); VHOST_LOG_CONFIG(INFO, "send inflight mmap_offset: %"PRIu64"\n", msg->payload.inflight.mmap_offset); VHOST_LOG_CONFIG(INFO, "send inflight fd: %d\n", msg->fds[0]); return RTE_VHOST_MSG_RESULT_REPLY; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'vhost: fix potential memory space leak A malicious container which has direct access to the vhost-user socket can keep sending VHOST_USER_GET_INFLIGHT_FD messages which may cause leaking resources until resulting a DOS. Fix it by unmapping the dev->inflight_info->addr before assigning new mapped addr to it. CVE-2020-10726 Fixes: d87f1a1cb7b6 ("vhost: support inflight info sharing") Cc: stable@dpdk.org Signed-off-by: Xiaolong Ye <xiaolong.ye@intel.com> Reviewed-by: Maxime Coquelin <maxime.coquelin@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: vhost_backend_cleanup(struct virtio_net *dev) { if (dev->mem) { free_mem_region(dev); rte_free(dev->mem); dev->mem = NULL; } rte_free(dev->guest_pages); dev->guest_pages = NULL; if (dev->log_addr) { munmap((void *)(uintptr_t)dev->log_addr, dev->log_size); dev->log_addr = 0; } if (dev->inflight_info) { if (dev->inflight_info->addr) { munmap(dev->inflight_info->addr, dev->inflight_info->size); dev->inflight_info->addr = NULL; } if (dev->inflight_info->fd > 0) { close(dev->inflight_info->fd); dev->inflight_info->fd = -1; } free(dev->inflight_info); dev->inflight_info = NULL; } if (dev->slave_req_fd >= 0) { close(dev->slave_req_fd); dev->slave_req_fd = -1; } if (dev->postcopy_ufd >= 0) { close(dev->postcopy_ufd); dev->postcopy_ufd = -1; } dev->postcopy_listening = 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'vhost: fix potential fd leak Vhost will create temporary file when receiving VHOST_USER_GET_INFLIGHT_FD message. Malicious guest can send endless this message to drain out the resource of host. When receiving VHOST_USER_GET_INFLIGHT_FD message repeatedly, closing the file created during the last handling of this message. CVE-2020-10726 Fixes: d87f1a1cb7b666550 ("vhost: support inflight info sharing") Cc: stable@dpdk.org Signed-off-by: Xuan Ding <xuan.ding@intel.com> Signed-off-by: Xiaolong Ye <xiaolong.ye@intel.com> Reviewed-by: Maxime Coquelin <maxime.coquelin@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: vhost_user_get_inflight_fd(struct virtio_net **pdev, VhostUserMsg *msg, int main_fd __rte_unused) { struct rte_vhost_inflight_info_packed *inflight_packed; uint64_t pervq_inflight_size, mmap_size; uint16_t num_queues, queue_size; struct virtio_net *dev = *pdev; int fd, i, j; void *addr; if (msg->size != sizeof(msg->payload.inflight)) { VHOST_LOG_CONFIG(ERR, "invalid get_inflight_fd message size is %d\n", msg->size); return RTE_VHOST_MSG_RESULT_ERR; } if (dev->inflight_info == NULL) { dev->inflight_info = calloc(1, sizeof(struct inflight_mem_info)); if (!dev->inflight_info) { VHOST_LOG_CONFIG(ERR, "failed to alloc dev inflight area\n"); return RTE_VHOST_MSG_RESULT_ERR; } } num_queues = msg->payload.inflight.num_queues; queue_size = msg->payload.inflight.queue_size; VHOST_LOG_CONFIG(INFO, "get_inflight_fd num_queues: %u\n", msg->payload.inflight.num_queues); VHOST_LOG_CONFIG(INFO, "get_inflight_fd queue_size: %u\n", msg->payload.inflight.queue_size); if (vq_is_packed(dev)) pervq_inflight_size = get_pervq_shm_size_packed(queue_size); else pervq_inflight_size = get_pervq_shm_size_split(queue_size); mmap_size = num_queues * pervq_inflight_size; addr = inflight_mem_alloc("vhost-inflight", mmap_size, &fd); if (!addr) { VHOST_LOG_CONFIG(ERR, "failed to alloc vhost inflight area\n"); msg->payload.inflight.mmap_size = 0; return RTE_VHOST_MSG_RESULT_ERR; } memset(addr, 0, mmap_size); if (dev->inflight_info->addr) { munmap(dev->inflight_info->addr, dev->inflight_info->size); dev->inflight_info->addr = NULL; } dev->inflight_info->addr = addr; dev->inflight_info->size = msg->payload.inflight.mmap_size = mmap_size; dev->inflight_info->fd = msg->fds[0] = fd; msg->payload.inflight.mmap_offset = 0; msg->fd_num = 1; if (vq_is_packed(dev)) { for (i = 0; i < num_queues; i++) { inflight_packed = (struct rte_vhost_inflight_info_packed *)addr; inflight_packed->used_wrap_counter = 1; inflight_packed->old_used_wrap_counter = 1; for (j = 0; j < queue_size; j++) inflight_packed->desc[j].next = j + 1; addr = (void *)((char *)addr + pervq_inflight_size); } } VHOST_LOG_CONFIG(INFO, "send inflight mmap_size: %"PRIu64"\n", msg->payload.inflight.mmap_size); VHOST_LOG_CONFIG(INFO, "send inflight mmap_offset: %"PRIu64"\n", msg->payload.inflight.mmap_offset); VHOST_LOG_CONFIG(INFO, "send inflight fd: %d\n", msg->fds[0]); return RTE_VHOST_MSG_RESULT_REPLY; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'vhost: fix potential fd leak Vhost will create temporary file when receiving VHOST_USER_GET_INFLIGHT_FD message. Malicious guest can send endless this message to drain out the resource of host. When receiving VHOST_USER_GET_INFLIGHT_FD message repeatedly, closing the file created during the last handling of this message. CVE-2020-10726 Fixes: d87f1a1cb7b666550 ("vhost: support inflight info sharing") Cc: stable@dpdk.org Signed-off-by: Xuan Ding <xuan.ding@intel.com> Signed-off-by: Xiaolong Ye <xiaolong.ye@intel.com> Reviewed-by: Maxime Coquelin <maxime.coquelin@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: DeepScanLineInputFile::DeepScanLineInputFile (const char fileName[], int numThreads) : _data (new Data (numThreads)) { _data->_streamData = new InputStreamMutex(); _data->_deleteStream = true; OPENEXR_IMF_INTERNAL_NAMESPACE::IStream* is = 0; try { is = new StdIFStream (fileName); readMagicNumberAndVersionField(*is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(*is); return; } _data->_streamData->is = is; _data->memoryMapped = is->isMemoryMapped(); _data->header.readFrom (*_data->_streamData->is, _data->version); _data->header.sanityCheck (isTiled (_data->version)); initialize(_data->header); readLineOffsets (*_data->_streamData->is, _data->lineOrder, _data->lineOffsets, _data->fileIsComplete); } catch (IEX_NAMESPACE::BaseExc &e) { if (is) delete is; if (_data && _data->_streamData) delete _data->_streamData; if (_data) delete _data; REPLACE_EXC (e, "Cannot read image file " "\"" << fileName << "\". " << e.what()); throw; } catch (...) { if (is) delete is; if (_data && _data->_streamData) delete _data->_streamData; if (_data) delete _data; throw; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: void readFile (int channelCount, bool bulkRead, bool relativeCoords, bool randomChannels, const std::string & filename) { if (relativeCoords) assert(bulkRead == false); cout << "reading " << flush; DeepTiledInputFile file (filename.c_str(), 4); const Header& fileHeader = file.header(); assert (fileHeader.displayWindow() == header.displayWindow()); assert (fileHeader.dataWindow() == header.dataWindow()); assert (fileHeader.pixelAspectRatio() == header.pixelAspectRatio()); assert (fileHeader.screenWindowCenter() == header.screenWindowCenter()); assert (fileHeader.screenWindowWidth() == header.screenWindowWidth()); assert (fileHeader.lineOrder() == header.lineOrder()); assert (fileHeader.compression() == header.compression()); assert (fileHeader.channels() == header.channels()); assert (fileHeader.type() == header.type()); assert (fileHeader.tileDescription() == header.tileDescription()); Array2D<unsigned int> localSampleCount; localSampleCount.resizeErase(height, width); // also test filling channels. Generate up to 2 extra channels int fillChannels=random_int(3); Array<Array2D< void* > > data(channelCount+fillChannels); for (int i = 0; i < channelCount+fillChannels; i++) data[i].resizeErase(height, width); DeepFrameBuffer frameBuffer; int memOffset; if (relativeCoords) memOffset = 0; else memOffset = dataWindow.min.x + dataWindow.min.y * width; frameBuffer.insertSampleCountSlice (Slice (IMF::UINT, (char *) (&localSampleCount[0][0] - memOffset), sizeof (unsigned int) * 1, sizeof (unsigned int) * width, 1, 1, 0, relativeCoords, relativeCoords)); vector<int> read_channel(channelCount); int channels_added=0; for (int i = 0; i < channelCount; i++) { if(randomChannels) { read_channel[i] = random_int(2); } if(!randomChannels || read_channel[i]==1) { PixelType type = IMF::NUM_PIXELTYPES; if (channelTypes[i] == 0) type = IMF::UINT; if (channelTypes[i] == 1) type = IMF::HALF; if (channelTypes[i] == 2) type = IMF::FLOAT; stringstream ss; ss << i; string str = ss.str(); int sampleSize = 0; if (channelTypes[i] == 0) sampleSize = sizeof (unsigned int); if (channelTypes[i] == 1) sampleSize = sizeof (half); if (channelTypes[i] == 2) sampleSize = sizeof (float); int pointerSize = sizeof (char *); frameBuffer.insert (str, DeepSlice (type, (char *) (&data[i][0][0] - memOffset), pointerSize * 1, pointerSize * width, sampleSize, 1, 1, 0, relativeCoords, relativeCoords)); channels_added++; } } if(channels_added==0) { cout << "skipping " <<flush; return; } for(int i = 0 ; i < fillChannels ; ++i ) { PixelType type = IMF::FLOAT; int sampleSize = sizeof(float); int pointerSize = sizeof (char *); stringstream ss; // generate channel names that aren't in file but (might) interleave with existing file ss << i << "fill"; string str = ss.str(); frameBuffer.insert (str, DeepSlice (type, (char *) (&data[i+channelCount][0][0] - memOffset), pointerSize * 1, pointerSize * width, sampleSize, 1, 1, 0, relativeCoords, relativeCoords)); } file.setFrameBuffer(frameBuffer); if (bulkRead) cout << "bulk " << flush; else { if (relativeCoords == false) cout << "per-tile " << flush; else cout << "per-tile with relative coordinates " << flush; } for (int ly = 0; ly < file.numYLevels(); ly++) for (int lx = 0; lx < file.numXLevels(); lx++) { Box2i dataWindowL = file.dataWindowForLevel(lx, ly); if (bulkRead) { // // Testing bulk read (without relative coordinates). // file.readPixelSampleCounts(0, file.numXTiles(lx) - 1, 0, file.numYTiles(ly) - 1, lx, ly); for (int i = 0; i < file.numYTiles(ly); i++) { for (int j = 0; j < file.numXTiles(lx); j++) { Box2i box = file.dataWindowForTile(j, i, lx, ly); for (int y = box.min.y; y <= box.max.y; y++) for (int x = box.min.x; x <= box.max.x; x++) { int dwy = y - dataWindowL.min.y; int dwx = x - dataWindowL.min.x; assert(localSampleCount[dwy][dwx] == sampleCountWhole[ly][lx][dwy][dwx]); for (size_t k = 0; k < channelTypes.size(); k++) { if (channelTypes[k] == 0) data[k][dwy][dwx] = new unsigned int[localSampleCount[dwy][dwx]]; if (channelTypes[k] == 1) data[k][dwy][dwx] = new half[localSampleCount[dwy][dwx]]; if (channelTypes[k] == 2) data[k][dwy][dwx] = new float[localSampleCount[dwy][dwx]]; } for( int f = 0 ; f < fillChannels ; ++f ) { data[f + channelTypes.size()][dwy][dwx] = new float[localSampleCount[dwy][dwx]]; } } } } file.readTiles(0, file.numXTiles(lx) - 1, 0, file.numYTiles(ly) - 1, lx, ly); } else if (bulkRead == false) { if (relativeCoords == false) { // // Testing per-tile read without relative coordinates. // for (int i = 0; i < file.numYTiles(ly); i++) { for (int j = 0; j < file.numXTiles(lx); j++) { file.readPixelSampleCount(j, i, lx, ly); Box2i box = file.dataWindowForTile(j, i, lx, ly); for (int y = box.min.y; y <= box.max.y; y++) for (int x = box.min.x; x <= box.max.x; x++) { int dwy = y - dataWindowL.min.y; int dwx = x - dataWindowL.min.x; assert(localSampleCount[dwy][dwx] == sampleCountWhole[ly][lx][dwy][dwx]); for (size_t k = 0; k < channelTypes.size(); k++) { if (channelTypes[k] == 0) data[k][dwy][dwx] = new unsigned int[localSampleCount[dwy][dwx]]; if (channelTypes[k] == 1) data[k][dwy][dwx] = new half[localSampleCount[dwy][dwx]]; if (channelTypes[k] == 2) data[k][dwy][dwx] = new float[localSampleCount[dwy][dwx]]; } for( int f = 0 ; f < fillChannels ; ++f ) { data[f + channelTypes.size()][dwy][dwx] = new float[localSampleCount[dwy][dwx]]; } } file.readTile(j, i, lx, ly); } } } else if (relativeCoords) { // // Testing per-tile read with relative coordinates. // for (int i = 0; i < file.numYTiles(ly); i++) { for (int j = 0; j < file.numXTiles(lx); j++) { file.readPixelSampleCount(j, i, lx, ly); Box2i box = file.dataWindowForTile(j, i, lx, ly); for (int y = box.min.y; y <= box.max.y; y++) for (int x = box.min.x; x <= box.max.x; x++) { int dwy = y - dataWindowL.min.y; int dwx = x - dataWindowL.min.x; int ty = y - box.min.y; int tx = x - box.min.x; assert(localSampleCount[ty][tx] == sampleCountWhole[ly][lx][dwy][dwx]); for (size_t k = 0; k < channelTypes.size(); k++) { if( !randomChannels || read_channel[k]==1) { if (channelTypes[k] == 0) data[k][ty][tx] = new unsigned int[localSampleCount[ty][tx]]; if (channelTypes[k] == 1) data[k][ty][tx] = new half[localSampleCount[ty][tx]]; if (channelTypes[k] == 2) data[k][ty][tx] = new float[localSampleCount[ty][tx]]; } } for( int f = 0 ; f < fillChannels ; ++f ) { data[f + channelTypes.size()][ty][tx] = new float[localSampleCount[ty][tx]]; } } file.readTile(j, i, lx, ly); for (int y = box.min.y; y <= box.max.y; y++) for (int x = box.min.x; x <= box.max.x; x++) { int dwy = y - dataWindowL.min.y; int dwx = x - dataWindowL.min.x; int ty = y - box.min.y; int tx = x - box.min.x; for (size_t k = 0; k < channelTypes.size(); k++) { if( !randomChannels || read_channel[k]==1) { checkValue(data[k][ty][tx], localSampleCount[ty][tx], channelTypes[k], dwx, dwy); if (channelTypes[k] == 0) delete[] (unsigned int*) data[k][ty][tx]; if (channelTypes[k] == 1) delete[] (half*) data[k][ty][tx]; if (channelTypes[k] == 2) delete[] (float*) data[k][ty][tx]; } } for( int f = 0 ; f < fillChannels ; ++f ) { delete[] (float*) data[f+channelTypes.size()][ty][tx]; } } } } } } if (relativeCoords == false) { for (int i = 0; i < file.levelHeight(ly); i++) for (int j = 0; j < file.levelWidth(lx); j++) for (int k = 0; k < channelCount; k++) { if( !randomChannels || read_channel[k]==1) { for (unsigned int l = 0; l < localSampleCount[i][j]; l++) { if (channelTypes[k] == 0) { unsigned int* value = (unsigned int*)(data[k][i][j]); if (value[l] != static_cast<unsigned int>(i * width + j) % 2049) cout << j << ", " << i << " error, should be " << (i * width + j) % 2049 << ", is " << value[l] << endl << flush; assert (value[l] == static_cast<unsigned int>(i * width + j) % 2049); } if (channelTypes[k] == 1) { half* value = (half*)(data[k][i][j]); if (value[l] != (i * width + j) % 2049) cout << j << ", " << i << " error, should be " << (i * width + j) % 2049 << ", is " << value[l] << endl << flush; assert (((half*)(data[k][i][j]))[l] == (i * width + j) % 2049); } if (channelTypes[k] == 2) { float* value = (float*)(data[k][i][j]); if (value[l] != (i * width + j) % 2049) cout << j << ", " << i << " error, should be " << (i * width + j) % 2049 << ", is " << value[l] << endl << flush; assert (((float*)(data[k][i][j]))[l] == (i * width + j) % 2049); } } } } for (int i = 0; i < file.levelHeight(ly); i++) for (int j = 0; j < file.levelWidth(lx); j++) { for (int k = 0; k < channelCount; k++) { if( !randomChannels || read_channel[k]==1) { if (channelTypes[k] == 0) delete[] (unsigned int*) data[k][i][j]; if (channelTypes[k] == 1) delete[] (half*) data[k][i][j]; if (channelTypes[k] == 2) delete[] (float*) data[k][i][j]; } } for( int f = 0 ; f < fillChannels ; ++f ) { delete[] (float*) data[f+channelTypes.size()][i][j]; } } } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: ScanLineInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) { Lock lock (*_streamData); const ChannelList &channels = _data->header.channels(); for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { ChannelList::ConstIterator i = channels.find (j.name()); if (i == channels.end()) continue; if (i.channel().xSampling != j.slice().xSampling || i.channel().ySampling != j.slice().ySampling) THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors " "of \"" << i.name() << "\" channel " "of input file \"" << fileName() << "\" are " "not compatible with the frame buffer's " "subsampling factors."); } // optimization is possible if this is a little endian system // and both inputs and outputs are half floats // bool optimizationPossible = true; if (!GLOBAL_SYSTEM_LITTLE_ENDIAN) { optimizationPossible =false; } vector<sliceOptimizationData> optData; // // Initialize the slice table for readPixels(). // vector<InSliceInfo> slices; ChannelList::ConstIterator i = channels.begin(); // current offset of channel: pixel data starts at offset*width into the // decompressed scanline buffer size_t offset = 0; for (FrameBuffer::ConstIterator j = frameBuffer.begin(); j != frameBuffer.end(); ++j) { while (i != channels.end() && strcmp (i.name(), j.name()) < 0) { // // Channel i is present in the file but not // in the frame buffer; data for channel i // will be skipped during readPixels(). // slices.push_back (InSliceInfo (i.channel().type, i.channel().type, 0, // base 0, // xStride 0, // yStride i.channel().xSampling, i.channel().ySampling, false, // fill true, // skip 0.0)); // fillValue switch(i.channel().type) { case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : offset++; break; case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : offset+=2; break; case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : offset+=2; break; case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES: default: // not possible. break; } ++i; } bool fill = false; if (i == channels.end() || strcmp (i.name(), j.name()) > 0) { // // Channel i is present in the frame buffer, but not in the file. // In the frame buffer, slice j will be filled with a default value. // fill = true; } slices.push_back (InSliceInfo (j.slice().type, fill? j.slice().type: i.channel().type, j.slice().base, j.slice().xStride, j.slice().yStride, j.slice().xSampling, j.slice().ySampling, fill, false, // skip j.slice().fillValue)); if(!fill && i.channel().type!=OPENEXR_IMF_INTERNAL_NAMESPACE::HALF) { optimizationPossible = false; } if(j.slice().type != OPENEXR_IMF_INTERNAL_NAMESPACE::HALF) { optimizationPossible = false; } if(j.slice().xSampling!=1 || j.slice().ySampling!=1) { optimizationPossible = false; } if(optimizationPossible) { sliceOptimizationData dat; dat.base = j.slice().base; dat.fill = fill; dat.fillValue = j.slice().fillValue; dat.offset = offset; dat.xStride = j.slice().xStride; dat.yStride = j.slice().yStride; dat.xSampling = j.slice().xSampling; dat.ySampling = j.slice().ySampling; optData.push_back(dat); } if(!fill) { switch(i.channel().type) { case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : offset++; break; case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : offset+=2; break; case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : offset+=2; break; case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES: default: // not possible. break; } } if (i != channels.end() && !fill) ++i; } if(optimizationPossible) { // // check optimisibility // based on channel ordering and fill channel positions // sort(optData.begin(),optData.end()); _data->optimizationMode = detectOptimizationMode(optData); } if(!optimizationPossible || _data->optimizationMode._optimizable==false) { optData = vector<sliceOptimizationData>(); _data->optimizationMode._optimizable=false; } // // Store the new frame buffer. // _data->frameBuffer = frameBuffer; _data->slices = slices; _data->optimizationData = optData; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: DeepScanLineInputFile::DeepScanLineInputFile(InputPartData* part) { _data = new Data(part->numThreads); _data->_deleteStream=false; _data->_streamData = part->mutex; _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); _data->version = part->version; initialize(part->header); _data->lineOffsets = part->chunkOffsets; _data->partNumber = part->partNumber; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: TiledInputFile::TiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int numThreads): _data (new Data (numThreads)) { _data->_deleteStream=false; // // This constructor is called when a user // explicitly wants to read a tiled file. // bool streamDataCreated = false; try { readMagicNumberAndVersionField(is, _data->version); // // Backward compatibility to read multpart file. // if (isMultiPart(_data->version)) { compatibilityInitialize(is); return; } streamDataCreated = true; _data->_streamData = new InputStreamMutex(); _data->_streamData->is = &is; _data->header.readFrom (*_data->_streamData->is, _data->version); initialize(); // file is guaranteed to be single part, regular image _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); _data->_streamData->currentPosition = _data->_streamData->is->tellg(); } catch (IEX_NAMESPACE::BaseExc &e) { if (streamDataCreated) delete _data->_streamData; delete _data; REPLACE_EXC (e, "Cannot open image file " "\"" << is.fileName() << "\". " << e.what()); throw; } catch (...) { if (streamDataCreated) delete _data->_streamData; delete _data; throw; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: generateRandomFile (int partCount, const std::string & fn) { // // Init data. // Array2D<half> halfData; Array2D<float> floatData; Array2D<unsigned int> uintData; fillPixels<unsigned int>(uintData, width, height); fillPixels<half>(halfData, width, height); fillPixels<float>(floatData, width, height); Array2D< Array2D< half > >* tiledHalfData = new Array2D< Array2D< half > >[partCount]; Array2D< Array2D< float > >* tiledFloatData = new Array2D< Array2D< float > >[partCount]; Array2D< Array2D< unsigned int > >* tiledUintData = new Array2D< Array2D< unsigned int > >[partCount]; vector<GenericOutputFile*> outputfiles; vector<WritingTaskData> taskList; pixelTypes.resize(partCount); partTypes.resize(partCount); levelModes.resize(partCount); // // Generate headers and data. // cout << "Generating headers and data " << flush; generateRandomHeaders(partCount, headers, taskList); // // Shuffle tasks. // cout << "Shuffling " << taskList.size() << " tasks " << flush; int taskListSize = taskList.size(); for (int i = 0; i < taskListSize; i++) { int a, b; a = random_int(taskListSize); b = random_int(taskListSize); swap(taskList[a], taskList[b]); } remove(fn.c_str()); MultiPartOutputFile file(fn.c_str(), &headers[0],headers.size()); // // Writing tasks. // cout << "Writing tasks " << flush; // // Pre-generating frameBuffers. // vector<void *> parts; vector<FrameBuffer> frameBuffers(partCount); Array<Array2D<FrameBuffer> >tiledFrameBuffers(partCount); for (int i = 0; i < partCount; i++) { if (partTypes[i] == 0) { OutputPart* part = new OutputPart(file, i); parts.push_back((void*) part); FrameBuffer& frameBuffer = frameBuffers[i]; setOutputFrameBuffer(frameBuffer, pixelTypes[i], uintData, floatData, halfData, width); part->setFrameBuffer(frameBuffer); } else { TiledOutputPart* part = new TiledOutputPart(file, i); parts.push_back((void*) part); int numXLevels = part->numXLevels(); int numYLevels = part->numYLevels(); // Allocating space. switch (pixelTypes[i]) { case 0: tiledUintData[i].resizeErase(numYLevels, numXLevels); break; case 1: tiledFloatData[i].resizeErase(numYLevels, numXLevels); break; case 2: tiledHalfData[i].resizeErase(numYLevels, numXLevels); break; } tiledFrameBuffers[i].resizeErase(numYLevels, numXLevels); for (int xLevel = 0; xLevel < numXLevels; xLevel++) for (int yLevel = 0; yLevel < numYLevels; yLevel++) { if (!part->isValidLevel(xLevel, yLevel)) continue; int w = part->levelWidth(xLevel); int h = part->levelHeight(yLevel); FrameBuffer& frameBuffer = tiledFrameBuffers[i][yLevel][xLevel]; switch (pixelTypes[i]) { case 0: fillPixels<unsigned int>(tiledUintData[i][yLevel][xLevel], w, h); break; case 1: fillPixels<float>(tiledFloatData[i][yLevel][xLevel], w, h); break; case 2: fillPixels<half>(tiledHalfData[i][yLevel][xLevel], w, h); break; } setOutputFrameBuffer(frameBuffer, pixelTypes[i], tiledUintData[i][yLevel][xLevel], tiledFloatData[i][yLevel][xLevel], tiledHalfData[i][yLevel][xLevel], w); } } } // // Writing tasks. // TaskGroup taskGroup; ThreadPool* threadPool = new ThreadPool(32); vector<WritingTaskData*> list; for (int i = 0; i < taskListSize; i++) { list.push_back(&taskList[i]); if (i % 10 == 0 || i == taskListSize - 1) { threadPool->addTask( (new WritingTask (&taskGroup, &file, list, tiledFrameBuffers))); list.clear(); } } delete threadPool; delete[] tiledHalfData; delete[] tiledUintData; delete[] tiledFloatData; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: InputFile::InputFile (InputPartData* part) : _data (new Data (part->numThreads)) { _data->_deleteStream=false; multiPartInitialize (part); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: bytesPerLineTable (const Header &header, vector<size_t> &bytesPerLine) { const Box2i &dataWindow = header.dataWindow(); const ChannelList &channels = header.channels(); bytesPerLine.resize (dataWindow.max.y - dataWindow.min.y + 1); for (ChannelList::ConstIterator c = channels.begin(); c != channels.end(); ++c) { int nBytes = pixelTypeSize (c.channel().type) * (dataWindow.max.x - dataWindow.min.x + 1) / c.channel().xSampling; for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i) if (modp (y, c.channel().ySampling) == 0) bytesPerLine[i] += nBytes; } size_t maxBytesPerLine = 0; for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i) if (maxBytesPerLine < bytesPerLine[i]) maxBytesPerLine = bytesPerLine[i]; return maxBytesPerLine; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: Classifier (const char *&ptr, int size) { if (size <= 0) throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (truncated rule)."); { char suffix[Name::SIZE]; memset (suffix, 0, Name::SIZE); Xdr::read<CharPtrIO> (ptr, std::min(size, Name::SIZE-1), suffix); _suffix = std::string(suffix); } if (static_cast<size_t>(size) < _suffix.length() + 1 + 2*Xdr::size<char>()) throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (truncated rule)."); char value; Xdr::read<CharPtrIO> (ptr, value); _cscIdx = (int)(value >> 4) - 1; if (_cscIdx < -1 || _cscIdx >= 3) throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (corrupt cscIdx rule)."); _scheme = (CompressorScheme)((value >> 2) & 3); if (_scheme < 0 || _scheme >= NUM_COMPRESSOR_SCHEMES) throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (corrupt scheme rule)."); _caseInsensitive = (value & 1 ? true : false); Xdr::read<CharPtrIO> (ptr, value); if (value < 0 || value >= NUM_PIXELTYPES) throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" " (corrupt rule)."); _type = (PixelType)value; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: PizCompressor::uncompress (const char *inPtr, int inSize, IMATH_NAMESPACE::Box2i range, const char *&outPtr) { // // This is the cunompress function which is used by both the tiled and // scanline decompression routines. // // // Special case - empty input buffer // if (inSize == 0) { outPtr = _outBuffer; return 0; } // // Determine the layout of the compressed pixel data // int minX = range.min.x; int maxX = range.max.x; int minY = range.min.y; int maxY = range.max.y; if (maxY > _maxY) maxY = _maxY; if (maxX > _maxX) maxX = _maxX; unsigned short *tmpBufferEnd = _tmpBuffer; int i = 0; for (ChannelList::ConstIterator c = _channels.begin(); c != _channels.end(); ++c, ++i) { ChannelData &cd = _channelData[i]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = numSamples (c.channel().xSampling, minX, maxX); cd.ny = numSamples (c.channel().ySampling, minY, maxY); cd.ys = c.channel().ySampling; cd.size = pixelTypeSize (c.channel().type) / pixelTypeSize (HALF); tmpBufferEnd += cd.nx * cd.ny * cd.size; } // // Read range compression data // unsigned short minNonZero; unsigned short maxNonZero; AutoArray <unsigned char, BITMAP_SIZE> bitmap; memset (bitmap, 0, sizeof (unsigned char) * BITMAP_SIZE); Xdr::read <CharPtrIO> (inPtr, minNonZero); Xdr::read <CharPtrIO> (inPtr, maxNonZero); if (maxNonZero >= BITMAP_SIZE) { throw InputExc ("Error in header for PIZ-compressed data " "(invalid bitmap size)."); } if (minNonZero <= maxNonZero) { Xdr::read <CharPtrIO> (inPtr, (char *) &bitmap[0] + minNonZero, maxNonZero - minNonZero + 1); } AutoArray <unsigned short, USHORT_RANGE> lut; unsigned short maxValue = reverseLutFromBitmap (bitmap, lut); // // Huffman decoding // int length; Xdr::read <CharPtrIO> (inPtr, length); if (length > inSize) { throw InputExc ("Error in header for PIZ-compressed data " "(invalid array length)."); } hufUncompress (inPtr, length, _tmpBuffer, tmpBufferEnd - _tmpBuffer); // // Wavelet decoding // for (int i = 0; i < _numChans; ++i) { ChannelData &cd = _channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode (cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut (lut, _tmpBuffer, tmpBufferEnd - _tmpBuffer); // // Rearrange the pixel data into the format expected by the caller. // char *outEnd = _outBuffer; if (_format == XDR) { // // Machine-independent (Xdr) data format // for (int y = minY; y <= maxY; ++y) { for (int i = 0; i < _numChans; ++i) { ChannelData &cd = _channelData[i]; if (modp (y, cd.ys) != 0) continue; for (int x = cd.nx * cd.size; x > 0; --x) { Xdr::write <CharPtrIO> (outEnd, *cd.end); ++cd.end; } } } } else { // // Native, machine-dependent data format // for (int y = minY; y <= maxY; ++y) { for (int i = 0; i < _numChans; ++i) { ChannelData &cd = _channelData[i]; if (modp (y, cd.ys) != 0) continue; int n = cd.nx * cd.size; memcpy (outEnd, cd.end, n * sizeof (unsigned short)); outEnd += n * sizeof (unsigned short); cd.end += n; } } } #if defined (DEBUG) for (int i = 1; i < _numChans; ++i) assert (_channelData[i-1].end == _channelData[i].start); assert (_channelData[_numChans-1].end == tmpBufferEnd); #endif outPtr = _outBuffer; return outEnd - _outBuffer; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: DeepScanLineInputFile::~DeepScanLineInputFile () { if (_data->_deleteStream) delete _data->_streamData->is; if (_data) { if (!_data->memoryMapped) for (size_t i = 0; i < _data->lineBuffers.size(); i++) delete [] _data->lineBuffers[i]->buffer; // // Unless this file was opened via the multipart API, delete the streamdata // object too. // (TODO) it should be "isMultiPart(data->version)", but when there is only // single part, // (see the above constructor) the version field is not set. // // (TODO) we should have a way to tell if the stream data is owned by this // file or by a parent multipart file. // if (_data->partNumber == -1 && _data->_streamData) delete _data->_streamData; delete _data; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: generatePreview (const char inFileName[], float exposure, int previewWidth, int &previewHeight, Array2D <PreviewRgba> &previewPixels) { // // Read the input file // RgbaInputFile in (inFileName); Box2i dw = in.dataWindow(); float a = in.pixelAspectRatio(); int w = dw.max.x - dw.min.x + 1; int h = dw.max.y - dw.min.y + 1; Array2D <Rgba> pixels (h, w); in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w); in.readPixels (dw.min.y, dw.max.y); // // Make a preview image // previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1); previewPixels.resizeErase (previewHeight, previewWidth); float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1; float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1; float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f)); for (int y = 0; y < previewHeight; ++y) { for (int x = 0; x < previewWidth; ++x) { PreviewRgba &preview = previewPixels[y][x]; const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)]; preview.r = gamma (pixel.r, m); preview.g = gamma (pixel.g, m); preview.b = gamma (pixel.b, m); preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: void DeepScanLineInputFile::initialize(const Header& header) { try { if (header.type() != DEEPSCANLINE) throw IEX_NAMESPACE::ArgExc("Can't build a DeepScanLineInputFile from " "a type-mismatched part."); if(header.version()!=1) { THROW(IEX_NAMESPACE::ArgExc, "Version " << header.version() << " not supported for deepscanline images in this version of the library"); } _data->header = header; _data->lineOrder = _data->header.lineOrder(); const Box2i &dataWindow = _data->header.dataWindow(); _data->minX = dataWindow.min.x; _data->maxX = dataWindow.max.x; _data->minY = dataWindow.min.y; _data->maxY = dataWindow.max.y; _data->sampleCount.resizeErase(_data->maxY - _data->minY + 1, _data->maxX - _data->minX + 1); _data->lineSampleCount.resizeErase(_data->maxY - _data->minY + 1); Compressor* compressor = newCompressor(_data->header.compression(), 0, _data->header); _data->linesInBuffer = numLinesInBuffer (compressor); delete compressor; _data->nextLineBufferMinY = _data->minY - 1; int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y + _data->linesInBuffer) / _data->linesInBuffer; _data->lineOffsets.resize (lineOffsetSize); for (size_t i = 0; i < _data->lineBuffers.size(); i++) _data->lineBuffers[i] = new LineBuffer (); _data->gotSampleCount.resizeErase(_data->maxY - _data->minY + 1); for (int i = 0; i < _data->maxY - _data->minY + 1; i++) _data->gotSampleCount[i] = false; _data->maxSampleCountTableSize = min(_data->linesInBuffer, _data->maxY - _data->minY + 1) * (_data->maxX - _data->minX + 1) * sizeof(unsigned int); _data->sampleCountTableBuffer.resizeErase(_data->maxSampleCountTableSize); _data->sampleCountTableComp = newCompressor(_data->header.compression(), _data->maxSampleCountTableSize, _data->header); _data->bytesPerLine.resize (_data->maxY - _data->minY + 1); const ChannelList & c=header.channels(); _data->combinedSampleSize=0; for(ChannelList::ConstIterator i=c.begin();i!=c.end();i++) { switch(i.channel().type) { case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : _data->combinedSampleSize+=Xdr::size<half>(); break; case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : _data->combinedSampleSize+=Xdr::size<float>(); break; case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : _data->combinedSampleSize+=Xdr::size<unsigned int>(); break; default : THROW(IEX_NAMESPACE::ArgExc, "Bad type for channel " << i.name() << " initializing deepscanline reader"); } } } catch (...) { delete _data; _data=NULL; throw; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: DeepScanLineInputFile::DeepScanLineInputFile (const Header &header, OPENEXR_IMF_INTERNAL_NAMESPACE::IStream *is, int version, int numThreads) : _data (new Data (numThreads)) { _data->_streamData=new InputStreamMutex(); _data->_deleteStream=false; _data->_streamData->is = is; _data->memoryMapped = is->isMemoryMapped(); _data->version =version; initialize (header); readLineOffsets (*_data->_streamData->is, _data->lineOrder, _data->lineOffsets, _data->fileIsComplete); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: TiledInputFile::TiledInputFile (InputPartData* part) { _data = new Data (part->numThreads); _data->_deleteStream=false; multiPartInitialize(part); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: generateRandomFile (int partCount, const std::string & fn) { // // Init data. // Array2D<half> halfData; Array2D<float> floatData; Array2D<unsigned int> uintData; fillPixels<unsigned int>(uintData, width, height); fillPixels<half>(halfData, width, height); fillPixels<float>(floatData, width, height); Array2D< Array2D< half > >* tiledHalfData = new Array2D< Array2D< half > >[partCount]; Array2D< Array2D< float > >* tiledFloatData = new Array2D< Array2D< float > >[partCount]; Array2D< Array2D< unsigned int > >* tiledUintData = new Array2D< Array2D< unsigned int > >[partCount]; vector<GenericOutputFile*> outputfiles; vector<Task> taskList; pixelTypes.resize(partCount); partTypes.resize(partCount); levelModes.resize(partCount); // // Generate headers and data. // cout << "Generating headers and data " << flush; generateRandomHeaders(partCount, headers, taskList); // // Shuffle tasks. // cout << "Shuffling " << taskList.size() << " tasks " << flush; int taskListSize = taskList.size(); for (int i = 0; i < taskListSize; i++) { int a, b; a = random_int(taskListSize); b = random_int(taskListSize); swap(taskList[a], taskList[b]); } remove(fn.c_str()); MultiPartOutputFile file(fn.c_str(), &headers[0],headers.size()); // // Writing tasks. // cout << "Writing tasks " << flush; // // Pre-generating frameBuffers. // vector<void *> parts; vector<FrameBuffer> frameBuffers(partCount); Array<Array2D<FrameBuffer> > tiledFrameBuffers(partCount); for (int i = 0; i < partCount; i++) { if (partTypes[i] == 0) { OutputPart* part = new OutputPart(file, i); parts.push_back((void*) part); FrameBuffer& frameBuffer = frameBuffers[i]; setOutputFrameBuffer(frameBuffer, pixelTypes[i], uintData, floatData, halfData, width); part->setFrameBuffer(frameBuffer); } else { TiledOutputPart* part = new TiledOutputPart(file, i); parts.push_back((void*) part); int numXLevels = part->numXLevels(); int numYLevels = part->numYLevels(); // Allocating space. switch (pixelTypes[i]) { case 0: tiledUintData[i].resizeErase(numYLevels, numXLevels); break; case 1: tiledFloatData[i].resizeErase(numYLevels, numXLevels); break; case 2: tiledHalfData[i].resizeErase(numYLevels, numXLevels); break; } tiledFrameBuffers[i].resizeErase(numYLevels, numXLevels); for (int xLevel = 0; xLevel < numXLevels; xLevel++) for (int yLevel = 0; yLevel < numYLevels; yLevel++) { if (!part->isValidLevel(xLevel, yLevel)) continue; int w = part->levelWidth(xLevel); int h = part->levelHeight(yLevel); FrameBuffer& frameBuffer = tiledFrameBuffers[i][yLevel][xLevel]; switch (pixelTypes[i]) { case 0: fillPixels<unsigned int>(tiledUintData[i][yLevel][xLevel], w, h); break; case 1: fillPixels<float>(tiledFloatData[i][yLevel][xLevel], w, h); break; case 2: fillPixels<half>(tiledHalfData[i][yLevel][xLevel], w, h); break; } setOutputFrameBuffer(frameBuffer, pixelTypes[i], tiledUintData[i][yLevel][xLevel], tiledFloatData[i][yLevel][xLevel], tiledHalfData[i][yLevel][xLevel], w); } } } // // Writing tasks. // for (int i = 0; i < taskListSize; i++) { int partNumber = taskList[i].partNumber; int partType = partTypes[partNumber]; if (partType == 0) { OutputPart* part = (OutputPart*) parts[partNumber]; part->writePixels(); } else { int tx = taskList[i].tx; int ty = taskList[i].ty; int lx = taskList[i].lx; int ly = taskList[i].ly; TiledOutputPart* part = (TiledOutputPart*) parts[partNumber]; part->setFrameBuffer(tiledFrameBuffers[partNumber][ly][lx]); part->writeTile(tx, ty, lx, ly); } } delete[] tiledHalfData; delete[] tiledUintData; delete[] tiledFloatData; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix memory leaks and invalid memory accesses Signed-off-by: Peter Hillman <peterh@wetafx.co.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: GIT_INLINE(bool) only_spaces_and_dots(const char *path) { const char *c = path; for (;; c++) { if (*c == '\0') return true; if (*c != ' ' && *c != '.') return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-706'], 'message': 'path: also guard `.gitmodules` against NTFS Alternate Data Streams We just safe-guarded `.git` against NTFS Alternate Data Stream-related attack vectors, and now it is time to do the same for `.gitmodules`. Note: In the added regression test, we refrain from verifying all kinds of variations between short names and NTFS Alternate Data Streams: as the new code disallows _all_ Alternate Data Streams of `.gitmodules`, it is enough to test one in order to know that all of them are guarded against. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.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: void test_checkout_nasty__git_tilde1(void) { #ifdef GIT_WIN32 test_checkout_fails("refs/heads/git_tilde1", ".git/foobar"); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-706'], 'message': 'Protect against 8.3 "short name" attacks also on Linux/macOS The Windows Subsystem for Linux (WSL) is getting increasingly popular, in particular because it makes it _so_ easy to run Linux software on Windows' files, via the auto-mounted Windows drives (`C:\` is mapped to `/mnt/c/`, no need to set that up manually). Unfortunately, files/directories on the Windows drives can be accessed via their _short names_, if that feature is enabled (which it is on the `C:` drive by default). Which means that we have to safeguard even our Linux users against the short name attacks. Further, while the default options of CIFS/SMB-mounts seem to disallow accessing files on network shares via their short names on Linux/macOS, it _is_ possible to do so with the right options. So let's just safe-guard against short name attacks _everywhere_. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.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: int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID) { CNetChunk Packet; if(!pMsg) return -1; // drop packet to dummy client if(0 <= ClientID && ClientID < MAX_CLIENTS && GameServer()->IsClientBot(ClientID)) return 0; mem_zero(&Packet, sizeof(CNetChunk)); Packet.m_ClientID = ClientID; Packet.m_pData = pMsg->Data(); Packet.m_DataSize = pMsg->Size(); if(Flags&MSGFLAG_VITAL) Packet.m_Flags |= NETSENDFLAG_VITAL; if(Flags&MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; // write message to demo recorder if(!(Flags&MSGFLAG_NORECORD)) m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size()); if(!(Flags&MSGFLAG_NOSEND)) { if(ClientID == -1) { // broadcast int i; for(i = 0; i < MAX_CLIENTS; i++) if(m_aClients[i].m_State == CClient::STATE_INGAME && !m_aClients[i].m_Quitting) { Packet.m_ClientID = i; m_NetServer.Send(&Packet); } } else m_NetServer.Send(&Packet); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-400'], 'message': 'changed a check'</s>
<s>[INST] Given the following code containing errors, provide 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 init_aliases(void) { FILE *fp; char alias[MAXALIASLEN + 1U]; char dir[PATH_MAX + 1U]; if ((fp = fopen(ALIASES_FILE, "r")) == NULL) { return 0; } while (fgets(alias, sizeof alias, fp) != NULL) { if (*alias == '#' || *alias == '\n' || *alias == 0) { continue; } { char * const z = alias + strlen(alias) - 1U; if (*z != '\n') { goto bad; } *z = 0; } do { if (fgets(dir, sizeof dir, fp) == NULL || *dir == 0) { goto bad; } { char * const z = dir + strlen(dir) - 1U; if (*z == '\n') { *z = 0; } } } while (*dir == '#' || *dir == 0); if (head == NULL) { if ((head = tail = malloc(sizeof *head)) == NULL || (tail->alias = strdup(alias)) == NULL || (tail->dir = strdup(dir)) == NULL) { die_mem(); } tail->next = NULL; } else { DirAlias *curr; if ((curr = malloc(sizeof *curr)) == NULL || (curr->alias = strdup(alias)) == NULL || (curr->dir = strdup(dir)) == NULL) { die_mem(); } tail->next = curr; tail = curr; } } fclose(fp); aliases_up++; return 0; bad: fclose(fp); logfile(LOG_ERR, MSG_ALIASES_BROKEN_FILE " [" ALIASES_FILE "]"); return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-824'], 'message': 'diraliases: always set the tail of the list to NULL Spotted and reported by Antonio Norales from GitHub Security Labs. Thanks!'</s>
<s>[INST] Given the following code containing errors, provide 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 cbs_jpeg_split_fragment(CodedBitstreamContext *ctx, CodedBitstreamFragment *frag, int header) { AVBufferRef *data_ref; uint8_t *data; size_t data_size; int unit, start, end, marker, next_start, next_marker; int err, i, j, length; if (frag->data_size < 4) { // Definitely too short to be meaningful. return AVERROR_INVALIDDATA; } for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++); if (i > 0) { av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at " "beginning of image.\n", i); } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size && frag->data[i]) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no SOI marker found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; if (marker != JPEG_MARKER_SOI) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first " "marker is %02x, should be SOI.\n", marker); return AVERROR_INVALIDDATA; } for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "no image content found.\n"); return AVERROR_INVALIDDATA; } marker = frag->data[i]; start = i + 1; for (unit = 0;; unit++) { if (marker == JPEG_MARKER_EOI) { break; } else if (marker == JPEG_MARKER_SOS) { for (i = start; i + 1 < frag->data_size; i++) { if (frag->data[i] != 0xff) continue; end = i; for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { if (frag->data[i] == 0x00) continue; next_marker = frag->data[i]; next_start = i + 1; } break; } } else { i = start; if (i + 2 > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker.\n", marker); return AVERROR_INVALIDDATA; } length = AV_RB16(frag->data + i); if (i + length > frag->data_size) { av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: " "truncated at %02x marker segment.\n", marker); return AVERROR_INVALIDDATA; } end = start + length; i = end; if (frag->data[i] != 0xff) { next_marker = -1; } else { for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++); if (i + 1 >= frag->data_size) { next_marker = -1; } else { next_marker = frag->data[i]; next_start = i + 1; } } } if (marker == JPEG_MARKER_SOS) { length = AV_RB16(frag->data + start); data_ref = NULL; data = av_malloc(end - start + AV_INPUT_BUFFER_PADDING_SIZE); if (!data) return AVERROR(ENOMEM); memcpy(data, frag->data + start, length); for (i = start + length, j = length; i < end; i++, j++) { if (frag->data[i] == 0xff) { while (frag->data[i] == 0xff) ++i; data[j] = 0xff; } else { data[j] = frag->data[i]; } } data_size = j; memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE); } else { data = frag->data + start; data_size = end - start; data_ref = frag->data_ref; } err = ff_cbs_insert_unit_data(ctx, frag, unit, marker, data, data_size, data_ref); if (err < 0) return err; if (next_marker == -1) break; marker = next_marker; start = next_start; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'avcodec/cbs_jpeg: Check length for SOS Fixes: out of array access Fixes: 19734/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5673507031875584 Fixes: 19353/clusterfuzz-testcase-minimized-ffmpeg_BSF_TRACE_HEADERS_fuzzer-5703944462663680 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg 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: void freeListData(char *** data, unsigned int length) { for(int i=0; i<length; i++) { free((*data)[i]); } free(*data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix a double free in the List functions The code was set up so that it would free the individual items and the data in `freeListData`, but there was already a Go `defer` to free the data item, resulting in a double free. Remove the `free` in `freeListData` and leave the original one. In addition, move the `defer` for freeing the list data before the error check, so that the data is also free in the error case. This just removes a minor leak. This vulnerability was discovered by: Jasiel Spelman of Trend Micro Zero Day Initiative and Trend Micro Team Nebula Signed-off-by: Justin Cormack <justin.cormack@docker.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: mptctl_do_fw_download(int ioc, char __user *ufwbuf, size_t fwlen) { FWDownload_t *dlmsg; MPT_FRAME_HDR *mf; MPT_ADAPTER *iocp; FWDownloadTCSGE_t *ptsge; MptSge_t *sgl, *sgIn; char *sgOut; struct buflist *buflist; struct buflist *bl; dma_addr_t sgl_dma; int ret; int numfrags = 0; int maxfrags; int n = 0; u32 sgdir; u32 nib; int fw_bytes_copied = 0; int i; int sge_offset = 0; u16 iocstat; pFWDownloadReply_t ReplyMsg = NULL; unsigned long timeleft; if (mpt_verify_adapter(ioc, &iocp) < 0) { printk(KERN_DEBUG MYNAM "ioctl_fwdl - ioc%d not found!\n", ioc); return -ENODEV; /* (-6) No such device or address */ } else { /* Valid device. Get a message frame and construct the FW download message. */ if ((mf = mpt_get_msg_frame(mptctl_id, iocp)) == NULL) return -EAGAIN; } dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "mptctl_do_fwdl called. mptctl_id = %xh.\n", iocp->name, mptctl_id)); dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.bufp = %p\n", iocp->name, ufwbuf)); dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.fwlen = %d\n", iocp->name, (int)fwlen)); dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.ioc = %04xh\n", iocp->name, ioc)); dlmsg = (FWDownload_t*) mf; ptsge = (FWDownloadTCSGE_t *) &dlmsg->SGL; sgOut = (char *) (ptsge + 1); /* * Construct f/w download request */ dlmsg->ImageType = MPI_FW_DOWNLOAD_ITYPE_FW; dlmsg->Reserved = 0; dlmsg->ChainOffset = 0; dlmsg->Function = MPI_FUNCTION_FW_DOWNLOAD; dlmsg->Reserved1[0] = dlmsg->Reserved1[1] = dlmsg->Reserved1[2] = 0; if (iocp->facts.MsgVersion >= MPI_VERSION_01_05) dlmsg->MsgFlags = MPI_FW_DOWNLOAD_MSGFLGS_LAST_SEGMENT; else dlmsg->MsgFlags = 0; /* Set up the Transaction SGE. */ ptsge->Reserved = 0; ptsge->ContextSize = 0; ptsge->DetailsLength = 12; ptsge->Flags = MPI_SGE_FLAGS_TRANSACTION_ELEMENT; ptsge->Reserved_0100_Checksum = 0; ptsge->ImageOffset = 0; ptsge->ImageSize = cpu_to_le32(fwlen); /* Add the SGL */ /* * Need to kmalloc area(s) for holding firmware image bytes. * But we need to do it piece meal, using a proper * scatter gather list (with 128kB MAX hunks). * * A practical limit here might be # of sg hunks that fit into * a single IOC request frame; 12 or 8 (see below), so: * For FC9xx: 12 x 128kB == 1.5 mB (max) * For C1030: 8 x 128kB == 1 mB (max) * We could support chaining, but things get ugly(ier:) * * Set the sge_offset to the start of the sgl (bytes). */ sgdir = 0x04000000; /* IOC will READ from sys mem */ sge_offset = sizeof(MPIHeader_t) + sizeof(FWDownloadTCSGE_t); if ((sgl = kbuf_alloc_2_sgl(fwlen, sgdir, sge_offset, &numfrags, &buflist, &sgl_dma, iocp)) == NULL) return -ENOMEM; /* * We should only need SGL with 2 simple_32bit entries (up to 256 kB) * for FC9xx f/w image, but calculate max number of sge hunks * we can fit into a request frame, and limit ourselves to that. * (currently no chain support) * maxfrags = (Request Size - FWdownload Size ) / Size of 32 bit SGE * Request maxfrags * 128 12 * 96 8 * 64 4 */ maxfrags = (iocp->req_sz - sizeof(MPIHeader_t) - sizeof(FWDownloadTCSGE_t)) / iocp->SGE_size; if (numfrags > maxfrags) { ret = -EMLINK; goto fwdl_out; } dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: sgl buffer = %p, sgfrags = %d\n", iocp->name, sgl, numfrags)); /* * Parse SG list, copying sgl itself, * plus f/w image hunks from user space as we go... */ ret = -EFAULT; sgIn = sgl; bl = buflist; for (i=0; i < numfrags; i++) { /* Get the SGE type: 0 - TCSGE, 3 - Chain, 1 - Simple SGE * Skip everything but Simple. If simple, copy from * user space into kernel space. * Note: we should not have anything but Simple as * Chain SGE are illegal. */ nib = (sgIn->FlagsLength & 0x30000000) >> 28; if (nib == 0 || nib == 3) { ; } else if (sgIn->Address) { iocp->add_sge(sgOut, sgIn->FlagsLength, sgIn->Address); n++; if (copy_from_user(bl->kptr, ufwbuf+fw_bytes_copied, bl->len)) { printk(MYIOC_s_ERR_FMT "%s@%d::_ioctl_fwdl - " "Unable to copy f/w buffer hunk#%d @ %p\n", iocp->name, __FILE__, __LINE__, n, ufwbuf); goto fwdl_out; } fw_bytes_copied += bl->len; } sgIn++; bl++; sgOut += iocp->SGE_size; } DBG_DUMP_FW_DOWNLOAD(iocp, (u32 *)mf, numfrags); /* * Finally, perform firmware download. */ ReplyMsg = NULL; SET_MGMT_MSG_CONTEXT(iocp->ioctl_cmds.msg_context, dlmsg->MsgContext); INITIALIZE_MGMT_STATUS(iocp->ioctl_cmds.status) mpt_put_msg_frame(mptctl_id, iocp, mf); /* Now wait for the command to complete */ retry_wait: timeleft = wait_for_completion_timeout(&iocp->ioctl_cmds.done, HZ*60); if (!(iocp->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) { ret = -ETIME; printk(MYIOC_s_WARN_FMT "%s: failed\n", iocp->name, __func__); if (iocp->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) { mpt_free_msg_frame(iocp, mf); goto fwdl_out; } if (!timeleft) { printk(MYIOC_s_WARN_FMT "FW download timeout, doorbell=0x%08x\n", iocp->name, mpt_GetIocState(iocp, 0)); mptctl_timeout_expired(iocp, mf); } else goto retry_wait; goto fwdl_out; } if (!(iocp->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID)) { printk(MYIOC_s_WARN_FMT "%s: failed\n", iocp->name, __func__); mpt_free_msg_frame(iocp, mf); ret = -ENODATA; goto fwdl_out; } if (sgl) kfree_sgl(sgl, sgl_dma, buflist, iocp); ReplyMsg = (pFWDownloadReply_t)iocp->ioctl_cmds.reply; iocstat = le16_to_cpu(ReplyMsg->IOCStatus) & MPI_IOCSTATUS_MASK; if (iocstat == MPI_IOCSTATUS_SUCCESS) { printk(MYIOC_s_INFO_FMT "F/W update successful!\n", iocp->name); return 0; } else if (iocstat == MPI_IOCSTATUS_INVALID_FUNCTION) { printk(MYIOC_s_WARN_FMT "Hmmm... F/W download not supported!?!\n", iocp->name); printk(MYIOC_s_WARN_FMT "(time to go bang on somebodies door)\n", iocp->name); return -EBADRQC; } else if (iocstat == MPI_IOCSTATUS_BUSY) { printk(MYIOC_s_WARN_FMT "IOC_BUSY!\n", iocp->name); printk(MYIOC_s_WARN_FMT "(try again later?)\n", iocp->name); return -EBUSY; } else { printk(MYIOC_s_WARN_FMT "ioctl_fwdl() returned [bad] status = %04xh\n", iocp->name, iocstat); printk(MYIOC_s_WARN_FMT "(bad VooDoo)\n", iocp->name); return -ENOMSG; } return 0; fwdl_out: CLEAR_MGMT_STATUS(iocp->ioctl_cmds.status); SET_MGMT_MSG_CONTEXT(iocp->ioctl_cmds.msg_context, 0); kfree_sgl(sgl, sgl_dma, buflist, iocp); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_gettargetinfo (unsigned long arg) { struct mpt_ioctl_targetinfo __user *uarg = (void __user *) arg; struct mpt_ioctl_targetinfo karg; MPT_ADAPTER *ioc; VirtDevice *vdevice; char *pmem; int *pdata; int iocnum; int numDevices = 0; int lun; int maxWordsLeft; int numBytes; u8 port; struct scsi_device *sdev; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_targetinfo))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_gettargetinfo - " "Unable to read in mpt_ioctl_targetinfo struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_gettargetinfo() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_gettargetinfo called.\n", ioc->name)); /* Get the port number and set the maximum number of bytes * in the returned structure. * Ignore the port setting. */ numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header); maxWordsLeft = numBytes/sizeof(int); port = karg.hdr.port; if (maxWordsLeft <= 0) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo() - no memory available!\n", ioc->name, __FILE__, __LINE__); return -ENOMEM; } /* Fill in the data and return the structure to the calling * program */ /* struct mpt_ioctl_targetinfo does not contain sufficient space * for the target structures so when the IOCTL is called, there is * not sufficient stack space for the structure. Allocate memory, * populate the memory, copy back to the user, then free memory. * targetInfo format: * bits 31-24: reserved * 23-16: LUN * 15- 8: Bus Number * 7- 0: Target ID */ pmem = kzalloc(numBytes, GFP_KERNEL); if (!pmem) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo() - no memory available!\n", ioc->name, __FILE__, __LINE__); return -ENOMEM; } pdata = (int *) pmem; /* Get number of devices */ if (ioc->sh){ shost_for_each_device(sdev, ioc->sh) { if (!maxWordsLeft) continue; vdevice = sdev->hostdata; if (vdevice == NULL || vdevice->vtarget == NULL) continue; if (vdevice->vtarget->tflags & MPT_TARGET_FLAGS_RAID_COMPONENT) continue; lun = (vdevice->vtarget->raidVolume) ? 0x80 : vdevice->lun; *pdata = (((u8)lun << 16) + (vdevice->vtarget->channel << 8) + (vdevice->vtarget->id )); pdata++; numDevices++; --maxWordsLeft; } } karg.numDevices = numDevices; /* Copy part of the data from kernel memory to user memory */ if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_targetinfo))) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo - " "Unable to write out mpt_ioctl_targetinfo struct @ %p\n", ioc->name, __FILE__, __LINE__, uarg); kfree(pmem); return -EFAULT; } /* Copy the remaining data from kernel memory to user memory */ if (copy_to_user(uarg->targetInfo, pmem, numBytes)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo - " "Unable to write out mpt_ioctl_targetinfo struct @ %p\n", ioc->name, __FILE__, __LINE__, pdata); kfree(pmem); return -EFAULT; } kfree(pmem); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_hp_hostinfo(unsigned long arg, unsigned int data_size) { hp_host_info_t __user *uarg = (void __user *) arg; MPT_ADAPTER *ioc; struct pci_dev *pdev; char *pbuf=NULL; dma_addr_t buf_dma; hp_host_info_t karg; CONFIGPARMS cfg; ConfigPageHeader_t hdr; int iocnum; int rc, cim_rev; ToolboxIstwiReadWriteRequest_t *IstwiRWRequest; MPT_FRAME_HDR *mf = NULL; unsigned long timeleft; int retval; u32 msgcontext; /* Reset long to int. Should affect IA64 and SPARC only */ if (data_size == sizeof(hp_host_info_t)) cim_rev = 1; else if (data_size == sizeof(hp_host_info_rev0_t)) cim_rev = 0; /* obsolete */ else return -EFAULT; if (copy_from_user(&karg, uarg, sizeof(hp_host_info_t))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_hp_host_info - " "Unable to read in hp_host_info struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_hp_hostinfo() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT ": mptctl_hp_hostinfo called.\n", ioc->name)); /* Fill in the data and return the structure to the calling * program */ pdev = (struct pci_dev *) ioc->pcidev; karg.vendor = pdev->vendor; karg.device = pdev->device; karg.subsystem_id = pdev->subsystem_device; karg.subsystem_vendor = pdev->subsystem_vendor; karg.devfn = pdev->devfn; karg.bus = pdev->bus->number; /* Save the SCSI host no. if * SCSI driver loaded */ if (ioc->sh != NULL) karg.host_no = ioc->sh->host_no; else karg.host_no = -1; /* Reformat the fw_version into a string */ snprintf(karg.fw_version, sizeof(karg.fw_version), "%.2hhu.%.2hhu.%.2hhu.%.2hhu", ioc->facts.FWVersion.Struct.Major, ioc->facts.FWVersion.Struct.Minor, ioc->facts.FWVersion.Struct.Unit, ioc->facts.FWVersion.Struct.Dev); /* Issue a config request to get the device serial number */ hdr.PageVersion = 0; hdr.PageLength = 0; hdr.PageNumber = 0; hdr.PageType = MPI_CONFIG_PAGETYPE_MANUFACTURING; cfg.cfghdr.hdr = &hdr; cfg.physAddr = -1; cfg.pageAddr = 0; cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER; cfg.dir = 0; /* read */ cfg.timeout = 10; strncpy(karg.serial_number, " ", 24); if (mpt_config(ioc, &cfg) == 0) { if (cfg.cfghdr.hdr->PageLength > 0) { /* Issue the second config page request */ cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT; pbuf = pci_alloc_consistent(ioc->pcidev, hdr.PageLength * 4, &buf_dma); if (pbuf) { cfg.physAddr = buf_dma; if (mpt_config(ioc, &cfg) == 0) { ManufacturingPage0_t *pdata = (ManufacturingPage0_t *) pbuf; if (strlen(pdata->BoardTracerNumber) > 1) { strlcpy(karg.serial_number, pdata->BoardTracerNumber, 24); } } pci_free_consistent(ioc->pcidev, hdr.PageLength * 4, pbuf, buf_dma); pbuf = NULL; } } } rc = mpt_GetIocState(ioc, 1); switch (rc) { case MPI_IOC_STATE_OPERATIONAL: karg.ioc_status = HP_STATUS_OK; break; case MPI_IOC_STATE_FAULT: karg.ioc_status = HP_STATUS_FAILED; break; case MPI_IOC_STATE_RESET: case MPI_IOC_STATE_READY: default: karg.ioc_status = HP_STATUS_OTHER; break; } karg.base_io_addr = pci_resource_start(pdev, 0); if ((ioc->bus_type == SAS) || (ioc->bus_type == FC)) karg.bus_phys_width = HP_BUS_WIDTH_UNK; else karg.bus_phys_width = HP_BUS_WIDTH_16; karg.hard_resets = 0; karg.soft_resets = 0; karg.timeouts = 0; if (ioc->sh != NULL) { MPT_SCSI_HOST *hd = shost_priv(ioc->sh); if (hd && (cim_rev == 1)) { karg.hard_resets = ioc->hard_resets; karg.soft_resets = ioc->soft_resets; karg.timeouts = ioc->timeouts; } } /* * Gather ISTWI(Industry Standard Two Wire Interface) Data */ if ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL) { dfailprintk(ioc, printk(MYIOC_s_WARN_FMT "%s, no msg frames!!\n", ioc->name, __func__)); goto out; } IstwiRWRequest = (ToolboxIstwiReadWriteRequest_t *)mf; msgcontext = IstwiRWRequest->MsgContext; memset(IstwiRWRequest,0,sizeof(ToolboxIstwiReadWriteRequest_t)); IstwiRWRequest->MsgContext = msgcontext; IstwiRWRequest->Function = MPI_FUNCTION_TOOLBOX; IstwiRWRequest->Tool = MPI_TOOLBOX_ISTWI_READ_WRITE_TOOL; IstwiRWRequest->Flags = MPI_TB_ISTWI_FLAGS_READ; IstwiRWRequest->NumAddressBytes = 0x01; IstwiRWRequest->DataLength = cpu_to_le16(0x04); if (pdev->devfn & 1) IstwiRWRequest->DeviceAddr = 0xB2; else IstwiRWRequest->DeviceAddr = 0xB0; pbuf = pci_alloc_consistent(ioc->pcidev, 4, &buf_dma); if (!pbuf) goto out; ioc->add_sge((char *)&IstwiRWRequest->SGL, (MPT_SGE_FLAGS_SSIMPLE_READ|4), buf_dma); retval = 0; SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, IstwiRWRequest->MsgContext); INITIALIZE_MGMT_STATUS(ioc->ioctl_cmds.status) mpt_put_msg_frame(mptctl_id, ioc, mf); retry_wait: timeleft = wait_for_completion_timeout(&ioc->ioctl_cmds.done, HZ*MPT_IOCTL_DEFAULT_TIMEOUT); if (!(ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) { retval = -ETIME; printk(MYIOC_s_WARN_FMT "%s: failed\n", ioc->name, __func__); if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) { mpt_free_msg_frame(ioc, mf); goto out; } if (!timeleft) { printk(MYIOC_s_WARN_FMT "HOST INFO command timeout, doorbell=0x%08x\n", ioc->name, mpt_GetIocState(ioc, 0)); mptctl_timeout_expired(ioc, mf); } else goto retry_wait; goto out; } /* *ISTWI Data Definition * pbuf[0] = FW_VERSION = 0x4 * pbuf[1] = Bay Count = 6 or 4 or 2, depending on * the config, you should be seeing one out of these three values * pbuf[2] = Drive Installed Map = bit pattern depend on which * bays have drives in them * pbuf[3] = Checksum (0x100 = (byte0 + byte2 + byte3) */ if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID) karg.rsvd = *(u32 *)pbuf; out: CLEAR_MGMT_STATUS(ioc->ioctl_cmds.status) SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, 0); if (pbuf) pci_free_consistent(ioc->pcidev, 4, pbuf, buf_dma); /* Copy the data from kernel memory to user memory */ if (copy_to_user((char __user *)arg, &karg, sizeof(hp_host_info_t))) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_hpgethostinfo - " "Unable to write out hp_host_info @ %p\n", ioc->name, __FILE__, __LINE__, uarg); return -EFAULT; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_getiocinfo (unsigned long arg, unsigned int data_size) { struct mpt_ioctl_iocinfo __user *uarg = (void __user *) arg; struct mpt_ioctl_iocinfo *karg; MPT_ADAPTER *ioc; struct pci_dev *pdev; int iocnum; unsigned int port; int cim_rev; struct scsi_device *sdev; VirtDevice *vdevice; /* Add of PCI INFO results in unaligned access for * IA64 and Sparc. Reset long to int. Return no PCI * data for obsolete format. */ if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev0)) cim_rev = 0; else if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev1)) cim_rev = 1; else if (data_size == sizeof(struct mpt_ioctl_iocinfo)) cim_rev = 2; else if (data_size == (sizeof(struct mpt_ioctl_iocinfo_rev0)+12)) cim_rev = 0; /* obsolete */ else return -EFAULT; karg = memdup_user(uarg, data_size); if (IS_ERR(karg)) { printk(KERN_ERR MYNAM "%s@%d::mpt_ioctl_iocinfo() - memdup_user returned error [%ld]\n", __FILE__, __LINE__, PTR_ERR(karg)); return PTR_ERR(karg); } if (((iocnum = mpt_verify_adapter(karg->hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_getiocinfo() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); kfree(karg); return -ENODEV; } /* Verify the data transfer size is correct. */ if (karg->hdr.maxDataSize != data_size) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_getiocinfo - " "Structure size mismatch. Command not completed.\n", ioc->name, __FILE__, __LINE__); kfree(karg); return -EFAULT; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_getiocinfo called.\n", ioc->name)); /* Fill in the data and return the structure to the calling * program */ if (ioc->bus_type == SAS) karg->adapterType = MPT_IOCTL_INTERFACE_SAS; else if (ioc->bus_type == FC) karg->adapterType = MPT_IOCTL_INTERFACE_FC; else karg->adapterType = MPT_IOCTL_INTERFACE_SCSI; if (karg->hdr.port > 1) { kfree(karg); return -EINVAL; } port = karg->hdr.port; karg->port = port; pdev = (struct pci_dev *) ioc->pcidev; karg->pciId = pdev->device; karg->hwRev = pdev->revision; karg->subSystemDevice = pdev->subsystem_device; karg->subSystemVendor = pdev->subsystem_vendor; if (cim_rev == 1) { /* Get the PCI bus, device, and function numbers for the IOC */ karg->pciInfo.u.bits.busNumber = pdev->bus->number; karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn ); karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn ); } else if (cim_rev == 2) { /* Get the PCI bus, device, function and segment ID numbers for the IOC */ karg->pciInfo.u.bits.busNumber = pdev->bus->number; karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn ); karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn ); karg->pciInfo.segmentID = pci_domain_nr(pdev->bus); } /* Get number of devices */ karg->numDevices = 0; if (ioc->sh) { shost_for_each_device(sdev, ioc->sh) { vdevice = sdev->hostdata; if (vdevice == NULL || vdevice->vtarget == NULL) continue; if (vdevice->vtarget->tflags & MPT_TARGET_FLAGS_RAID_COMPONENT) continue; karg->numDevices++; } } /* Set the BIOS and FW Version */ karg->FWVersion = ioc->facts.FWVersion.Word; karg->BIOSVersion = ioc->biosVersion; /* Set the Version Strings. */ strncpy (karg->driverVersion, MPT_LINUX_PACKAGE_NAME, MPT_IOCTL_VERSION_LENGTH); karg->driverVersion[MPT_IOCTL_VERSION_LENGTH-1]='\0'; karg->busChangeEvent = 0; karg->hostId = ioc->pfacts[port].PortSCSIID; karg->rsvd[0] = karg->rsvd[1] = 0; /* Copy the data from kernel memory to user memory */ if (copy_to_user((char __user *)arg, karg, data_size)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_getiocinfo - " "Unable to write out mpt_ioctl_iocinfo struct @ %p\n", ioc->name, __FILE__, __LINE__, uarg); kfree(karg); return -EFAULT; } kfree(karg); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_eventenable (unsigned long arg) { struct mpt_ioctl_eventenable __user *uarg = (void __user *) arg; struct mpt_ioctl_eventenable karg; MPT_ADAPTER *ioc; int iocnum; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_eventenable - " "Unable to read in mpt_ioctl_eventenable struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_eventenable() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventenable called.\n", ioc->name)); if (ioc->events == NULL) { /* Have not yet allocated memory - do so now. */ int sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS); ioc->events = kzalloc(sz, GFP_KERNEL); if (!ioc->events) { printk(MYIOC_s_ERR_FMT ": ERROR - Insufficient memory to add adapter!\n", ioc->name); return -ENOMEM; } ioc->alloc_total += sz; ioc->eventContext = 0; } /* Update the IOC event logging flag. */ ioc->eventTypes = karg.eventTypes; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_do_mpt_command (struct mpt_ioctl_command karg, void __user *mfPtr) { MPT_ADAPTER *ioc; MPT_FRAME_HDR *mf = NULL; MPIHeader_t *hdr; char *psge; struct buflist bufIn; /* data In buffer */ struct buflist bufOut; /* data Out buffer */ dma_addr_t dma_addr_in; dma_addr_t dma_addr_out; int sgSize = 0; /* Num SG elements */ int iocnum, flagsLength; int sz, rc = 0; int msgContext; u16 req_idx; ulong timeout; unsigned long timeleft; struct scsi_device *sdev; unsigned long flags; u8 function; /* bufIn and bufOut are used for user to kernel space transfers */ bufIn.kptr = bufOut.kptr = NULL; bufIn.len = bufOut.len = 0; if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_do_mpt_command() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } spin_lock_irqsave(&ioc->taskmgmt_lock, flags); if (ioc->ioc_reset_in_progress) { spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags); printk(KERN_ERR MYNAM "%s@%d::mptctl_do_mpt_command - " "Busy with diagnostic reset\n", __FILE__, __LINE__); return -EBUSY; } spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags); /* Basic sanity checks to prevent underflows or integer overflows */ if (karg.maxReplyBytes < 0 || karg.dataInSize < 0 || karg.dataOutSize < 0 || karg.dataSgeOffset < 0 || karg.maxSenseBytes < 0 || karg.dataSgeOffset > ioc->req_sz / 4) return -EINVAL; /* Verify that the final request frame will not be too large. */ sz = karg.dataSgeOffset * 4; if (karg.dataInSize > 0) sz += ioc->SGE_size; if (karg.dataOutSize > 0) sz += ioc->SGE_size; if (sz > ioc->req_sz) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Request frame too large (%d) maximum (%d)\n", ioc->name, __FILE__, __LINE__, sz, ioc->req_sz); return -EFAULT; } /* Get a free request frame and save the message context. */ if ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL) return -EAGAIN; hdr = (MPIHeader_t *) mf; msgContext = le32_to_cpu(hdr->MsgContext); req_idx = le16_to_cpu(mf->u.frame.hwhdr.msgctxu.fld.req_idx); /* Copy the request frame * Reset the saved message context. * Request frame in user space */ if (copy_from_user(mf, mfPtr, karg.dataSgeOffset * 4)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Unable to read MF from mpt_ioctl_command struct @ %p\n", ioc->name, __FILE__, __LINE__, mfPtr); function = -1; rc = -EFAULT; goto done_free_mem; } hdr->MsgContext = cpu_to_le32(msgContext); function = hdr->Function; /* Verify that this request is allowed. */ dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "sending mpi function (0x%02X), req=%p\n", ioc->name, hdr->Function, mf)); switch (function) { case MPI_FUNCTION_IOC_FACTS: case MPI_FUNCTION_PORT_FACTS: karg.dataOutSize = karg.dataInSize = 0; break; case MPI_FUNCTION_CONFIG: { Config_t *config_frame; config_frame = (Config_t *)mf; dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "\ttype=0x%02x ext_type=0x%02x " "number=0x%02x action=0x%02x\n", ioc->name, config_frame->Header.PageType, config_frame->ExtPageType, config_frame->Header.PageNumber, config_frame->Action)); break; } case MPI_FUNCTION_FC_COMMON_TRANSPORT_SEND: case MPI_FUNCTION_FC_EX_LINK_SRVC_SEND: case MPI_FUNCTION_FW_UPLOAD: case MPI_FUNCTION_SCSI_ENCLOSURE_PROCESSOR: case MPI_FUNCTION_FW_DOWNLOAD: case MPI_FUNCTION_FC_PRIMITIVE_SEND: case MPI_FUNCTION_TOOLBOX: case MPI_FUNCTION_SAS_IO_UNIT_CONTROL: break; case MPI_FUNCTION_SCSI_IO_REQUEST: if (ioc->sh) { SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf; int qtag = MPI_SCSIIO_CONTROL_UNTAGGED; int scsidir = 0; int dataSize; u32 id; id = (ioc->devices_per_bus == 0) ? 256 : ioc->devices_per_bus; if (pScsiReq->TargetID > id) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Target ID out of bounds. \n", ioc->name, __FILE__, __LINE__); rc = -ENODEV; goto done_free_mem; } if (pScsiReq->Bus >= ioc->number_of_buses) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Target Bus out of bounds. \n", ioc->name, __FILE__, __LINE__); rc = -ENODEV; goto done_free_mem; } pScsiReq->MsgFlags &= ~MPI_SCSIIO_MSGFLGS_SENSE_WIDTH; pScsiReq->MsgFlags |= mpt_msg_flags(ioc); /* verify that app has not requested * more sense data than driver * can provide, if so, reset this parameter * set the sense buffer pointer low address * update the control field to specify Q type */ if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE) pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE; else pScsiReq->SenseBufferLength = karg.maxSenseBytes; pScsiReq->SenseBufferLowAddr = cpu_to_le32(ioc->sense_buf_low_dma + (req_idx * MPT_SENSE_BUFFER_ALLOC)); shost_for_each_device(sdev, ioc->sh) { struct scsi_target *starget = scsi_target(sdev); VirtTarget *vtarget = starget->hostdata; if (vtarget == NULL) continue; if ((pScsiReq->TargetID == vtarget->id) && (pScsiReq->Bus == vtarget->channel) && (vtarget->tflags & MPT_TARGET_FLAGS_Q_YES)) qtag = MPI_SCSIIO_CONTROL_SIMPLEQ; } /* Have the IOCTL driver set the direction based * on the dataOutSize (ordering issue with Sparc). */ if (karg.dataOutSize > 0) { scsidir = MPI_SCSIIO_CONTROL_WRITE; dataSize = karg.dataOutSize; } else { scsidir = MPI_SCSIIO_CONTROL_READ; dataSize = karg.dataInSize; } pScsiReq->Control = cpu_to_le32(scsidir | qtag); pScsiReq->DataLength = cpu_to_le32(dataSize); } else { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "SCSI driver is not loaded. \n", ioc->name, __FILE__, __LINE__); rc = -EFAULT; goto done_free_mem; } break; case MPI_FUNCTION_SMP_PASSTHROUGH: /* Check mf->PassthruFlags to determine if * transfer is ImmediateMode or not. * Immediate mode returns data in the ReplyFrame. * Else, we are sending request and response data * in two SGLs at the end of the mf. */ break; case MPI_FUNCTION_SATA_PASSTHROUGH: if (!ioc->sh) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "SCSI driver is not loaded. \n", ioc->name, __FILE__, __LINE__); rc = -EFAULT; goto done_free_mem; } break; case MPI_FUNCTION_RAID_ACTION: /* Just add a SGE */ break; case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH: if (ioc->sh) { SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf; int qtag = MPI_SCSIIO_CONTROL_SIMPLEQ; int scsidir = MPI_SCSIIO_CONTROL_READ; int dataSize; pScsiReq->MsgFlags &= ~MPI_SCSIIO_MSGFLGS_SENSE_WIDTH; pScsiReq->MsgFlags |= mpt_msg_flags(ioc); /* verify that app has not requested * more sense data than driver * can provide, if so, reset this parameter * set the sense buffer pointer low address * update the control field to specify Q type */ if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE) pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE; else pScsiReq->SenseBufferLength = karg.maxSenseBytes; pScsiReq->SenseBufferLowAddr = cpu_to_le32(ioc->sense_buf_low_dma + (req_idx * MPT_SENSE_BUFFER_ALLOC)); /* All commands to physical devices are tagged */ /* Have the IOCTL driver set the direction based * on the dataOutSize (ordering issue with Sparc). */ if (karg.dataOutSize > 0) { scsidir = MPI_SCSIIO_CONTROL_WRITE; dataSize = karg.dataOutSize; } else { scsidir = MPI_SCSIIO_CONTROL_READ; dataSize = karg.dataInSize; } pScsiReq->Control = cpu_to_le32(scsidir | qtag); pScsiReq->DataLength = cpu_to_le32(dataSize); } else { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "SCSI driver is not loaded. \n", ioc->name, __FILE__, __LINE__); rc = -EFAULT; goto done_free_mem; } break; case MPI_FUNCTION_SCSI_TASK_MGMT: { SCSITaskMgmt_t *pScsiTm; pScsiTm = (SCSITaskMgmt_t *)mf; dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "\tTaskType=0x%x MsgFlags=0x%x " "TaskMsgContext=0x%x id=%d channel=%d\n", ioc->name, pScsiTm->TaskType, le32_to_cpu (pScsiTm->TaskMsgContext), pScsiTm->MsgFlags, pScsiTm->TargetID, pScsiTm->Bus)); break; } case MPI_FUNCTION_IOC_INIT: { IOCInit_t *pInit = (IOCInit_t *) mf; u32 high_addr, sense_high; /* Verify that all entries in the IOC INIT match * existing setup (and in LE format). */ if (sizeof(dma_addr_t) == sizeof(u64)) { high_addr = cpu_to_le32((u32)((u64)ioc->req_frames_dma >> 32)); sense_high= cpu_to_le32((u32)((u64)ioc->sense_buf_pool_dma >> 32)); } else { high_addr = 0; sense_high= 0; } if ((pInit->Flags != 0) || (pInit->MaxDevices != ioc->facts.MaxDevices) || (pInit->MaxBuses != ioc->facts.MaxBuses) || (pInit->ReplyFrameSize != cpu_to_le16(ioc->reply_sz)) || (pInit->HostMfaHighAddr != high_addr) || (pInit->SenseBufferHighAddr != sense_high)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "IOC_INIT issued with 1 or more incorrect parameters. Rejected.\n", ioc->name, __FILE__, __LINE__); rc = -EFAULT; goto done_free_mem; } } break; default: /* * MPI_FUNCTION_PORT_ENABLE * MPI_FUNCTION_TARGET_CMD_BUFFER_POST * MPI_FUNCTION_TARGET_ASSIST * MPI_FUNCTION_TARGET_STATUS_SEND * MPI_FUNCTION_TARGET_MODE_ABORT * MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET * MPI_FUNCTION_IO_UNIT_RESET * MPI_FUNCTION_HANDSHAKE * MPI_FUNCTION_REPLY_FRAME_REMOVAL * MPI_FUNCTION_EVENT_NOTIFICATION * (driver handles event notification) * MPI_FUNCTION_EVENT_ACK */ /* What to do with these??? CHECK ME!!! MPI_FUNCTION_FC_LINK_SRVC_BUF_POST MPI_FUNCTION_FC_LINK_SRVC_RSP MPI_FUNCTION_FC_ABORT MPI_FUNCTION_LAN_SEND MPI_FUNCTION_LAN_RECEIVE MPI_FUNCTION_LAN_RESET */ printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Illegal request (function 0x%x) \n", ioc->name, __FILE__, __LINE__, hdr->Function); rc = -EFAULT; goto done_free_mem; } /* Add the SGL ( at most one data in SGE and one data out SGE ) * In the case of two SGE's - the data out (write) will always * preceede the data in (read) SGE. psgList is used to free the * allocated memory. */ psge = (char *) (((int *) mf) + karg.dataSgeOffset); flagsLength = 0; if (karg.dataOutSize > 0) sgSize ++; if (karg.dataInSize > 0) sgSize ++; if (sgSize > 0) { /* Set up the dataOut memory allocation */ if (karg.dataOutSize > 0) { if (karg.dataInSize > 0) { flagsLength = ( MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER | MPI_SGE_FLAGS_DIRECTION) << MPI_SGE_FLAGS_SHIFT; } else { flagsLength = MPT_SGE_FLAGS_SSIMPLE_WRITE; } flagsLength |= karg.dataOutSize; bufOut.len = karg.dataOutSize; bufOut.kptr = pci_alloc_consistent( ioc->pcidev, bufOut.len, &dma_addr_out); if (bufOut.kptr == NULL) { rc = -ENOMEM; goto done_free_mem; } else { /* Set up this SGE. * Copy to MF and to sglbuf */ ioc->add_sge(psge, flagsLength, dma_addr_out); psge += ioc->SGE_size; /* Copy user data to kernel space. */ if (copy_from_user(bufOut.kptr, karg.dataOutBufPtr, bufOut.len)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - Unable " "to read user data " "struct @ %p\n", ioc->name, __FILE__, __LINE__,karg.dataOutBufPtr); rc = -EFAULT; goto done_free_mem; } } } if (karg.dataInSize > 0) { flagsLength = MPT_SGE_FLAGS_SSIMPLE_READ; flagsLength |= karg.dataInSize; bufIn.len = karg.dataInSize; bufIn.kptr = pci_alloc_consistent(ioc->pcidev, bufIn.len, &dma_addr_in); if (bufIn.kptr == NULL) { rc = -ENOMEM; goto done_free_mem; } else { /* Set up this SGE * Copy to MF and to sglbuf */ ioc->add_sge(psge, flagsLength, dma_addr_in); } } } else { /* Add a NULL SGE */ ioc->add_sge(psge, flagsLength, (dma_addr_t) -1); } SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, hdr->MsgContext); INITIALIZE_MGMT_STATUS(ioc->ioctl_cmds.status) if (hdr->Function == MPI_FUNCTION_SCSI_TASK_MGMT) { mutex_lock(&ioc->taskmgmt_cmds.mutex); if (mpt_set_taskmgmt_in_progress_flag(ioc) != 0) { mutex_unlock(&ioc->taskmgmt_cmds.mutex); goto done_free_mem; } DBG_DUMP_TM_REQUEST_FRAME(ioc, (u32 *)mf); if ((ioc->facts.IOCCapabilities & MPI_IOCFACTS_CAPABILITY_HIGH_PRI_Q) && (ioc->facts.MsgVersion >= MPI_VERSION_01_05)) mpt_put_msg_frame_hi_pri(mptctl_id, ioc, mf); else { rc =mpt_send_handshake_request(mptctl_id, ioc, sizeof(SCSITaskMgmt_t), (u32*)mf, CAN_SLEEP); if (rc != 0) { dfailprintk(ioc, printk(MYIOC_s_ERR_FMT "send_handshake FAILED! (ioc %p, mf %p)\n", ioc->name, ioc, mf)); mpt_clear_taskmgmt_in_progress_flag(ioc); rc = -ENODATA; mutex_unlock(&ioc->taskmgmt_cmds.mutex); goto done_free_mem; } } } else mpt_put_msg_frame(mptctl_id, ioc, mf); /* Now wait for the command to complete */ timeout = (karg.timeout > 0) ? karg.timeout : MPT_IOCTL_DEFAULT_TIMEOUT; retry_wait: timeleft = wait_for_completion_timeout(&ioc->ioctl_cmds.done, HZ*timeout); if (!(ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) { rc = -ETIME; dfailprintk(ioc, printk(MYIOC_s_ERR_FMT "%s: TIMED OUT!\n", ioc->name, __func__)); if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) { if (function == MPI_FUNCTION_SCSI_TASK_MGMT) mutex_unlock(&ioc->taskmgmt_cmds.mutex); goto done_free_mem; } if (!timeleft) { printk(MYIOC_s_WARN_FMT "mpt cmd timeout, doorbell=0x%08x" " function=0x%x\n", ioc->name, mpt_GetIocState(ioc, 0), function); if (function == MPI_FUNCTION_SCSI_TASK_MGMT) mutex_unlock(&ioc->taskmgmt_cmds.mutex); mptctl_timeout_expired(ioc, mf); mf = NULL; } else goto retry_wait; goto done_free_mem; } if (function == MPI_FUNCTION_SCSI_TASK_MGMT) mutex_unlock(&ioc->taskmgmt_cmds.mutex); mf = NULL; /* If a valid reply frame, copy to the user. * Offset 2: reply length in U32's */ if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID) { if (karg.maxReplyBytes < ioc->reply_sz) { sz = min(karg.maxReplyBytes, 4*ioc->ioctl_cmds.reply[2]); } else { sz = min(ioc->reply_sz, 4*ioc->ioctl_cmds.reply[2]); } if (sz > 0) { if (copy_to_user(karg.replyFrameBufPtr, ioc->ioctl_cmds.reply, sz)){ printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Unable to write out reply frame %p\n", ioc->name, __FILE__, __LINE__, karg.replyFrameBufPtr); rc = -ENODATA; goto done_free_mem; } } } /* If valid sense data, copy to user. */ if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_SENSE_VALID) { sz = min(karg.maxSenseBytes, MPT_SENSE_BUFFER_SIZE); if (sz > 0) { if (copy_to_user(karg.senseDataPtr, ioc->ioctl_cmds.sense, sz)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Unable to write sense data to user %p\n", ioc->name, __FILE__, __LINE__, karg.senseDataPtr); rc = -ENODATA; goto done_free_mem; } } } /* If the overall status is _GOOD and data in, copy data * to user. */ if ((ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD) && (karg.dataInSize > 0) && (bufIn.kptr)) { if (copy_to_user(karg.dataInBufPtr, bufIn.kptr, karg.dataInSize)) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - " "Unable to write data to user %p\n", ioc->name, __FILE__, __LINE__, karg.dataInBufPtr); rc = -ENODATA; } } done_free_mem: CLEAR_MGMT_STATUS(ioc->ioctl_cmds.status) SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, 0); /* Free the allocated memory. */ if (bufOut.kptr != NULL) { pci_free_consistent(ioc->pcidev, bufOut.len, (void *) bufOut.kptr, dma_addr_out); } if (bufIn.kptr != NULL) { pci_free_consistent(ioc->pcidev, bufIn.len, (void *) bufIn.kptr, dma_addr_in); } /* mf is null if command issued successfully * otherwise, failure occurred after mf acquired. */ if (mf) mpt_free_msg_frame(ioc, mf); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __mptctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { mpt_ioctl_header __user *uhdr = (void __user *) arg; mpt_ioctl_header khdr; int iocnum; unsigned iocnumX; int nonblock = (file->f_flags & O_NONBLOCK); int ret; MPT_ADAPTER *iocp = NULL; if (copy_from_user(&khdr, uhdr, sizeof(khdr))) { printk(KERN_ERR MYNAM "%s::mptctl_ioctl() @%d - " "Unable to copy mpt_ioctl_header data @ %p\n", __FILE__, __LINE__, uhdr); return -EFAULT; } ret = -ENXIO; /* (-6) No such device or address */ /* Verify intended MPT adapter - set iocnum and the adapter * pointer (iocp) */ iocnumX = khdr.iocnum & 0xFF; if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) || (iocp == NULL)) return -ENODEV; if (!iocp->active) { printk(KERN_DEBUG MYNAM "%s::mptctl_ioctl() @%d - Controller disabled.\n", __FILE__, __LINE__); return -EFAULT; } /* Handle those commands that are just returning * information stored in the driver. * These commands should never time out and are unaffected * by TM and FW reloads. */ if ((cmd & ~IOCSIZE_MASK) == (MPTIOCINFO & ~IOCSIZE_MASK)) { return mptctl_getiocinfo(arg, _IOC_SIZE(cmd)); } else if (cmd == MPTTARGETINFO) { return mptctl_gettargetinfo(arg); } else if (cmd == MPTTEST) { return mptctl_readtest(arg); } else if (cmd == MPTEVENTQUERY) { return mptctl_eventquery(arg); } else if (cmd == MPTEVENTENABLE) { return mptctl_eventenable(arg); } else if (cmd == MPTEVENTREPORT) { return mptctl_eventreport(arg); } else if (cmd == MPTFWREPLACE) { return mptctl_replace_fw(arg); } /* All of these commands require an interrupt or * are unknown/illegal. */ if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) return ret; if (cmd == MPTFWDOWNLOAD) ret = mptctl_fw_download(arg); else if (cmd == MPTCOMMAND) ret = mptctl_mpt_command(arg); else if (cmd == MPTHARDRESET) ret = mptctl_do_reset(arg); else if ((cmd & ~IOCSIZE_MASK) == (HP_GETHOSTINFO & ~IOCSIZE_MASK)) ret = mptctl_hp_hostinfo(arg, _IOC_SIZE(cmd)); else if (cmd == HP_GETTARGETINFO) ret = mptctl_hp_targetinfo(arg); else ret = -EINVAL; mutex_unlock(&iocp->ioctl_cmds.mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_eventquery (unsigned long arg) { struct mpt_ioctl_eventquery __user *uarg = (void __user *) arg; struct mpt_ioctl_eventquery karg; MPT_ADAPTER *ioc; int iocnum; if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) { printk(KERN_ERR MYNAM "%s@%d::mptctl_eventquery - " "Unable to read in mpt_ioctl_eventquery struct @ %p\n", __FILE__, __LINE__, uarg); return -EFAULT; } if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) || (ioc == NULL)) { printk(KERN_DEBUG MYNAM "%s::mptctl_eventquery() @%d - ioc%d not found!\n", __FILE__, __LINE__, iocnum); return -ENODEV; } dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventquery called.\n", ioc->name)); karg.eventEntries = MPTCTL_EVENT_LOG_SIZE; karg.eventTypes = ioc->eventTypes; /* Copy the data from kernel memory to user memory */ if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) { printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventquery - " "Unable to write out mpt_ioctl_eventquery struct @ %p\n", ioc->name, __FILE__, __LINE__, uarg); return -EFAULT; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: mptctl_fw_download(unsigned long arg) { struct mpt_fw_xfer __user *ufwdl = (void __user *) arg; struct mpt_fw_xfer kfwdl; if (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) { printk(KERN_ERR MYNAM "%s@%d::_ioctl_fwdl - " "Unable to copy mpt_fw_xfer struct @ %p\n", __FILE__, __LINE__, ufwdl); return -EFAULT; } return mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362', 'CWE-369'], 'message': 'scsi: mptfusion: Fix double fetch bug in ioctl Tom Hatskevich reported that we look up "iocp" then, in the called functions we do a second copy_from_user() and look it up again. The problem that could cause is: drivers/message/fusion/mptctl.c 674 /* All of these commands require an interrupt or 675 * are unknown/illegal. 676 */ 677 if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0) ^^^^ We take this lock. 678 return ret; 679 680 if (cmd == MPTFWDOWNLOAD) 681 ret = mptctl_fw_download(arg); ^^^ Then the user memory changes and we look up "iocp" again but a different one so now we are holding the incorrect lock and have a race condition. 682 else if (cmd == MPTCOMMAND) 683 ret = mptctl_mpt_command(arg); The security impact of this bug is not as bad as it could have been because these operations are all privileged and root already has enormous destructive power. But it's still worth fixing. This patch passes the "iocp" pointer to the functions to avoid the second lookup. That deletes 100 lines of code from the driver so it's a nice clean up as well. Link: https://lore.kernel.org/r/20200114123414.GA7957@kadam Reported-by: Tom Hatskevich <tom2001tom.23@gmail.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void hci_auth_complete_evt(struct hci_dev *hdev, struct sk_buff *skb) { struct hci_ev_auth_complete *ev = (void *) skb->data; struct hci_conn *conn; BT_DBG("%s status 0x%2.2x", hdev->name, ev->status); hci_dev_lock(hdev); conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(ev->handle)); if (!conn) goto unlock; if (!ev->status) { clear_bit(HCI_CONN_AUTH_FAILURE, &conn->flags); if (!hci_conn_ssp_enabled(conn) && test_bit(HCI_CONN_REAUTH_PEND, &conn->flags)) { bt_dev_info(hdev, "re-auth of legacy device is not possible."); } else { set_bit(HCI_CONN_AUTH, &conn->flags); conn->sec_level = conn->pending_sec_level; } } else { if (ev->status == HCI_ERROR_PIN_OR_KEY_MISSING) set_bit(HCI_CONN_AUTH_FAILURE, &conn->flags); mgmt_auth_failed(conn, ev->status); } clear_bit(HCI_CONN_AUTH_PEND, &conn->flags); clear_bit(HCI_CONN_REAUTH_PEND, &conn->flags); if (conn->state == BT_CONFIG) { if (!ev->status && hci_conn_ssp_enabled(conn)) { struct hci_cp_set_conn_encrypt cp; cp.handle = ev->handle; cp.encrypt = 0x01; hci_send_cmd(hdev, HCI_OP_SET_CONN_ENCRYPT, sizeof(cp), &cp); } else { conn->state = BT_CONNECTED; hci_connect_cfm(conn, ev->status); hci_conn_drop(conn); } } else { hci_auth_cfm(conn, ev->status); hci_conn_hold(conn); conn->disc_timeout = HCI_DISCONN_TIMEOUT; hci_conn_drop(conn); } if (test_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags)) { if (!ev->status) { struct hci_cp_set_conn_encrypt cp; cp.handle = ev->handle; cp.encrypt = 0x01; hci_send_cmd(hdev, HCI_OP_SET_CONN_ENCRYPT, sizeof(cp), &cp); } else { clear_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags); hci_encrypt_cfm(conn, ev->status, 0x00); } } unlock: hci_dev_unlock(hdev); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-290'], 'message': 'Bluetooth: Consolidate encryption handling in hci_encrypt_cfm This makes hci_encrypt_cfm calls hci_connect_cfm in case the connection state is BT_CONFIG so callers don't have to check the state. Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com> Signed-off-by: Marcel Holtmann <marcel@holtmann.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void hci_encrypt_change_evt(struct hci_dev *hdev, struct sk_buff *skb) { struct hci_ev_encrypt_change *ev = (void *) skb->data; struct hci_conn *conn; BT_DBG("%s status 0x%2.2x", hdev->name, ev->status); hci_dev_lock(hdev); conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(ev->handle)); if (!conn) goto unlock; if (!ev->status) { if (ev->encrypt) { /* Encryption implies authentication */ set_bit(HCI_CONN_AUTH, &conn->flags); set_bit(HCI_CONN_ENCRYPT, &conn->flags); conn->sec_level = conn->pending_sec_level; /* P-256 authentication key implies FIPS */ if (conn->key_type == HCI_LK_AUTH_COMBINATION_P256) set_bit(HCI_CONN_FIPS, &conn->flags); if ((conn->type == ACL_LINK && ev->encrypt == 0x02) || conn->type == LE_LINK) set_bit(HCI_CONN_AES_CCM, &conn->flags); } else { clear_bit(HCI_CONN_ENCRYPT, &conn->flags); clear_bit(HCI_CONN_AES_CCM, &conn->flags); } } /* We should disregard the current RPA and generate a new one * whenever the encryption procedure fails. */ if (ev->status && conn->type == LE_LINK) { hci_dev_set_flag(hdev, HCI_RPA_EXPIRED); hci_adv_instances_set_rpa_expired(hdev, true); } clear_bit(HCI_CONN_ENCRYPT_PEND, &conn->flags); if (ev->status && conn->state == BT_CONNECTED) { if (ev->status == HCI_ERROR_PIN_OR_KEY_MISSING) set_bit(HCI_CONN_AUTH_FAILURE, &conn->flags); hci_disconnect(conn, HCI_ERROR_AUTH_FAILURE); hci_conn_drop(conn); goto unlock; } /* In Secure Connections Only mode, do not allow any connections * that are not encrypted with AES-CCM using a P-256 authenticated * combination key. */ if (hci_dev_test_flag(hdev, HCI_SC_ONLY) && (!test_bit(HCI_CONN_AES_CCM, &conn->flags) || conn->key_type != HCI_LK_AUTH_COMBINATION_P256)) { hci_connect_cfm(conn, HCI_ERROR_AUTH_FAILURE); hci_conn_drop(conn); goto unlock; } /* Try reading the encryption key size for encrypted ACL links */ if (!ev->status && ev->encrypt && conn->type == ACL_LINK) { struct hci_cp_read_enc_key_size cp; struct hci_request req; /* Only send HCI_Read_Encryption_Key_Size if the * controller really supports it. If it doesn't, assume * the default size (16). */ if (!(hdev->commands[20] & 0x10)) { conn->enc_key_size = HCI_LINK_KEY_SIZE; goto notify; } hci_req_init(&req, hdev); cp.handle = cpu_to_le16(conn->handle); hci_req_add(&req, HCI_OP_READ_ENC_KEY_SIZE, sizeof(cp), &cp); if (hci_req_run_skb(&req, read_enc_key_size_complete)) { bt_dev_err(hdev, "sending read key size failed"); conn->enc_key_size = HCI_LINK_KEY_SIZE; goto notify; } goto unlock; } /* Set the default Authenticated Payload Timeout after * an LE Link is established. As per Core Spec v5.0, Vol 2, Part B * Section 3.3, the HCI command WRITE_AUTH_PAYLOAD_TIMEOUT should be * sent when the link is active and Encryption is enabled, the conn * type can be either LE or ACL and controller must support LMP Ping. * Ensure for AES-CCM encryption as well. */ if (test_bit(HCI_CONN_ENCRYPT, &conn->flags) && test_bit(HCI_CONN_AES_CCM, &conn->flags) && ((conn->type == ACL_LINK && lmp_ping_capable(hdev)) || (conn->type == LE_LINK && (hdev->le_features[0] & HCI_LE_PING)))) { struct hci_cp_write_auth_payload_to cp; cp.handle = cpu_to_le16(conn->handle); cp.timeout = cpu_to_le16(hdev->auth_payload_timeout); hci_send_cmd(conn->hdev, HCI_OP_WRITE_AUTH_PAYLOAD_TO, sizeof(cp), &cp); } notify: if (conn->state == BT_CONFIG) { if (!ev->status) conn->state = BT_CONNECTED; hci_connect_cfm(conn, ev->status); hci_conn_drop(conn); } else hci_encrypt_cfm(conn, ev->status, ev->encrypt); unlock: hci_dev_unlock(hdev); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-290'], 'message': 'Bluetooth: Consolidate encryption handling in hci_encrypt_cfm This makes hci_encrypt_cfm calls hci_connect_cfm in case the connection state is BT_CONFIG so callers don't have to check the state. Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com> Signed-off-by: Marcel Holtmann <marcel@holtmann.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: xfs_agf_verify( struct xfs_buf *bp) { struct xfs_mount *mp = bp->b_mount; struct xfs_agf *agf = XFS_BUF_TO_AGF(bp); if (xfs_sb_version_hascrc(&mp->m_sb)) { if (!uuid_equal(&agf->agf_uuid, &mp->m_sb.sb_meta_uuid)) return __this_address; if (!xfs_log_check_lsn(mp, be64_to_cpu(XFS_BUF_TO_AGF(bp)->agf_lsn))) return __this_address; } if (!xfs_verify_magic(bp, agf->agf_magicnum)) return __this_address; if (!(XFS_AGF_GOOD_VERSION(be32_to_cpu(agf->agf_versionnum)) && be32_to_cpu(agf->agf_freeblks) <= be32_to_cpu(agf->agf_length) && be32_to_cpu(agf->agf_flfirst) < xfs_agfl_size(mp) && be32_to_cpu(agf->agf_fllast) < xfs_agfl_size(mp) && be32_to_cpu(agf->agf_flcount) <= xfs_agfl_size(mp))) return __this_address; if (be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) < 1 || be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) < 1 || be32_to_cpu(agf->agf_levels[XFS_BTNUM_BNO]) > XFS_BTREE_MAXLEVELS || be32_to_cpu(agf->agf_levels[XFS_BTNUM_CNT]) > XFS_BTREE_MAXLEVELS) return __this_address; if (xfs_sb_version_hasrmapbt(&mp->m_sb) && (be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAP]) < 1 || be32_to_cpu(agf->agf_levels[XFS_BTNUM_RMAP]) > XFS_BTREE_MAXLEVELS)) return __this_address; /* * during growfs operations, the perag is not fully initialised, * so we can't use it for any useful checking. growfs ensures we can't * use it by using uncached buffers that don't have the perag attached * so we can detect and avoid this problem. */ if (bp->b_pag && be32_to_cpu(agf->agf_seqno) != bp->b_pag->pag_agno) return __this_address; if (xfs_sb_version_haslazysbcount(&mp->m_sb) && be32_to_cpu(agf->agf_btreeblks) > be32_to_cpu(agf->agf_length)) return __this_address; if (xfs_sb_version_hasreflink(&mp->m_sb) && (be32_to_cpu(agf->agf_refcount_level) < 1 || be32_to_cpu(agf->agf_refcount_level) > XFS_BTREE_MAXLEVELS)) return __this_address; return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703', 'CWE-835'], 'message': 'xfs: add agf freeblocks verify in xfs_agf_verify We recently used fuzz(hydra) to test XFS and automatically generate tmp.img(XFS v5 format, but some metadata is wrong) xfs_repair information(just one AG): agf_freeblks 0, counted 3224 in ag 0 agf_longest 536874136, counted 3224 in ag 0 sb_fdblocks 613, counted 3228 Test as follows: mount tmp.img tmpdir cp file1M tmpdir sync In 4.19-stable, sync will stuck, the reason is: xfs_mountfs xfs_check_summary_counts if ((!xfs_sb_version_haslazysbcount(&mp->m_sb) || XFS_LAST_UNMOUNT_WAS_CLEAN(mp)) && !xfs_fs_has_sickness(mp, XFS_SICK_FS_COUNTERS)) return 0; -->just return, incore sb_fdblocks still be 613 xfs_initialize_perag_data cp file1M tmpdir -->ok(write file to pagecache) sync -->stuck(write pagecache to disk) xfs_map_blocks xfs_iomap_write_allocate while (count_fsb != 0) { nimaps = 0; while (nimaps == 0) { --> endless loop nimaps = 1; xfs_bmapi_write(..., &nimaps) --> nimaps becomes 0 again xfs_bmapi_write xfs_bmap_alloc xfs_bmap_btalloc xfs_alloc_vextent xfs_alloc_fix_freelist xfs_alloc_space_available -->fail(agf_freeblks is 0) In linux-next, sync not stuck, cause commit c2b3164320b5 ("xfs: use the latest extent at writeback delalloc conversion time") remove the above while, dmesg is as follows: [ 55.250114] XFS (loop0): page discard on page ffffea0008bc7380, inode 0x1b0c, offset 0. Users do not know why this page is discard, the better soultion is: 1. Like xfs_repair, make sure sb_fdblocks is equal to counted (xfs_initialize_perag_data did this, who is not called at this mount) 2. Add agf verify, if fail, will tell users to repair This patch use the second soultion. Signed-off-by: Zheng Bin <zhengbin13@huawei.com> Signed-off-by: Ren Xudong <renxudong1@huawei.com> Reviewed-by: Darrick J. Wong <darrick.wong@oracle.com> Signed-off-by: Darrick J. Wong <darrick.wong@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: */ static enum hrtimer_restart bfq_idle_slice_timer(struct hrtimer *timer) { struct bfq_data *bfqd = container_of(timer, struct bfq_data, idle_slice_timer); struct bfq_queue *bfqq = bfqd->in_service_queue; /* * Theoretical race here: the in-service queue can be NULL or * different from the queue that was idling if a new request * arrives for the current queue and there is a full dispatch * cycle that changes the in-service queue. This can hardly * happen, but in the worst case we just expire a queue too * early. */ if (bfqq) bfq_idle_slice_timer_body(bfqq); return HRTIMER_NORESTART; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'block, bfq: fix use-after-free in bfq_idle_slice_timer_body In bfq_idle_slice_timer func, bfqq = bfqd->in_service_queue is not in bfqd-lock critical section. The bfqq, which is not equal to NULL in bfq_idle_slice_timer, may be freed after passing to bfq_idle_slice_timer_body. So we will access the freed memory. In addition, considering the bfqq may be in race, we should firstly check whether bfqq is in service before doing something on it in bfq_idle_slice_timer_body func. If the bfqq in race is not in service, it means the bfqq has been expired through __bfq_bfqq_expire func, and wait_request flags has been cleared in __bfq_bfqd_reset_in_service func. So we do not need to re-clear the wait_request of bfqq which is not in service. KASAN log is given as follows: [13058.354613] ================================================================== [13058.354640] BUG: KASAN: use-after-free in bfq_idle_slice_timer+0xac/0x290 [13058.354644] Read of size 8 at addr ffffa02cf3e63f78 by task fork13/19767 [13058.354646] [13058.354655] CPU: 96 PID: 19767 Comm: fork13 [13058.354661] Call trace: [13058.354667] dump_backtrace+0x0/0x310 [13058.354672] show_stack+0x28/0x38 [13058.354681] dump_stack+0xd8/0x108 [13058.354687] print_address_description+0x68/0x2d0 [13058.354690] kasan_report+0x124/0x2e0 [13058.354697] __asan_load8+0x88/0xb0 [13058.354702] bfq_idle_slice_timer+0xac/0x290 [13058.354707] __hrtimer_run_queues+0x298/0x8b8 [13058.354710] hrtimer_interrupt+0x1b8/0x678 [13058.354716] arch_timer_handler_phys+0x4c/0x78 [13058.354722] handle_percpu_devid_irq+0xf0/0x558 [13058.354731] generic_handle_irq+0x50/0x70 [13058.354735] __handle_domain_irq+0x94/0x110 [13058.354739] gic_handle_irq+0x8c/0x1b0 [13058.354742] el1_irq+0xb8/0x140 [13058.354748] do_wp_page+0x260/0xe28 [13058.354752] __handle_mm_fault+0x8ec/0x9b0 [13058.354756] handle_mm_fault+0x280/0x460 [13058.354762] do_page_fault+0x3ec/0x890 [13058.354765] do_mem_abort+0xc0/0x1b0 [13058.354768] el0_da+0x24/0x28 [13058.354770] [13058.354773] Allocated by task 19731: [13058.354780] kasan_kmalloc+0xe0/0x190 [13058.354784] kasan_slab_alloc+0x14/0x20 [13058.354788] kmem_cache_alloc_node+0x130/0x440 [13058.354793] bfq_get_queue+0x138/0x858 [13058.354797] bfq_get_bfqq_handle_split+0xd4/0x328 [13058.354801] bfq_init_rq+0x1f4/0x1180 [13058.354806] bfq_insert_requests+0x264/0x1c98 [13058.354811] blk_mq_sched_insert_requests+0x1c4/0x488 [13058.354818] blk_mq_flush_plug_list+0x2d4/0x6e0 [13058.354826] blk_flush_plug_list+0x230/0x548 [13058.354830] blk_finish_plug+0x60/0x80 [13058.354838] read_pages+0xec/0x2c0 [13058.354842] __do_page_cache_readahead+0x374/0x438 [13058.354846] ondemand_readahead+0x24c/0x6b0 [13058.354851] page_cache_sync_readahead+0x17c/0x2f8 [13058.354858] generic_file_buffered_read+0x588/0xc58 [13058.354862] generic_file_read_iter+0x1b4/0x278 [13058.354965] ext4_file_read_iter+0xa8/0x1d8 [ext4] [13058.354972] __vfs_read+0x238/0x320 [13058.354976] vfs_read+0xbc/0x1c0 [13058.354980] ksys_read+0xdc/0x1b8 [13058.354984] __arm64_sys_read+0x50/0x60 [13058.354990] el0_svc_common+0xb4/0x1d8 [13058.354994] el0_svc_handler+0x50/0xa8 [13058.354998] el0_svc+0x8/0xc [13058.354999] [13058.355001] Freed by task 19731: [13058.355007] __kasan_slab_free+0x120/0x228 [13058.355010] kasan_slab_free+0x10/0x18 [13058.355014] kmem_cache_free+0x288/0x3f0 [13058.355018] bfq_put_queue+0x134/0x208 [13058.355022] bfq_exit_icq_bfqq+0x164/0x348 [13058.355026] bfq_exit_icq+0x28/0x40 [13058.355030] ioc_exit_icq+0xa0/0x150 [13058.355035] put_io_context_active+0x250/0x438 [13058.355038] exit_io_context+0xd0/0x138 [13058.355045] do_exit+0x734/0xc58 [13058.355050] do_group_exit+0x78/0x220 [13058.355054] __wake_up_parent+0x0/0x50 [13058.355058] el0_svc_common+0xb4/0x1d8 [13058.355062] el0_svc_handler+0x50/0xa8 [13058.355066] el0_svc+0x8/0xc [13058.355067] [13058.355071] The buggy address belongs to the object at ffffa02cf3e63e70#012 which belongs to the cache bfq_queue of size 464 [13058.355075] The buggy address is located 264 bytes inside of#012 464-byte region [ffffa02cf3e63e70, ffffa02cf3e64040) [13058.355077] The buggy address belongs to the page: [13058.355083] page:ffff7e80b3cf9800 count:1 mapcount:0 mapping:ffff802db5c90780 index:0xffffa02cf3e606f0 compound_mapcount: 0 [13058.366175] flags: 0x2ffffe0000008100(slab|head) [13058.370781] raw: 2ffffe0000008100 ffff7e80b53b1408 ffffa02d730c1c90 ffff802db5c90780 [13058.370787] raw: ffffa02cf3e606f0 0000000000370023 00000001ffffffff 0000000000000000 [13058.370789] page dumped because: kasan: bad access detected [13058.370791] [13058.370792] Memory state around the buggy address: [13058.370797] ffffa02cf3e63e00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fb fb [13058.370801] ffffa02cf3e63e80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [13058.370805] >ffffa02cf3e63f00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [13058.370808] ^ [13058.370811] ffffa02cf3e63f80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb [13058.370815] ffffa02cf3e64000: fb fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc [13058.370817] ================================================================== [13058.370820] Disabling lock debugging due to kernel taint Here, we directly pass the bfqd to bfq_idle_slice_timer_body func. -- V2->V3: rewrite the comment as suggested by Paolo Valente V1->V2: add one comment, and add Fixes and Reported-by tag. Fixes: aee69d78d ("block, bfq: introduce the BFQ-v0 I/O scheduler as an extra scheduler") Acked-by: Paolo Valente <paolo.valente@linaro.org> Reported-by: Wang Wang <wangwang2@huawei.com> Signed-off-by: Zhiqiang Liu <liuzhiqiang26@huawei.com> Signed-off-by: Feilong Lin <linfeilong@huawei.com> Signed-off-by: Jens Axboe <axboe@kernel.dk>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rsock_strbuf(VALUE str, long buflen) { long len; if (NIL_P(str)) return rb_str_new(0, buflen); StringValue(str); len = RSTRING_LEN(str); if (len >= buflen) { rb_str_modify(str); } else { rb_str_modify_expand(str, buflen - len); } rb_str_set_len(str, buflen); return str; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908'], 'message': 'ext/socket/init.c: do not return uninitialized buffer Resize string buffer only if some data is received in BasicSocket#read_nonblock and some methods. Co-Authored-By: Samuel Williams <samuel.williams@oriontransfer.co.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: rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from) { rb_io_t *fptr; VALUE str; struct recvfrom_arg arg; VALUE len, flg; long buflen; long slen; rb_scan_args(argc, argv, "12", &len, &flg, &str); if (flg == Qnil) arg.flags = 0; else arg.flags = NUM2INT(flg); buflen = NUM2INT(len); str = rsock_strbuf(str, buflen); GetOpenFile(sock, fptr); if (rb_io_read_pending(fptr)) { rb_raise(rb_eIOError, "recv for buffered IO"); } arg.fd = fptr->fd; arg.alen = (socklen_t)sizeof(arg.buf); arg.str = str; while (rb_io_check_closed(fptr), rsock_maybe_wait_fd(arg.fd), (slen = (long)rb_str_locktmp_ensure(str, recvfrom_locktmp, (VALUE)&arg)) < 0) { if (!rb_io_wait_readable(fptr->fd)) { rb_sys_fail("recvfrom(2)"); } } if (slen != RSTRING_LEN(str)) { rb_str_set_len(str, slen); } switch (from) { case RECV_RECV: return str; case RECV_IP: #if 0 if (arg.alen != sizeof(struct sockaddr_in)) { rb_raise(rb_eTypeError, "sockaddr size differs - should not happen"); } #endif if (arg.alen && arg.alen != sizeof(arg.buf)) /* OSX doesn't return a from result for connection-oriented sockets */ return rb_assoc_new(str, rsock_ipaddr(&arg.buf.addr, arg.alen, fptr->mode & FMODE_NOREVLOOKUP)); else return rb_assoc_new(str, Qnil); #ifdef HAVE_SYS_UN_H case RECV_UNIX: return rb_assoc_new(str, rsock_unixaddr(&arg.buf.un, arg.alen)); #endif case RECV_SOCKET: return rb_assoc_new(str, rsock_io_socket_addrinfo(sock, &arg.buf.addr, arg.alen)); default: rb_bug("rsock_s_recvfrom called with bad value"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908'], 'message': 'ext/socket/init.c: do not return uninitialized buffer Resize string buffer only if some data is received in BasicSocket#read_nonblock and some methods. Co-Authored-By: Samuel Williams <samuel.williams@oriontransfer.co.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: HiiGetConfigRespInfo( IN CONST EFI_HII_DATABASE_PROTOCOL *This ) { EFI_STATUS Status; HII_DATABASE_PRIVATE_DATA *Private; EFI_STRING ConfigAltResp; UINTN ConfigSize; ConfigAltResp = NULL; ConfigSize = 0; Private = HII_DATABASE_DATABASE_PRIVATE_DATA_FROM_THIS (This); // // Get ConfigResp string // Status = HiiConfigRoutingExportConfig(&Private->ConfigRouting,&ConfigAltResp); if (!EFI_ERROR (Status)){ ConfigSize = StrSize(ConfigAltResp); if (ConfigSize > gConfigRespSize){ // // Do 25% overallocation to minimize the number of memory allocations after ReadyToBoot. // Since lots of allocation after ReadyToBoot may change memory map and cause S4 resume issue. // gConfigRespSize = ConfigSize + (ConfigSize >> 2); if (gRTConfigRespBuffer != NULL){ FreePool(gRTConfigRespBuffer); DEBUG ((DEBUG_WARN, "[HiiDatabase]: Memory allocation is required after ReadyToBoot, which may change memory map and cause S4 resume issue.\n")); } gRTConfigRespBuffer = (EFI_STRING) AllocateRuntimeZeroPool (gConfigRespSize); if (gRTConfigRespBuffer == NULL){ FreePool(ConfigAltResp); DEBUG ((DEBUG_ERROR, "[HiiDatabase]: No enough memory resource to store the ConfigResp string.\n")); return EFI_OUT_OF_RESOURCES; } } else { ZeroMem(gRTConfigRespBuffer,gConfigRespSize); } CopyMem(gRTConfigRespBuffer,ConfigAltResp,ConfigSize); gBS->InstallConfigurationTable (&gEfiHiiConfigRoutingProtocolGuid, gRTConfigRespBuffer); FreePool(ConfigAltResp); } return EFI_SUCCESS; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'MdeModulePkg/HiiDB: Remove configuration table when it's freed (CVE-2019-14586) REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1995 Fix the corner case issue that the original configuration runtime memory is freed, but it is still exposed to the OS runtime. So this patch is to remove the configuration table to avoid being used in OS runtime when the configuration runtime memory is freed. Cc: Liming Gao <liming.gao@intel.com> Cc: Eric Dong <eric.dong@intel.com> Cc: Jian J Wang <jian.j.wang@intel.com> Signed-off-by: Dandan Bi <dandan.bi@intel.com> Reviewed-by: Eric Dong <eric.dong@intel.com> Reviewed-by: Jian J Wang <jian.j.wang@intel.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ov518_mode_init_regs(struct sd *sd) { struct gspca_dev *gspca_dev = (struct gspca_dev *)sd; int hsegs, vsegs, packet_size; struct usb_host_interface *alt; struct usb_interface *intf; intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface); alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt); if (!alt) { gspca_err(gspca_dev, "Couldn't get altsetting\n"); sd->gspca_dev.usb_err = -EIO; return; } packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize); ov518_reg_w32(sd, R51x_FIFO_PSIZE, packet_size & ~7, 2); /******** Set the mode ********/ reg_w(sd, 0x2b, 0); reg_w(sd, 0x2c, 0); reg_w(sd, 0x2d, 0); reg_w(sd, 0x2e, 0); reg_w(sd, 0x3b, 0); reg_w(sd, 0x3c, 0); reg_w(sd, 0x3d, 0); reg_w(sd, 0x3e, 0); if (sd->bridge == BRIDGE_OV518) { /* Set 8-bit (YVYU) input format */ reg_w_mask(sd, 0x20, 0x08, 0x08); /* Set 12-bit (4:2:0) output format */ reg_w_mask(sd, 0x28, 0x80, 0xf0); reg_w_mask(sd, 0x38, 0x80, 0xf0); } else { reg_w(sd, 0x28, 0x80); reg_w(sd, 0x38, 0x80); } hsegs = sd->gspca_dev.pixfmt.width / 16; vsegs = sd->gspca_dev.pixfmt.height / 4; reg_w(sd, 0x29, hsegs); reg_w(sd, 0x2a, vsegs); reg_w(sd, 0x39, hsegs); reg_w(sd, 0x3a, vsegs); /* Windows driver does this here; who knows why */ reg_w(sd, 0x2f, 0x80); /******** Set the framerate ********/ if (sd->bridge == BRIDGE_OV518PLUS && sd->revision == 0 && sd->sensor == SEN_OV7620AE) sd->clockdiv = 0; else sd->clockdiv = 1; /* Mode independent, but framerate dependent, regs */ /* 0x51: Clock divider; Only works on some cams which use 2 crystals */ reg_w(sd, 0x51, 0x04); reg_w(sd, 0x22, 0x18); reg_w(sd, 0x23, 0xff); if (sd->bridge == BRIDGE_OV518PLUS) { switch (sd->sensor) { case SEN_OV7620AE: /* * HdG: 640x480 needs special handling on device * revision 2, we check for device revision > 0 to * avoid regressions, as we don't know the correct * thing todo for revision 1. * * Also this likely means we don't need to * differentiate between the OV7620 and OV7620AE, * earlier testing hitting this same problem likely * happened to be with revision < 2 cams using an * OV7620 and revision 2 cams using an OV7620AE. */ if (sd->revision > 0 && sd->gspca_dev.pixfmt.width == 640) { reg_w(sd, 0x20, 0x60); reg_w(sd, 0x21, 0x1f); } else { reg_w(sd, 0x20, 0x00); reg_w(sd, 0x21, 0x19); } break; case SEN_OV7620: reg_w(sd, 0x20, 0x00); reg_w(sd, 0x21, 0x19); break; default: reg_w(sd, 0x21, 0x19); } } else reg_w(sd, 0x71, 0x17); /* Compression-related? */ /* FIXME: Sensor-specific */ /* Bit 5 is what matters here. Of course, it is "reserved" */ i2c_w(sd, 0x54, 0x23); reg_w(sd, 0x2f, 0x80); if (sd->bridge == BRIDGE_OV518PLUS) { reg_w(sd, 0x24, 0x94); reg_w(sd, 0x25, 0x90); ov518_reg_w32(sd, 0xc4, 400, 2); /* 190h */ ov518_reg_w32(sd, 0xc6, 540, 2); /* 21ch */ ov518_reg_w32(sd, 0xc7, 540, 2); /* 21ch */ ov518_reg_w32(sd, 0xc8, 108, 2); /* 6ch */ ov518_reg_w32(sd, 0xca, 131098, 3); /* 2001ah */ ov518_reg_w32(sd, 0xcb, 532, 2); /* 214h */ ov518_reg_w32(sd, 0xcc, 2400, 2); /* 960h */ ov518_reg_w32(sd, 0xcd, 32, 2); /* 20h */ ov518_reg_w32(sd, 0xce, 608, 2); /* 260h */ } else { reg_w(sd, 0x24, 0x9f); reg_w(sd, 0x25, 0x90); ov518_reg_w32(sd, 0xc4, 400, 2); /* 190h */ ov518_reg_w32(sd, 0xc6, 381, 2); /* 17dh */ ov518_reg_w32(sd, 0xc7, 381, 2); /* 17dh */ ov518_reg_w32(sd, 0xc8, 128, 2); /* 80h */ ov518_reg_w32(sd, 0xca, 183331, 3); /* 2cc23h */ ov518_reg_w32(sd, 0xcb, 746, 2); /* 2eah */ ov518_reg_w32(sd, 0xcc, 1750, 2); /* 6d6h */ ov518_reg_w32(sd, 0xcd, 45, 2); /* 2dh */ ov518_reg_w32(sd, 0xce, 851, 2); /* 353h */ } reg_w(sd, 0x2f, 0x80); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'media: ov519: add missing endpoint sanity checks Make sure to check that we have at least one endpoint before accessing the endpoint array to avoid dereferencing a NULL-pointer on stream start. Note that these sanity checks are not redundant as the driver is mixing looking up altsettings by index and by number, which need not coincide. Fixes: 1876bb923c98 ("V4L/DVB (12079): gspca_ov519: add support for the ov511 bridge") Fixes: b282d87332f5 ("V4L/DVB (12080): gspca_ov519: Fix ov518+ with OV7620AE (Trust spacecam 320)") Cc: stable <stable@vger.kernel.org> # 2.6.31 Cc: Hans de Goede <hdegoede@redhat.com> Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pb0100_start(struct sd *sd) { int err, packet_size, max_packet_size; struct usb_host_interface *alt; struct usb_interface *intf; struct gspca_dev *gspca_dev = (struct gspca_dev *)sd; struct cam *cam = &sd->gspca_dev.cam; u32 mode = cam->cam_mode[sd->gspca_dev.curr_mode].priv; intf = usb_ifnum_to_if(sd->gspca_dev.dev, sd->gspca_dev.iface); alt = usb_altnum_to_altsetting(intf, sd->gspca_dev.alt); if (!alt) return -ENODEV; packet_size = le16_to_cpu(alt->endpoint[0].desc.wMaxPacketSize); /* If we don't have enough bandwidth use a lower framerate */ max_packet_size = sd->sensor->max_packet_size[sd->gspca_dev.curr_mode]; if (packet_size < max_packet_size) stv06xx_write_sensor(sd, PB_ROWSPEED, BIT(4)|BIT(3)|BIT(1)); else stv06xx_write_sensor(sd, PB_ROWSPEED, BIT(5)|BIT(3)|BIT(1)); /* Setup sensor window */ if (mode & PB0100_CROP_TO_VGA) { stv06xx_write_sensor(sd, PB_RSTART, 30); stv06xx_write_sensor(sd, PB_CSTART, 20); stv06xx_write_sensor(sd, PB_RWSIZE, 240 - 1); stv06xx_write_sensor(sd, PB_CWSIZE, 320 - 1); } else { stv06xx_write_sensor(sd, PB_RSTART, 8); stv06xx_write_sensor(sd, PB_CSTART, 4); stv06xx_write_sensor(sd, PB_RWSIZE, 288 - 1); stv06xx_write_sensor(sd, PB_CWSIZE, 352 - 1); } if (mode & PB0100_SUBSAMPLE) { stv06xx_write_bridge(sd, STV_Y_CTRL, 0x02); /* Wrong, FIXME */ stv06xx_write_bridge(sd, STV_X_CTRL, 0x06); stv06xx_write_bridge(sd, STV_SCAN_RATE, 0x10); } else { stv06xx_write_bridge(sd, STV_Y_CTRL, 0x01); stv06xx_write_bridge(sd, STV_X_CTRL, 0x0a); /* larger -> slower */ stv06xx_write_bridge(sd, STV_SCAN_RATE, 0x20); } err = stv06xx_write_sensor(sd, PB_CONTROL, BIT(5)|BIT(3)|BIT(1)); gspca_dbg(gspca_dev, D_STREAM, "Started stream, status: %d\n", err); return (err < 0) ? err : 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'media: stv06xx: add missing descriptor sanity checks Make sure to check that we have two alternate settings and at least one endpoint before accessing the second altsetting structure and dereferencing the endpoint arrays. This specifically avoids dereferencing NULL-pointers or corrupting memory when a device does not have the expected descriptors. Note that the sanity checks in stv06xx_start() and pb0100_start() are not redundant as the driver is mixing looking up altsettings by index and by number, which may not coincide. Fixes: 8668d504d72c ("V4L/DVB (12082): gspca_stv06xx: Add support for st6422 bridge and sensor") Fixes: c0b33bdc5b8d ("[media] gspca-stv06xx: support bandwidth changing") Cc: stable <stable@vger.kernel.org> # 2.6.31 Cc: Hans de Goede <hdegoede@redhat.com> Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int stv06xx_isoc_init(struct gspca_dev *gspca_dev) { struct usb_host_interface *alt; struct sd *sd = (struct sd *) gspca_dev; /* Start isoc bandwidth "negotiation" at max isoc bandwidth */ alt = &gspca_dev->dev->actconfig->intf_cache[0]->altsetting[1]; alt->endpoint[0].desc.wMaxPacketSize = cpu_to_le16(sd->sensor->max_packet_size[gspca_dev->curr_mode]); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'media: stv06xx: add missing descriptor sanity checks Make sure to check that we have two alternate settings and at least one endpoint before accessing the second altsetting structure and dereferencing the endpoint arrays. This specifically avoids dereferencing NULL-pointers or corrupting memory when a device does not have the expected descriptors. Note that the sanity checks in stv06xx_start() and pb0100_start() are not redundant as the driver is mixing looking up altsettings by index and by number, which may not coincide. Fixes: 8668d504d72c ("V4L/DVB (12082): gspca_stv06xx: Add support for st6422 bridge and sensor") Fixes: c0b33bdc5b8d ("[media] gspca-stv06xx: support bandwidth changing") Cc: stable <stable@vger.kernel.org> # 2.6.31 Cc: Hans de Goede <hdegoede@redhat.com> Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Hans Verkuil <hverkuil-cisco@xs4all.nl> Signed-off-by: Mauro Carvalho Chehab <mchehab+huawei@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: get_filter( Operation *op, BerElement *ber, Filter **filt, const char **text ) { ber_tag_t tag; ber_len_t len; int err; Filter f; Debug( LDAP_DEBUG_FILTER, "begin get_filter\n", 0, 0, 0 ); /* * A filter looks like this coming in: * Filter ::= CHOICE { * and [0] SET OF Filter, * or [1] SET OF Filter, * not [2] Filter, * equalityMatch [3] AttributeValueAssertion, * substrings [4] SubstringFilter, * greaterOrEqual [5] AttributeValueAssertion, * lessOrEqual [6] AttributeValueAssertion, * present [7] AttributeType, * approxMatch [8] AttributeValueAssertion, * extensibleMatch [9] MatchingRuleAssertion * } * * SubstringFilter ::= SEQUENCE { * type AttributeType, * SEQUENCE OF CHOICE { * initial [0] IA5String, * any [1] IA5String, * final [2] IA5String * } * } * * MatchingRuleAssertion ::= SEQUENCE { * matchingRule [1] MatchingRuleId OPTIONAL, * type [2] AttributeDescription OPTIONAL, * matchValue [3] AssertionValue, * dnAttributes [4] BOOLEAN DEFAULT FALSE * } * */ tag = ber_peek_tag( ber, &len ); if( tag == LBER_ERROR ) { *text = "error decoding filter"; return SLAPD_DISCONNECT; } err = LDAP_SUCCESS; f.f_next = NULL; f.f_choice = tag; switch ( f.f_choice ) { case LDAP_FILTER_EQUALITY: Debug( LDAP_DEBUG_FILTER, "EQUALITY\n", 0, 0, 0 ); err = get_ava( op, ber, &f, SLAP_MR_EQUALITY, text ); if ( err != LDAP_SUCCESS ) { break; } assert( f.f_ava != NULL ); break; case LDAP_FILTER_SUBSTRINGS: Debug( LDAP_DEBUG_FILTER, "SUBSTRINGS\n", 0, 0, 0 ); err = get_ssa( op, ber, &f, text ); if( err != LDAP_SUCCESS ) { break; } assert( f.f_sub != NULL ); break; case LDAP_FILTER_GE: Debug( LDAP_DEBUG_FILTER, "GE\n", 0, 0, 0 ); err = get_ava( op, ber, &f, SLAP_MR_ORDERING, text ); if ( err != LDAP_SUCCESS ) { break; } assert( f.f_ava != NULL ); break; case LDAP_FILTER_LE: Debug( LDAP_DEBUG_FILTER, "LE\n", 0, 0, 0 ); err = get_ava( op, ber, &f, SLAP_MR_ORDERING, text ); if ( err != LDAP_SUCCESS ) { break; } assert( f.f_ava != NULL ); break; case LDAP_FILTER_PRESENT: { struct berval type; Debug( LDAP_DEBUG_FILTER, "PRESENT\n", 0, 0, 0 ); if ( ber_scanf( ber, "m", &type ) == LBER_ERROR ) { err = SLAPD_DISCONNECT; *text = "error decoding filter"; break; } f.f_desc = NULL; err = slap_bv2ad( &type, &f.f_desc, text ); if( err != LDAP_SUCCESS ) { f.f_choice |= SLAPD_FILTER_UNDEFINED; err = slap_bv2undef_ad( &type, &f.f_desc, text, SLAP_AD_PROXIED|SLAP_AD_NOINSERT ); if ( err != LDAP_SUCCESS ) { /* unrecognized attribute description or other error */ Debug( LDAP_DEBUG_ANY, "get_filter: conn %lu unknown attribute " "type=%s (%d)\n", op->o_connid, type.bv_val, err ); err = LDAP_SUCCESS; f.f_desc = slap_bv2tmp_ad( &type, op->o_tmpmemctx ); } *text = NULL; } assert( f.f_desc != NULL ); } break; case LDAP_FILTER_APPROX: Debug( LDAP_DEBUG_FILTER, "APPROX\n", 0, 0, 0 ); err = get_ava( op, ber, &f, SLAP_MR_EQUALITY_APPROX, text ); if ( err != LDAP_SUCCESS ) { break; } assert( f.f_ava != NULL ); break; case LDAP_FILTER_AND: Debug( LDAP_DEBUG_FILTER, "AND\n", 0, 0, 0 ); err = get_filter_list( op, ber, &f.f_and, text ); if ( err != LDAP_SUCCESS ) { break; } if ( f.f_and == NULL ) { f.f_choice = SLAPD_FILTER_COMPUTED; f.f_result = LDAP_COMPARE_TRUE; } /* no assert - list could be empty */ break; case LDAP_FILTER_OR: Debug( LDAP_DEBUG_FILTER, "OR\n", 0, 0, 0 ); err = get_filter_list( op, ber, &f.f_or, text ); if ( err != LDAP_SUCCESS ) { break; } if ( f.f_or == NULL ) { f.f_choice = SLAPD_FILTER_COMPUTED; f.f_result = LDAP_COMPARE_FALSE; } /* no assert - list could be empty */ break; case LDAP_FILTER_NOT: Debug( LDAP_DEBUG_FILTER, "NOT\n", 0, 0, 0 ); (void) ber_skip_tag( ber, &len ); err = get_filter( op, ber, &f.f_not, text ); if ( err != LDAP_SUCCESS ) { break; } assert( f.f_not != NULL ); if ( f.f_not->f_choice == SLAPD_FILTER_COMPUTED ) { int fresult = f.f_not->f_result; f.f_choice = SLAPD_FILTER_COMPUTED; op->o_tmpfree( f.f_not, op->o_tmpmemctx ); f.f_not = NULL; switch( fresult ) { case LDAP_COMPARE_TRUE: f.f_result = LDAP_COMPARE_FALSE; break; case LDAP_COMPARE_FALSE: f.f_result = LDAP_COMPARE_TRUE; break; default: ; /* (!Undefined) is Undefined */ } } break; case LDAP_FILTER_EXT: Debug( LDAP_DEBUG_FILTER, "EXTENSIBLE\n", 0, 0, 0 ); err = get_mra( op, ber, &f, text ); if ( err != LDAP_SUCCESS ) { break; } assert( f.f_mra != NULL ); break; default: (void) ber_scanf( ber, "x" ); /* skip the element */ Debug( LDAP_DEBUG_ANY, "get_filter: unknown filter type=%lu\n", f.f_choice, 0, 0 ); f.f_choice = SLAPD_FILTER_COMPUTED; f.f_result = SLAPD_COMPARE_UNDEFINED; break; } if( err != LDAP_SUCCESS && err != SLAPD_DISCONNECT ) { /* ignore error */ *text = NULL; f.f_choice = SLAPD_FILTER_COMPUTED; f.f_result = SLAPD_COMPARE_UNDEFINED; err = LDAP_SUCCESS; } if ( err == LDAP_SUCCESS ) { *filt = op->o_tmpalloc( sizeof(f), op->o_tmpmemctx ); **filt = f; } Debug( LDAP_DEBUG_FILTER, "end get_filter %d\n", err, 0, 0 ); return( err ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674'], 'message': 'ITS#9202 limit depth of nested filters Using a hardcoded limit for now; no reasonable apps should ever run into it.'</s>
<s>[INST] Given the following code containing errors, provide 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 dw_spi_transfer_one(struct spi_controller *master, struct spi_device *spi, struct spi_transfer *transfer) { struct dw_spi *dws = spi_controller_get_devdata(master); struct chip_data *chip = spi_get_ctldata(spi); u8 imask = 0; u16 txlevel = 0; u32 cr0; int ret; dws->dma_mapped = 0; dws->tx = (void *)transfer->tx_buf; dws->tx_end = dws->tx + transfer->len; dws->rx = transfer->rx_buf; dws->rx_end = dws->rx + transfer->len; dws->len = transfer->len; spi_enable_chip(dws, 0); /* Handle per transfer options for bpw and speed */ if (transfer->speed_hz != dws->current_freq) { if (transfer->speed_hz != chip->speed_hz) { /* clk_div doesn't support odd number */ chip->clk_div = (DIV_ROUND_UP(dws->max_freq, transfer->speed_hz) + 1) & 0xfffe; chip->speed_hz = transfer->speed_hz; } dws->current_freq = transfer->speed_hz; spi_set_clk(dws, chip->clk_div); } dws->n_bytes = DIV_ROUND_UP(transfer->bits_per_word, BITS_PER_BYTE); dws->dma_width = DIV_ROUND_UP(transfer->bits_per_word, BITS_PER_BYTE); /* Default SPI mode is SCPOL = 0, SCPH = 0 */ cr0 = (transfer->bits_per_word - 1) | (chip->type << SPI_FRF_OFFSET) | ((((spi->mode & SPI_CPOL) ? 1 : 0) << SPI_SCOL_OFFSET) | (((spi->mode & SPI_CPHA) ? 1 : 0) << SPI_SCPH_OFFSET)) | (chip->tmode << SPI_TMOD_OFFSET); /* * Adjust transfer mode if necessary. Requires platform dependent * chipselect mechanism. */ if (chip->cs_control) { if (dws->rx && dws->tx) chip->tmode = SPI_TMOD_TR; else if (dws->rx) chip->tmode = SPI_TMOD_RO; else chip->tmode = SPI_TMOD_TO; cr0 &= ~SPI_TMOD_MASK; cr0 |= (chip->tmode << SPI_TMOD_OFFSET); } dw_writel(dws, DW_SPI_CTRL0, cr0); /* Check if current transfer is a DMA transaction */ if (master->can_dma && master->can_dma(master, spi, transfer)) dws->dma_mapped = master->cur_msg_mapped; /* For poll mode just disable all interrupts */ spi_mask_intr(dws, 0xff); /* * Interrupt mode * we only need set the TXEI IRQ, as TX/RX always happen syncronizely */ if (dws->dma_mapped) { ret = dws->dma_ops->dma_setup(dws, transfer); if (ret < 0) { spi_enable_chip(dws, 1); return ret; } } else if (!chip->poll_mode) { txlevel = min_t(u16, dws->fifo_len / 2, dws->len / dws->n_bytes); dw_writel(dws, DW_SPI_TXFLTR, txlevel); /* Set the interrupt mask */ imask |= SPI_INT_TXEI | SPI_INT_TXOI | SPI_INT_RXUI | SPI_INT_RXOI; spi_umask_intr(dws, imask); dws->transfer_handler = interrupt_transfer; } spi_enable_chip(dws, 1); if (dws->dma_mapped) { ret = dws->dma_ops->dma_transfer(dws, transfer); if (ret < 0) return ret; } if (chip->poll_mode) return poll_transfer(dws); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'spi: spi-dw: Add lock protect dw_spi rx/tx to prevent concurrent calls dw_spi_irq() and dw_spi_transfer_one concurrent calls. I find a panic in dw_writer(): txw = *(u8 *)(dws->tx), when dw->tx==null, dw->len==4, and dw->tx_end==1. When tpm driver's message overtime dw_spi_irq() and dw_spi_transfer_one may concurrent visit dw_spi, so I think dw_spi structure lack of protection. Otherwise dw_spi_transfer_one set dw rx/tx buffer and then open irq, store dw rx/tx instructions and other cores handle irq load dw rx/tx instructions may out of order. [ 1025.321302] Call trace: ... [ 1025.321319] __crash_kexec+0x98/0x148 [ 1025.321323] panic+0x17c/0x314 [ 1025.321329] die+0x29c/0x2e8 [ 1025.321334] die_kernel_fault+0x68/0x78 [ 1025.321337] __do_kernel_fault+0x90/0xb0 [ 1025.321346] do_page_fault+0x88/0x500 [ 1025.321347] do_translation_fault+0xa8/0xb8 [ 1025.321349] do_mem_abort+0x68/0x118 [ 1025.321351] el1_da+0x20/0x8c [ 1025.321362] dw_writer+0xc8/0xd0 [ 1025.321364] interrupt_transfer+0x60/0x110 [ 1025.321365] dw_spi_irq+0x48/0x70 ... Signed-off-by: wuxu.wu <wuxu.wu@huawei.com> Link: https://lore.kernel.org/r/1577849981-31489-1-git-send-email-wuxu.wu@huawei.com Signed-off-by: Mark Brown <broonie@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void dw_writer(struct dw_spi *dws) { u32 max = tx_max(dws); u16 txw = 0; while (max--) { /* Set the tx word if the transfer's original "tx" is not null */ if (dws->tx_end - dws->len) { if (dws->n_bytes == 1) txw = *(u8 *)(dws->tx); else txw = *(u16 *)(dws->tx); } dw_write_io_reg(dws, DW_SPI_DR, txw); dws->tx += dws->n_bytes; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-662'], 'message': 'spi: spi-dw: Add lock protect dw_spi rx/tx to prevent concurrent calls dw_spi_irq() and dw_spi_transfer_one concurrent calls. I find a panic in dw_writer(): txw = *(u8 *)(dws->tx), when dw->tx==null, dw->len==4, and dw->tx_end==1. When tpm driver's message overtime dw_spi_irq() and dw_spi_transfer_one may concurrent visit dw_spi, so I think dw_spi structure lack of protection. Otherwise dw_spi_transfer_one set dw rx/tx buffer and then open irq, store dw rx/tx instructions and other cores handle irq load dw rx/tx instructions may out of order. [ 1025.321302] Call trace: ... [ 1025.321319] __crash_kexec+0x98/0x148 [ 1025.321323] panic+0x17c/0x314 [ 1025.321329] die+0x29c/0x2e8 [ 1025.321334] die_kernel_fault+0x68/0x78 [ 1025.321337] __do_kernel_fault+0x90/0xb0 [ 1025.321346] do_page_fault+0x88/0x500 [ 1025.321347] do_translation_fault+0xa8/0xb8 [ 1025.321349] do_mem_abort+0x68/0x118 [ 1025.321351] el1_da+0x20/0x8c [ 1025.321362] dw_writer+0xc8/0xd0 [ 1025.321364] interrupt_transfer+0x60/0x110 [ 1025.321365] dw_spi_irq+0x48/0x70 ... Signed-off-by: wuxu.wu <wuxu.wu@huawei.com> Link: https://lore.kernel.org/r/1577849981-31489-1-git-send-email-wuxu.wu@huawei.com Signed-off-by: Mark Brown <broonie@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s, UINT16 flags) { BYTE bitsPerPixelId; BITMAP_DATA_EX* bitmapData; UINT32 new_len; BYTE* new_data; CACHE_BITMAP_V3_ORDER* cache_bitmap_v3; if (!update || !s) return NULL; cache_bitmap_v3 = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER)); if (!cache_bitmap_v3) goto fail; cache_bitmap_v3->cacheId = flags & 0x00000003; cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7; bitsPerPixelId = (flags & 0x00000078) >> 3; cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId]; if (Stream_GetRemainingLength(s) < 21) goto fail; Stream_Read_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key1); /* key1 (4 bytes) */ Stream_Read_UINT32(s, cache_bitmap_v3->key2); /* key2 (4 bytes) */ bitmapData = &cache_bitmap_v3->bitmapData; Stream_Read_UINT8(s, bitmapData->bpp); if ((bitmapData->bpp < 1) || (bitmapData->bpp > 32)) { WLog_Print(update->log, WLOG_ERROR, "invalid bpp value %" PRIu32 "", bitmapData->bpp); goto fail; } Stream_Seek_UINT8(s); /* reserved1 (1 byte) */ Stream_Seek_UINT8(s); /* reserved2 (1 byte) */ Stream_Read_UINT8(s, bitmapData->codecID); /* codecID (1 byte) */ Stream_Read_UINT16(s, bitmapData->width); /* width (2 bytes) */ Stream_Read_UINT16(s, bitmapData->height); /* height (2 bytes) */ Stream_Read_UINT32(s, new_len); /* length (4 bytes) */ if (Stream_GetRemainingLength(s) < new_len) goto fail; new_data = (BYTE*)realloc(bitmapData->data, new_len); if (!new_data) goto fail; bitmapData->data = new_data; bitmapData->length = new_len; Stream_Read(s, bitmapData->data, bitmapData->length); return cache_bitmap_v3; fail: free_cache_bitmap_v3_order(update->context, cache_bitmap_v3); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fixed #6013: Check new length is > 0'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void update_read_synchronize(rdpUpdate* update, wStream* s) { WINPR_UNUSED(update); Stream_Seek_UINT16(s); /* pad2Octets (2 bytes) */ /** * The Synchronize Update is an artifact from the * T.128 protocol and should be ignored. */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-125'], 'message': 'Fixed #6006: bounds checks in update_read_synchronize'</s>
<s>[INST] Given the following code containing errors, provide 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 autodetect_recv_bandwidth_measure_results(rdpRdp* rdp, wStream* s, AUTODETECT_RSP_PDU* autodetectRspPdu) { BOOL success = TRUE; if (autodetectRspPdu->headerLength != 0x0E) return FALSE; WLog_VRB(AUTODETECT_TAG, "received Bandwidth Measure Results PDU"); Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureTimeDelta); /* timeDelta (4 bytes) */ Stream_Read_UINT32(s, rdp->autodetect->bandwidthMeasureByteCount); /* byteCount (4 bytes) */ if (rdp->autodetect->bandwidthMeasureTimeDelta > 0) rdp->autodetect->netCharBandwidth = rdp->autodetect->bandwidthMeasureByteCount * 8 / rdp->autodetect->bandwidthMeasureTimeDelta; else rdp->autodetect->netCharBandwidth = 0; IFCALLRET(rdp->autodetect->BandwidthMeasureResults, success, rdp->context, autodetectRspPdu->sequenceNumber); return success; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed #6009: Bounds checks in autodetect_recv_bandwidth_measure_results'</s>
<s>[INST] Given the following code containing errors, provide 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 rdp_read_flow_control_pdu(wStream* s, UINT16* type) { /* * Read flow control PDU - documented in FlowPDU section in T.128 * http://www.itu.int/rec/T-REC-T.128-199802-S/en * The specification for the PDU has pad8bits listed BEFORE pduTypeFlow. * However, so far pad8bits has always been observed to arrive AFTER pduTypeFlow. * Switched the order of these two fields to match this observation. */ UINT8 pduType; Stream_Read_UINT8(s, pduType); /* pduTypeFlow */ *type = pduType; Stream_Seek_UINT8(s); /* pad8bits */ Stream_Seek_UINT8(s); /* flowIdentifier */ Stream_Seek_UINT8(s); /* flowNumber */ Stream_Seek_UINT16(s); /* pduSource */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed #6007: Boundary checks in rdp_read_flow_control_pdu'</s>
<s>[INST] Given the following code containing errors, provide 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 ip6_input(struct mbuf *m) { struct ip6 *ip6; Slirp *slirp = m->slirp; if (!slirp->in6_enabled) { goto bad; } DEBUG_CALL("ip6_input"); DEBUG_ARG("m = %p", m); DEBUG_ARG("m_len = %d", m->m_len); if (m->m_len < sizeof(struct ip6)) { goto bad; } ip6 = mtod(m, struct ip6 *); if (ip6->ip_v != IP6VERSION) { goto bad; } if (ntohs(ip6->ip_pl) > slirp->if_mtu) { icmp6_send_error(m, ICMP6_TOOBIG, 0); goto bad; } /* check ip_ttl for a correct ICMP reply */ if (ip6->ip_hl == 0) { icmp6_send_error(m, ICMP6_TIMXCEED, ICMP6_TIMXCEED_INTRANS); goto bad; } /* * Switch out to protocol's input routine. */ switch (ip6->ip_nh) { case IPPROTO_TCP: NTOHS(ip6->ip_pl); tcp_input(m, sizeof(struct ip6), (struct socket *)NULL, AF_INET6); break; case IPPROTO_UDP: udp6_input(m); break; case IPPROTO_ICMPV6: icmp6_input(m); break; default: m_free(m); } return; bad: m_free(m); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Drop bogus IPv6 messages Drop IPv6 message shorter than what's mentioned in the payload length header (+ the size of the IPv6 header). They're invalid an could lead to data leakage in icmp6_send_echoreply().'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static INLINE INT32 planar_skip_plane_rle(const BYTE* pSrcData, UINT32 SrcSize, UINT32 nWidth, UINT32 nHeight) { UINT32 x, y; BYTE controlByte; const BYTE* pRLE = pSrcData; const BYTE* pEnd = &pSrcData[SrcSize]; for (y = 0; y < nHeight; y++) { for (x = 0; x < nWidth;) { int cRawBytes; int nRunLength; if (pRLE >= pEnd) return -1; controlByte = *pRLE++; nRunLength = PLANAR_CONTROL_BYTE_RUN_LENGTH(controlByte); cRawBytes = PLANAR_CONTROL_BYTE_RAW_BYTES(controlByte); if (nRunLength == 1) { nRunLength = cRawBytes + 16; cRawBytes = 0; } else if (nRunLength == 2) { nRunLength = cRawBytes + 32; cRawBytes = 0; } pRLE += cRawBytes; x += cRawBytes; x += nRunLength; if (x > nWidth) return -1; if (pRLE > pEnd) return -1; } } return (INT32)(pRLE - pSrcData); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11521: Out of bounds write in planar codec. Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide 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 update_read_multi_dstblt_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_DSTBLT_ORDER* multi_dstblt) { ORDER_FIELD_COORD(1, multi_dstblt->nLeftRect); ORDER_FIELD_COORD(2, multi_dstblt->nTopRect); ORDER_FIELD_COORD(3, multi_dstblt->nWidth); ORDER_FIELD_COORD(4, multi_dstblt->nHeight); ORDER_FIELD_BYTE(5, multi_dstblt->bRop); ORDER_FIELD_BYTE(6, multi_dstblt->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_dstblt->cbData); return update_read_delta_rects(s, multi_dstblt->rectangles, multi_dstblt->numRectangles); } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11522: Limit number of DELTA_RECT to 45. Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide 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 update_read_multi_opaque_rect_order(wStream* s, const ORDER_INFO* orderInfo, MULTI_OPAQUE_RECT_ORDER* multi_opaque_rect) { BYTE byte; ORDER_FIELD_COORD(1, multi_opaque_rect->nLeftRect); ORDER_FIELD_COORD(2, multi_opaque_rect->nTopRect); ORDER_FIELD_COORD(3, multi_opaque_rect->nWidth); ORDER_FIELD_COORD(4, multi_opaque_rect->nHeight); if (orderInfo->fieldFlags & ORDER_FIELD_05) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FFFF00) | ((UINT32)byte); } if (orderInfo->fieldFlags & ORDER_FIELD_06) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x00FF00FF) | ((UINT32)byte << 8); } if (orderInfo->fieldFlags & ORDER_FIELD_07) { if (Stream_GetRemainingLength(s) < 1) return FALSE; Stream_Read_UINT8(s, byte); multi_opaque_rect->color = (multi_opaque_rect->color & 0x0000FFFF) | ((UINT32)byte << 16); } ORDER_FIELD_BYTE(8, multi_opaque_rect->numRectangles); if (orderInfo->fieldFlags & ORDER_FIELD_09) { if (Stream_GetRemainingLength(s) < 2) return FALSE; Stream_Read_UINT16(s, multi_opaque_rect->cbData); return update_read_delta_rects(s, multi_opaque_rect->rectangles, multi_opaque_rect->numRectangles); } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11522: Limit number of DELTA_RECT to 45. Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static INLINE BOOL update_read_delta_rects(wStream* s, DELTA_RECT* rectangles, UINT32 number) { UINT32 i; BYTE flags = 0; BYTE* zeroBits; UINT32 zeroBitsSize; if (number > 45) number = 45; zeroBitsSize = ((number + 1) / 2); if (Stream_GetRemainingLength(s) < zeroBitsSize) return FALSE; Stream_GetPointer(s, zeroBits); Stream_Seek(s, zeroBitsSize); ZeroMemory(rectangles, sizeof(DELTA_RECT) * number); for (i = 0; i < number; i++) { if (i % 2 == 0) flags = zeroBits[i / 2]; if ((~flags & 0x80) && !update_read_delta(s, &rectangles[i].left)) return FALSE; if ((~flags & 0x40) && !update_read_delta(s, &rectangles[i].top)) return FALSE; if (~flags & 0x20) { if (!update_read_delta(s, &rectangles[i].width)) return FALSE; } else if (i > 0) rectangles[i].width = rectangles[i - 1].width; else rectangles[i].width = 0; if (~flags & 0x10) { if (!update_read_delta(s, &rectangles[i].height)) return FALSE; } else if (i > 0) rectangles[i].height = rectangles[i - 1].height; else rectangles[i].height = 0; if (i > 0) { rectangles[i].left += rectangles[i - 1].left; rectangles[i].top += rectangles[i - 1].top; } flags <<= 4; } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11522: Limit number of DELTA_RECT to 45. Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static INLINE BOOL RLEDECOMPRESS(const BYTE* pbSrcBuffer, UINT32 cbSrcBuffer, BYTE* pbDestBuffer, UINT32 rowDelta, UINT32 width, UINT32 height) { const BYTE* pbSrc = pbSrcBuffer; const BYTE* pbEnd; const BYTE* pbDestEnd; BYTE* pbDest = pbDestBuffer; PIXEL temp; PIXEL fgPel = WHITE_PIXEL; BOOL fInsertFgPel = FALSE; BOOL fFirstLine = TRUE; BYTE bitmask; PIXEL pixelA, pixelB; UINT32 runLength; UINT32 code; UINT32 advance; RLEEXTRA if ((rowDelta == 0) || (rowDelta < width)) return FALSE; if (!pbSrcBuffer || !pbDestBuffer) return FALSE; pbEnd = pbSrcBuffer + cbSrcBuffer; pbDestEnd = pbDestBuffer + rowDelta * height; while (pbSrc < pbEnd) { /* Watch out for the end of the first scanline. */ if (fFirstLine) { if ((UINT32)(pbDest - pbDestBuffer) >= rowDelta) { fFirstLine = FALSE; fInsertFgPel = FALSE; } } /* Extract the compression order code ID from the compression order header. */ code = ExtractCodeId(*pbSrc); /* Handle Background Run Orders. */ if (code == REGULAR_BG_RUN || code == MEGA_MEGA_BG_RUN) { runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; if (fFirstLine) { if (fInsertFgPel) { if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, fgPel); DESTNEXTPIXEL(pbDest); runLength = runLength - 1; } if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; UNROLL(runLength, { DESTWRITEPIXEL(pbDest, BLACK_PIXEL); DESTNEXTPIXEL(pbDest); }); } else { if (fInsertFgPel) { DESTREADPIXEL(temp, pbDest - rowDelta); if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, temp ^ fgPel); DESTNEXTPIXEL(pbDest); runLength--; } if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; UNROLL(runLength, { DESTREADPIXEL(temp, pbDest - rowDelta); DESTWRITEPIXEL(pbDest, temp); DESTNEXTPIXEL(pbDest); }); } /* A follow-on background run order will need a foreground pel inserted. */ fInsertFgPel = TRUE; continue; } /* For any of the other run-types a follow-on background run order does not need a foreground pel inserted. */ fInsertFgPel = FALSE; switch (code) { /* Handle Foreground Run Orders. */ case REGULAR_FG_RUN: case MEGA_MEGA_FG_RUN: case LITE_SET_FG_FG_RUN: case MEGA_MEGA_SET_FG_RUN: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; if (code == LITE_SET_FG_FG_RUN || code == MEGA_MEGA_SET_FG_RUN) { SRCREADPIXEL(fgPel, pbSrc); SRCNEXTPIXEL(pbSrc); } if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; if (fFirstLine) { UNROLL(runLength, { DESTWRITEPIXEL(pbDest, fgPel); DESTNEXTPIXEL(pbDest); }); } else { UNROLL(runLength, { DESTREADPIXEL(temp, pbDest - rowDelta); DESTWRITEPIXEL(pbDest, temp ^ fgPel); DESTNEXTPIXEL(pbDest); }); } break; /* Handle Dithered Run Orders. */ case LITE_DITHERED_RUN: case MEGA_MEGA_DITHERED_RUN: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; SRCREADPIXEL(pixelA, pbSrc); SRCNEXTPIXEL(pbSrc); SRCREADPIXEL(pixelB, pbSrc); SRCNEXTPIXEL(pbSrc); if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength * 2)) return FALSE; UNROLL(runLength, { DESTWRITEPIXEL(pbDest, pixelA); DESTNEXTPIXEL(pbDest); DESTWRITEPIXEL(pbDest, pixelB); DESTNEXTPIXEL(pbDest); }); break; /* Handle Color Run Orders. */ case REGULAR_COLOR_RUN: case MEGA_MEGA_COLOR_RUN: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; SRCREADPIXEL(pixelA, pbSrc); SRCNEXTPIXEL(pbSrc); if (!ENSURE_CAPACITY(pbDest, pbDestEnd, runLength)) return FALSE; UNROLL(runLength, { DESTWRITEPIXEL(pbDest, pixelA); DESTNEXTPIXEL(pbDest); }); break; /* Handle Foreground/Background Image Orders. */ case REGULAR_FGBG_IMAGE: case MEGA_MEGA_FGBG_IMAGE: case LITE_SET_FG_FGBG_IMAGE: case MEGA_MEGA_SET_FGBG_IMAGE: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; if (code == LITE_SET_FG_FGBG_IMAGE || code == MEGA_MEGA_SET_FGBG_IMAGE) { SRCREADPIXEL(fgPel, pbSrc); SRCNEXTPIXEL(pbSrc); } if (fFirstLine) { while (runLength > 8) { bitmask = *pbSrc; pbSrc = pbSrc + 1; pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, 8); if (!pbDest) return FALSE; runLength = runLength - 8; } } else { while (runLength > 8) { bitmask = *pbSrc; pbSrc = pbSrc + 1; pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, 8); if (!pbDest) return FALSE; runLength = runLength - 8; } } if (runLength > 0) { bitmask = *pbSrc; pbSrc = pbSrc + 1; if (fFirstLine) { pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, bitmask, fgPel, runLength); } else { pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, bitmask, fgPel, runLength); } if (!pbDest) return FALSE; } break; /* Handle Color Image Orders. */ case REGULAR_COLOR_IMAGE: case MEGA_MEGA_COLOR_IMAGE: runLength = ExtractRunLength(code, pbSrc, &advance); pbSrc = pbSrc + advance; UNROLL(runLength, { SRCREADPIXEL(temp, pbSrc); SRCNEXTPIXEL(pbSrc); DESTWRITEPIXEL(pbDest, temp); DESTNEXTPIXEL(pbDest); }); break; /* Handle Special Order 1. */ case SPECIAL_FGBG_1: pbSrc = pbSrc + 1; if (fFirstLine) { pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg1, fgPel, 8); } else { pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg1, fgPel, 8); } if (!pbDest) return FALSE; break; /* Handle Special Order 2. */ case SPECIAL_FGBG_2: pbSrc = pbSrc + 1; if (fFirstLine) { pbDest = WRITEFIRSTLINEFGBGIMAGE(pbDest, pbDestEnd, g_MaskSpecialFgBg2, fgPel, 8); } else { pbDest = WRITEFGBGIMAGE(pbDest, pbDestEnd, rowDelta, g_MaskSpecialFgBg2, fgPel, 8); } if (!pbDest) return FALSE; break; /* Handle White Order. */ case SPECIAL_WHITE: pbSrc = pbSrc + 1; if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, WHITE_PIXEL); DESTNEXTPIXEL(pbDest); break; /* Handle Black Order. */ case SPECIAL_BLACK: pbSrc = pbSrc + 1; if (!ENSURE_CAPACITY(pbDest, pbDestEnd, 1)) return FALSE; DESTWRITEPIXEL(pbDest, BLACK_PIXEL); DESTNEXTPIXEL(pbDest); break; default: return FALSE; } } return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Fix CVE-2020-11524: out of bounds access in interleaved Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: INLINE void gdi_RectToCRgn(const HGDI_RECT rect, INT32* x, INT32* y, INT32* w, INT32* h) { *x = rect->left; *y = rect->top; *w = rect->right - rect->left + 1; *h = rect->bottom - rect->top + 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fix CVE-2020-11523: clamp invalid rectangles to size 0 Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: rdpBitmapCache* bitmap_cache_new(rdpSettings* settings) { int i; rdpBitmapCache* bitmapCache; bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache)); if (!bitmapCache) return NULL; bitmapCache->settings = settings; bitmapCache->update = ((freerdp*)settings->instance)->update; bitmapCache->context = bitmapCache->update->context; bitmapCache->cells = (BITMAP_V2_CELL*)calloc(settings->BitmapCacheV2NumCells, sizeof(BITMAP_V2_CELL)); if (!bitmapCache->cells) goto fail; bitmapCache->maxCells = settings->BitmapCacheV2NumCells; for (i = 0; i < (int)bitmapCache->maxCells; i++) { bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries; /* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */ bitmapCache->cells[i].entries = (rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*)); if (!bitmapCache->cells[i].entries) goto fail; } return bitmapCache; fail: if (bitmapCache->cells) { for (i = 0; i < (int)bitmapCache->maxCells; i++) free(bitmapCache->cells[i].entries); } free(bitmapCache); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed CVE-2020-11525: Out of bounds read in bitmap_cache_new Thanks to Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide 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 update_recv_secondary_order(rdpUpdate* update, wStream* s, BYTE flags) { BOOL rc = FALSE; BYTE* next; BYTE orderType; UINT16 extraFlags; UINT16 orderLength; rdpContext* context = update->context; rdpSettings* settings = context->settings; rdpSecondaryUpdate* secondary = update->secondary; const char* name; if (Stream_GetRemainingLength(s) < 5) { WLog_Print(update->log, WLOG_ERROR, "Stream_GetRemainingLength(s) < 5"); return FALSE; } Stream_Read_UINT16(s, orderLength); /* orderLength (2 bytes) */ Stream_Read_UINT16(s, extraFlags); /* extraFlags (2 bytes) */ Stream_Read_UINT8(s, orderType); /* orderType (1 byte) */ next = Stream_Pointer(s) + ((INT16)orderLength) + 7; name = secondary_order_string(orderType); WLog_Print(update->log, WLOG_DEBUG, "Secondary Drawing Order %s", name); if (!check_secondary_order_supported(update->log, settings, orderType, name)) return FALSE; switch (orderType) { case ORDER_TYPE_BITMAP_UNCOMPRESSED: case ORDER_TYPE_CACHE_BITMAP_COMPRESSED: { const BOOL compressed = (orderType == ORDER_TYPE_CACHE_BITMAP_COMPRESSED); CACHE_BITMAP_ORDER* order = update_read_cache_bitmap_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmap, context, order); free_cache_bitmap_order(context, order); } } break; case ORDER_TYPE_BITMAP_UNCOMPRESSED_V2: case ORDER_TYPE_BITMAP_COMPRESSED_V2: { const BOOL compressed = (orderType == ORDER_TYPE_BITMAP_COMPRESSED_V2); CACHE_BITMAP_V2_ORDER* order = update_read_cache_bitmap_v2_order(update, s, compressed, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV2, context, order); free_cache_bitmap_v2_order(context, order); } } break; case ORDER_TYPE_BITMAP_COMPRESSED_V3: { CACHE_BITMAP_V3_ORDER* order = update_read_cache_bitmap_v3_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBitmapV3, context, order); free_cache_bitmap_v3_order(context, order); } } break; case ORDER_TYPE_CACHE_COLOR_TABLE: { CACHE_COLOR_TABLE_ORDER* order = update_read_cache_color_table_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheColorTable, context, order); free_cache_color_table_order(context, order); } } break; case ORDER_TYPE_CACHE_GLYPH: { switch (settings->GlyphSupportLevel) { case GLYPH_SUPPORT_PARTIAL: case GLYPH_SUPPORT_FULL: { CACHE_GLYPH_ORDER* order = update_read_cache_glyph_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyph, context, order); free_cache_glyph_order(context, order); } } break; case GLYPH_SUPPORT_ENCODE: { CACHE_GLYPH_V2_ORDER* order = update_read_cache_glyph_v2_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheGlyphV2, context, order); free_cache_glyph_v2_order(context, order); } } break; case GLYPH_SUPPORT_NONE: default: break; } } break; case ORDER_TYPE_CACHE_BRUSH: /* [MS-RDPEGDI] 2.2.2.2.1.2.7 Cache Brush (CACHE_BRUSH_ORDER) */ { CACHE_BRUSH_ORDER* order = update_read_cache_brush_order(update, s, extraFlags); if (order) { rc = IFCALLRESULT(FALSE, secondary->CacheBrush, context, order); free_cache_brush_order(context, order); } } break; default: WLog_Print(update->log, WLOG_WARN, "SECONDARY ORDER %s not supported", name); break; } if (!rc) { WLog_Print(update->log, WLOG_ERROR, "SECONDARY ORDER %s failed", name); } Stream_SetPointer(s, next); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fixed #6012: CVE-2020-11526: Out of bounds read in update_recv_orders Thanks to @hac425xxx and Sunglin and HuanGMz from Knownsec 404'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: auth_spa_server(auth_instance *ablock, uschar *data) { auth_spa_options_block *ob = (auth_spa_options_block *)(ablock->options_block); uint8x lmRespData[24]; uint8x ntRespData[24]; SPAAuthRequest request; SPAAuthChallenge challenge; SPAAuthResponse response; SPAAuthResponse *responseptr = &response; uschar msgbuf[2048]; uschar *clearpass; /* send a 334, MS Exchange style, and grab the client's request, unless we already have it via an initial response. */ if (!*data && auth_get_no64_data(&data, US"NTLM supported") != OK) return FAIL; if (spa_base64_to_bits(CS &request, sizeof(request), CCS data) < 0) { DEBUG(D_auth) debug_printf("auth_spa_server(): bad base64 data in " "request: %s\n", data); return FAIL; } /* create a challenge and send it back */ spa_build_auth_challenge(&request, &challenge); spa_bits_to_base64(msgbuf, US &challenge, spa_request_length(&challenge)); if (auth_get_no64_data(&data, msgbuf) != OK) return FAIL; /* dump client response */ if (spa_base64_to_bits(CS &response, sizeof(response), CCS data) < 0) { DEBUG(D_auth) debug_printf("auth_spa_server(): bad base64 data in " "response: %s\n", data); return FAIL; } /*************************************************************** PH 07-Aug-2003: The original code here was this: Ustrcpy(msgbuf, unicodeToString(((char*)responseptr) + IVAL(&responseptr->uUser.offset,0), SVAL(&responseptr->uUser.len,0)/2) ); However, if the response data is too long, unicodeToString bombs out on an assertion failure. It uses a 1024 fixed buffer. Bombing out is not a good idea. It's too messy to try to rework that function to return an error because it is called from a number of other places in the auth-spa.c module. Instead, since it is a very small function, I reproduce its code here, with a size check that causes failure if the size of msgbuf is exceeded. ****/ { int i; char * p = (CS responseptr) + IVAL(&responseptr->uUser.offset,0); int len = SVAL(&responseptr->uUser.len,0)/2; if (len + 1 >= sizeof(msgbuf)) return FAIL; for (i = 0; i < len; ++i) { msgbuf[i] = *p & 0x7f; p += 2; } msgbuf[i] = 0; } /***************************************************************/ /* Put the username in $auth1 and $1. The former is now the preferred variable; the latter is the original variable. These have to be out of stack memory, and need to be available once known even if not authenticated, for error messages (server_set_id, which only makes it to authenticated_id if we return OK) */ auth_vars[0] = expand_nstring[1] = string_copy(msgbuf); expand_nlength[1] = Ustrlen(msgbuf); expand_nmax = 1; debug_print_string(ablock->server_debug_string); /* customized debug */ /* look up password */ if (!(clearpass = expand_string(ob->spa_serverpassword))) if (f.expand_string_forcedfail) { DEBUG(D_auth) debug_printf("auth_spa_server(): forced failure while " "expanding spa_serverpassword\n"); return FAIL; } else { DEBUG(D_auth) debug_printf("auth_spa_server(): error while expanding " "spa_serverpassword: %s\n", expand_string_message); return DEFER; } /* create local hash copy */ spa_smb_encrypt(clearpass, challenge.challengeData, lmRespData); spa_smb_nt_encrypt(clearpass, challenge.challengeData, ntRespData); /* compare NT hash (LM may not be available) */ if (memcmp(ntRespData, (US responseptr)+IVAL(&responseptr->ntResponse.offset,0), 24) == 0) return auth_check_serv_cond(ablock); /* success. we have a winner. */ /* Expand server_condition as an authorization check (PH) */ return FAIL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix SPA authenticator, checking client-supplied data before using it. Bug 2571'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: spa_bits_to_base64 (uschar *out, const uschar *in, int inlen) /* raw bytes in quasi-big-endian order to base 64 string (NUL-terminated) */ { for (; inlen >= 3; inlen -= 3) { *out++ = base64digits[in[0] >> 2]; *out++ = base64digits[((in[0] << 4) & 0x30) | (in[1] >> 4)]; *out++ = base64digits[((in[1] << 2) & 0x3c) | (in[2] >> 6)]; *out++ = base64digits[in[2] & 0x3f]; in += 3; } if (inlen > 0) { uschar fragment; *out++ = base64digits[in[0] >> 2]; fragment = (in[0] << 4) & 0x30; if (inlen > 1) fragment |= in[1] >> 4; *out++ = base64digits[fragment]; *out++ = (inlen < 2) ? '=' : base64digits[(in[1] << 2) & 0x3c]; *out++ = '='; } *out = '\0'; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix SPA authenticator, checking client-supplied data before using it. Bug 2571'</s>
<s>[INST] Given the following code containing errors, provide 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 nodeDestruct(struct SaveNode* node) { if (node->v == &node->sorted) { tr_free(node->sorted.val.l.vals); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-284'], 'message': 'CVE-2018-10756: Fix heap-use-after-free in tr_variantWalk In libtransmission/variant.c, function tr_variantWalk, when the variant stack is reallocated, a pointer to the previously allocated memory region is kept. This address is later accessed (heap use-after-free) while walking back down the stack, causing the application to crash. The application can be any application which uses libtransmission, such as transmission-daemon, transmission-gtk, transmission-show, etc. Reported-by: Tom Richards <tom@tomrichards.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: error_supers(struct module_qstate* qstate, int id, struct module_qstate* super) { struct iter_qstate* super_iq = (struct iter_qstate*)super->minfo[id]; if(qstate->qinfo.qtype == LDNS_RR_TYPE_A || qstate->qinfo.qtype == LDNS_RR_TYPE_AAAA) { /* mark address as failed. */ struct delegpt_ns* dpns = NULL; super_iq->num_target_queries--; if(super_iq->dp) dpns = delegpt_find_ns(super_iq->dp, qstate->qinfo.qname, qstate->qinfo.qname_len); if(!dpns) { /* not interested */ /* this can happen, for eg. qname minimisation asked * for an NXDOMAIN to be validated, and used qtype * A for that, and the error of that, the name, is * not listed in super_iq->dp */ verbose(VERB_ALGO, "subq error, but not interested"); log_query_info(VERB_ALGO, "superq", &super->qinfo); return; } else { /* see if the failure did get (parent-lame) info */ if(!cache_fill_missing(super->env, super_iq->qchase.qclass, super->region, super_iq->dp)) log_err("out of memory adding missing"); } dpns->resolved = 1; /* mark as failed */ } if(qstate->qinfo.qtype == LDNS_RR_TYPE_NS) { /* prime failed to get delegation */ super_iq->dp = NULL; } /* evaluate targets again */ super_iq->state = QUERYTARGETS_STATE; /* super becomes runnable, and will process this change */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide 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 delegpt_add_neg_msg(struct delegpt* dp, struct msgreply_entry* msg) { struct reply_info* rep = (struct reply_info*)msg->entry.data; if(!rep) return; /* if error or no answers */ if(FLAGS_GET_RCODE(rep->flags) != 0 || rep->an_numrrsets == 0) { struct delegpt_ns* ns = delegpt_find_ns(dp, msg->key.qname, msg->key.qname_len); if(ns) { if(msg->key.qtype == LDNS_RR_TYPE_A) ns->got4 = 1; else if(msg->key.qtype == LDNS_RR_TYPE_AAAA) ns->got6 = 1; if(ns->got4 && ns->got6) ns->resolved = 1; } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: dname_pkt_compare(sldns_buffer* pkt, uint8_t* d1, uint8_t* d2) { uint8_t len1, len2; log_assert(pkt && d1 && d2); len1 = *d1++; len2 = *d2++; while( len1 != 0 || len2 != 0 ) { /* resolve ptrs */ if(LABEL_IS_PTR(len1)) { d1 = sldns_buffer_at(pkt, PTR_OFFSET(len1, *d1)); len1 = *d1++; continue; } if(LABEL_IS_PTR(len2)) { d2 = sldns_buffer_at(pkt, PTR_OFFSET(len2, *d2)); len2 = *d2++; continue; } /* check label length */ log_assert(len1 <= LDNS_MAX_LABELLEN); log_assert(len2 <= LDNS_MAX_LABELLEN); if(len1 != len2) { if(len1 < len2) return -1; return 1; } log_assert(len1 == len2 && len1 != 0); /* compare labels */ while(len1--) { if(tolower((unsigned char)*d1) != tolower((unsigned char)*d2)) { if(tolower((unsigned char)*d1) < tolower((unsigned char)*d2)) return -1; return 1; } d1++; d2++; } len1 = *d1++; len2 = *d2++; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: delegpt_from_message(struct dns_msg* msg, struct regional* region) { struct ub_packed_rrset_key* ns_rrset = NULL; struct delegpt* dp; size_t i; /* look for NS records in the authority section... */ ns_rrset = find_NS(msg->rep, msg->rep->an_numrrsets, msg->rep->an_numrrsets+msg->rep->ns_numrrsets); /* In some cases (even legitimate, perfectly legal cases), the * NS set for the "referral" might be in the answer section. */ if(!ns_rrset) ns_rrset = find_NS(msg->rep, 0, msg->rep->an_numrrsets); /* If there was no NS rrset in the authority section, then this * wasn't a referral message. (It might not actually be a * referral message anyway) */ if(!ns_rrset) return NULL; /* If we found any, then Yay! we have a delegation point. */ dp = delegpt_create(region); if(!dp) return NULL; dp->has_parent_side_NS = 1; /* created from message */ if(!delegpt_set_name(dp, region, ns_rrset->rk.dname)) return NULL; if(!delegpt_rrset_add_ns(dp, region, ns_rrset, 0)) return NULL; /* add glue, A and AAAA in answer and additional section */ for(i=0; i<msg->rep->rrset_count; i++) { struct ub_packed_rrset_key* s = msg->rep->rrsets[i]; /* skip auth section. FIXME really needed?*/ if(msg->rep->an_numrrsets <= i && i < (msg->rep->an_numrrsets+msg->rep->ns_numrrsets)) continue; if(ntohs(s->rk.type) == LDNS_RR_TYPE_A) { if(!delegpt_add_rrset_A(dp, region, s, 0)) return NULL; } else if(ntohs(s->rk.type) == LDNS_RR_TYPE_AAAA) { if(!delegpt_add_rrset_AAAA(dp, region, s, 0)) return NULL; } } return dp; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: processLastResort(struct module_qstate* qstate, struct iter_qstate* iq, struct iter_env* ie, int id) { struct delegpt_ns* ns; int query_count = 0; verbose(VERB_ALGO, "No more query targets, attempting last resort"); log_assert(iq->dp); if(!can_have_last_resort(qstate->env, iq->dp->name, iq->dp->namelen, iq->qchase.qclass, NULL)) { /* fail -- no more targets, no more hope of targets, no hope * of a response. */ errinf(qstate, "all the configured stub or forward servers failed,"); errinf_dname(qstate, "at zone", iq->dp->name); verbose(VERB_QUERY, "configured stub or forward servers failed -- returning SERVFAIL"); return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); } if(!iq->dp->has_parent_side_NS && dname_is_root(iq->dp->name)) { struct delegpt* p = hints_lookup_root(qstate->env->hints, iq->qchase.qclass); if(p) { struct delegpt_addr* a; iq->chase_flags &= ~BIT_RD; /* go to authorities */ for(ns = p->nslist; ns; ns=ns->next) { (void)delegpt_add_ns(iq->dp, qstate->region, ns->name, ns->lame); } for(a = p->target_list; a; a=a->next_target) { (void)delegpt_add_addr(iq->dp, qstate->region, &a->addr, a->addrlen, a->bogus, a->lame, a->tls_auth_name); } } iq->dp->has_parent_side_NS = 1; } else if(!iq->dp->has_parent_side_NS) { if(!iter_lookup_parent_NS_from_cache(qstate->env, iq->dp, qstate->region, &qstate->qinfo) || !iq->dp->has_parent_side_NS) { /* if: malloc failure in lookup go up to try */ /* if: no parent NS in cache - go up one level */ verbose(VERB_ALGO, "try to grab parent NS"); iq->store_parent_NS = iq->dp; iq->chase_flags &= ~BIT_RD; /* go to authorities */ iq->deleg_msg = NULL; iq->refetch_glue = 1; iq->query_restart_count++; iq->sent_count = 0; if(qstate->env->cfg->qname_minimisation) iq->minimisation_state = INIT_MINIMISE_STATE; return next_state(iq, INIT_REQUEST_STATE); } } /* see if that makes new names available */ if(!cache_fill_missing(qstate->env, iq->qchase.qclass, qstate->region, iq->dp)) log_err("out of memory in cache_fill_missing"); if(iq->dp->usable_list) { verbose(VERB_ALGO, "try parent-side-name, w. glue from cache"); return next_state(iq, QUERYTARGETS_STATE); } /* try to fill out parent glue from cache */ if(iter_lookup_parent_glue_from_cache(qstate->env, iq->dp, qstate->region, &qstate->qinfo)) { /* got parent stuff from cache, see if we can continue */ verbose(VERB_ALGO, "try parent-side glue from cache"); return next_state(iq, QUERYTARGETS_STATE); } /* query for an extra name added by the parent-NS record */ if(delegpt_count_missing_targets(iq->dp) > 0) { int qs = 0; verbose(VERB_ALGO, "try parent-side target name"); if(!query_for_targets(qstate, iq, ie, id, 1, &qs)) { errinf(qstate, "could not fetch nameserver"); errinf_dname(qstate, "at zone", iq->dp->name); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } iq->num_target_queries += qs; target_count_increase(iq, qs); if(qs != 0) { qstate->ext_state[id] = module_wait_subquery; return 0; /* and wait for them */ } } if(iq->depth == ie->max_dependency_depth) { verbose(VERB_QUERY, "maxdepth and need more nameservers, fail"); errinf(qstate, "cannot fetch more nameservers because at max dependency depth"); return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); } if(iq->depth > 0 && iq->target_count && iq->target_count[1] > MAX_TARGET_COUNT) { char s[LDNS_MAX_DOMAINLEN+1]; dname_str(qstate->qinfo.qname, s); verbose(VERB_QUERY, "request %s has exceeded the maximum " "number of glue fetches %d", s, iq->target_count[1]); errinf(qstate, "exceeded the maximum number of glue fetches"); return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); } /* mark cycle targets for parent-side lookups */ iter_mark_pside_cycle_targets(qstate, iq->dp); /* see if we can issue queries to get nameserver addresses */ /* this lookup is not randomized, but sequential. */ for(ns = iq->dp->nslist; ns; ns = ns->next) { /* if this nameserver is at a delegation point, but that * delegation point is a stub and we cannot go higher, skip*/ if( ((ie->supports_ipv6 && !ns->done_pside6) || (ie->supports_ipv4 && !ns->done_pside4)) && !can_have_last_resort(qstate->env, ns->name, ns->namelen, iq->qchase.qclass, NULL)) { log_nametypeclass(VERB_ALGO, "cannot pside lookup ns " "because it is also a stub/forward,", ns->name, LDNS_RR_TYPE_NS, iq->qchase.qclass); if(ie->supports_ipv6) ns->done_pside6 = 1; if(ie->supports_ipv4) ns->done_pside4 = 1; continue; } /* query for parent-side A and AAAA for nameservers */ if(ie->supports_ipv6 && !ns->done_pside6) { /* Send the AAAA request. */ if(!generate_parentside_target_query(qstate, iq, id, ns->name, ns->namelen, LDNS_RR_TYPE_AAAA, iq->qchase.qclass)) { errinf_dname(qstate, "could not generate nameserver AAAA lookup for", ns->name); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } ns->done_pside6 = 1; query_count++; } if(ie->supports_ipv4 && !ns->done_pside4) { /* Send the A request. */ if(!generate_parentside_target_query(qstate, iq, id, ns->name, ns->namelen, LDNS_RR_TYPE_A, iq->qchase.qclass)) { errinf_dname(qstate, "could not generate nameserver A lookup for", ns->name); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } ns->done_pside4 = 1; query_count++; } if(query_count != 0) { /* suspend to await results */ verbose(VERB_ALGO, "try parent-side glue lookup"); iq->num_target_queries += query_count; target_count_increase(iq, query_count); qstate->ext_state[id] = module_wait_subquery; return 0; } } /* if this was a parent-side glue query itself, then store that * failure in cache. */ if(!qstate->no_cache_store && iq->query_for_pside_glue && !iq->pside_glue) iter_store_parentside_neg(qstate->env, &qstate->qinfo, iq->deleg_msg?iq->deleg_msg->rep: (iq->response?iq->response->rep:NULL)); errinf(qstate, "all servers for this domain failed,"); errinf_dname(qstate, "at zone", iq->dp->name); verbose(VERB_QUERY, "out of query targets -- returning SERVFAIL"); /* fail -- no more targets, no more hope of targets, no hope * of a response. */ return error_response_cache(qstate, id, LDNS_RCODE_SERVFAIL); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: processCollectClass(struct module_qstate* qstate, int id) { struct iter_qstate* iq = (struct iter_qstate*)qstate->minfo[id]; struct module_qstate* subq; /* If qchase.qclass == 0 then send out queries for all classes. * Otherwise, do nothing (wait for all answers to arrive and the * processClassResponse to put them together, and that moves us * towards the Finished state when done. */ if(iq->qchase.qclass == 0) { uint16_t c = 0; iq->qchase.qclass = LDNS_RR_CLASS_ANY; while(iter_get_next_root(qstate->env->hints, qstate->env->fwds, &c)) { /* generate query for this class */ log_nametypeclass(VERB_ALGO, "spawn collect query", qstate->qinfo.qname, qstate->qinfo.qtype, c); if(!generate_sub_request(qstate->qinfo.qname, qstate->qinfo.qname_len, qstate->qinfo.qtype, c, qstate, id, iq, INIT_REQUEST_STATE, FINISHED_STATE, &subq, (int)!(qstate->query_flags&BIT_CD))) { errinf(qstate, "could not generate class ANY" " lookup query"); return error_response(qstate, id, LDNS_RCODE_SERVFAIL); } /* ignore subq, no special init required */ iq->num_current_queries ++; if(c == 0xffff) break; else c++; } /* if no roots are configured at all, return */ if(iq->num_current_queries == 0) { verbose(VERB_ALGO, "No root hints or fwds, giving up " "on qclass ANY"); return error_response(qstate, id, LDNS_RCODE_REFUSED); } /* return false, wait for queries to return */ } /* if woke up here because of an answer, wait for more answers */ return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: target_count_increase(struct iter_qstate* iq, int num) { target_count_create(iq); if(iq->target_count) iq->target_count[1] += num; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400'], 'message': '- CVE-2020-12662 Unbound can be tricked into amplifying an incoming query into a large number of queries directed to a target. - CVE-2020-12663 Malformed answers from upstream name servers can be used to make Unbound unresponsive.'</s>