instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[4],b[0],c2,c3,c1); mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); mul_add_c(a[0],b[4],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[0],b[5],c3,c1,c2); mul_add_c(a[1],b[4],c3,c1,c2); mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); mul_add_c(a[4],b[1],c3,c1,c2); mul_add_c(a[5],b[0],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[6],b[0],c1,c2,c3); mul_add_c(a[5],b[1],c1,c2,c3); mul_add_c(a[4],b[2],c1,c2,c3); mul_add_c(a[3],b[3],c1,c2,c3); mul_add_c(a[2],b[4],c1,c2,c3); mul_add_c(a[1],b[5],c1,c2,c3); mul_add_c(a[0],b[6],c1,c2,c3); r[6]=c1; c1=0; mul_add_c(a[0],b[7],c2,c3,c1); mul_add_c(a[1],b[6],c2,c3,c1); mul_add_c(a[2],b[5],c2,c3,c1); mul_add_c(a[3],b[4],c2,c3,c1); mul_add_c(a[4],b[3],c2,c3,c1); mul_add_c(a[5],b[2],c2,c3,c1); mul_add_c(a[6],b[1],c2,c3,c1); mul_add_c(a[7],b[0],c2,c3,c1); r[7]=c2; c2=0; mul_add_c(a[7],b[1],c3,c1,c2); mul_add_c(a[6],b[2],c3,c1,c2); mul_add_c(a[5],b[3],c3,c1,c2); mul_add_c(a[4],b[4],c3,c1,c2); mul_add_c(a[3],b[5],c3,c1,c2); mul_add_c(a[2],b[6],c3,c1,c2); mul_add_c(a[1],b[7],c3,c1,c2); r[8]=c3; c3=0; mul_add_c(a[2],b[7],c1,c2,c3); mul_add_c(a[3],b[6],c1,c2,c3); mul_add_c(a[4],b[5],c1,c2,c3); mul_add_c(a[5],b[4],c1,c2,c3); mul_add_c(a[6],b[3],c1,c2,c3); mul_add_c(a[7],b[2],c1,c2,c3); r[9]=c1; c1=0; mul_add_c(a[7],b[3],c2,c3,c1); mul_add_c(a[6],b[4],c2,c3,c1); mul_add_c(a[5],b[5],c2,c3,c1); mul_add_c(a[4],b[6],c2,c3,c1); mul_add_c(a[3],b[7],c2,c3,c1); r[10]=c2; c2=0; mul_add_c(a[4],b[7],c3,c1,c2); mul_add_c(a[5],b[6],c3,c1,c2); mul_add_c(a[6],b[5],c3,c1,c2); mul_add_c(a[7],b[4],c3,c1,c2); r[11]=c3; c3=0; mul_add_c(a[7],b[5],c1,c2,c3); mul_add_c(a[6],b[6],c1,c2,c3); mul_add_c(a[5],b[7],c1,c2,c3); r[12]=c1; c1=0; mul_add_c(a[6],b[7],c2,c3,c1); mul_add_c(a[7],b[6],c2,c3,c1); r[13]=c2; c2=0; mul_add_c(a[7],b[7],c3,c1,c2); r[14]=c3; r[15]=c1; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <[email protected]> CWE ID: CWE-310
void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; mul_add_c(a[0],b[0],c1,c2,c3); r[0]=c1; c1=0; mul_add_c(a[0],b[1],c2,c3,c1); mul_add_c(a[1],b[0],c2,c3,c1); r[1]=c2; c2=0; mul_add_c(a[2],b[0],c3,c1,c2); mul_add_c(a[1],b[1],c3,c1,c2); mul_add_c(a[0],b[2],c3,c1,c2); r[2]=c3; c3=0; mul_add_c(a[0],b[3],c1,c2,c3); mul_add_c(a[1],b[2],c1,c2,c3); mul_add_c(a[2],b[1],c1,c2,c3); mul_add_c(a[3],b[0],c1,c2,c3); r[3]=c1; c1=0; mul_add_c(a[4],b[0],c2,c3,c1); mul_add_c(a[3],b[1],c2,c3,c1); mul_add_c(a[2],b[2],c2,c3,c1); mul_add_c(a[1],b[3],c2,c3,c1); mul_add_c(a[0],b[4],c2,c3,c1); r[4]=c2; c2=0; mul_add_c(a[0],b[5],c3,c1,c2); mul_add_c(a[1],b[4],c3,c1,c2); mul_add_c(a[2],b[3],c3,c1,c2); mul_add_c(a[3],b[2],c3,c1,c2); mul_add_c(a[4],b[1],c3,c1,c2); mul_add_c(a[5],b[0],c3,c1,c2); r[5]=c3; c3=0; mul_add_c(a[6],b[0],c1,c2,c3); mul_add_c(a[5],b[1],c1,c2,c3); mul_add_c(a[4],b[2],c1,c2,c3); mul_add_c(a[3],b[3],c1,c2,c3); mul_add_c(a[2],b[4],c1,c2,c3); mul_add_c(a[1],b[5],c1,c2,c3); mul_add_c(a[0],b[6],c1,c2,c3); r[6]=c1; c1=0; mul_add_c(a[0],b[7],c2,c3,c1); mul_add_c(a[1],b[6],c2,c3,c1); mul_add_c(a[2],b[5],c2,c3,c1); mul_add_c(a[3],b[4],c2,c3,c1); mul_add_c(a[4],b[3],c2,c3,c1); mul_add_c(a[5],b[2],c2,c3,c1); mul_add_c(a[6],b[1],c2,c3,c1); mul_add_c(a[7],b[0],c2,c3,c1); r[7]=c2; c2=0; mul_add_c(a[7],b[1],c3,c1,c2); mul_add_c(a[6],b[2],c3,c1,c2); mul_add_c(a[5],b[3],c3,c1,c2); mul_add_c(a[4],b[4],c3,c1,c2); mul_add_c(a[3],b[5],c3,c1,c2); mul_add_c(a[2],b[6],c3,c1,c2); mul_add_c(a[1],b[7],c3,c1,c2); r[8]=c3; c3=0; mul_add_c(a[2],b[7],c1,c2,c3); mul_add_c(a[3],b[6],c1,c2,c3); mul_add_c(a[4],b[5],c1,c2,c3); mul_add_c(a[5],b[4],c1,c2,c3); mul_add_c(a[6],b[3],c1,c2,c3); mul_add_c(a[7],b[2],c1,c2,c3); r[9]=c1; c1=0; mul_add_c(a[7],b[3],c2,c3,c1); mul_add_c(a[6],b[4],c2,c3,c1); mul_add_c(a[5],b[5],c2,c3,c1); mul_add_c(a[4],b[6],c2,c3,c1); mul_add_c(a[3],b[7],c2,c3,c1); r[10]=c2; c2=0; mul_add_c(a[4],b[7],c3,c1,c2); mul_add_c(a[5],b[6],c3,c1,c2); mul_add_c(a[6],b[5],c3,c1,c2); mul_add_c(a[7],b[4],c3,c1,c2); r[11]=c3; c3=0; mul_add_c(a[7],b[5],c1,c2,c3); mul_add_c(a[6],b[6],c1,c2,c3); mul_add_c(a[5],b[7],c1,c2,c3); r[12]=c1; c1=0; mul_add_c(a[6],b[7],c2,c3,c1); mul_add_c(a[7],b[6],c2,c3,c1); r[13]=c2; c2=0; mul_add_c(a[7],b[7],c3,c1,c2); r[14]=c3; r[15]=c1; }
166,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PrintMsg_Print_Params::PrintMsg_Print_Params() : page_size(), content_size(), printable_area(), margin_top(0), margin_left(0), dpi(0), scale_factor(1.0f), rasterize_pdf(false), document_cookie(0), selection_only(false), supports_alpha_blend(false), preview_ui_id(-1), preview_request_id(0), is_first_request(false), print_scaling_option(blink::kWebPrintScalingOptionSourceSize), print_to_pdf(false), display_header_footer(false), title(), url(), should_print_backgrounds(false), printed_doc_type(printing::SkiaDocumentType::PDF) {} Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
PrintMsg_Print_Params::PrintMsg_Print_Params() : page_size(), content_size(), printable_area(), margin_top(0), margin_left(0), dpi(0), scale_factor(1.0f), rasterize_pdf(false), document_cookie(0), selection_only(false), supports_alpha_blend(false), preview_ui_id(-1), preview_request_id(0), is_first_request(false), print_scaling_option(blink::kWebPrintScalingOptionSourceSize), print_to_pdf(false), display_header_footer(false), title(), url(), header_template(), footer_template(), should_print_backgrounds(false), printed_doc_type(printing::SkiaDocumentType::PDF) {}
172,897
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SampleTable::isValid() const { return mChunkOffsetOffset >= 0 && mSampleToChunkOffset >= 0 && mSampleSizeOffset >= 0 && mTimeToSample != NULL; } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
bool SampleTable::isValid() const { return mChunkOffsetOffset >= 0 && mSampleToChunkOffset >= 0 && mSampleSizeOffset >= 0 && !mTimeToSample.empty(); }
174,172
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pixHtmlViewer(const char *dirin, const char *dirout, const char *rootname, l_int32 thumbwidth, l_int32 viewwidth) { char *fname, *fullname, *outname; char *mainname, *linkname, *linknameshort; char *viewfile, *thumbfile; char *shtml, *slink; char charbuf[512]; char htmlstring[] = "<html>"; char framestring[] = "</frameset></html>"; l_int32 i, nfiles, index, w, d, nimages, ret; l_float32 factor; PIX *pix, *pixthumb, *pixview; SARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink; PROCNAME("pixHtmlViewer"); if (!dirin) return ERROR_INT("dirin not defined", procName, 1); if (!dirout) return ERROR_INT("dirout not defined", procName, 1); if (!rootname) return ERROR_INT("rootname not defined", procName, 1); if (thumbwidth == 0) thumbwidth = DEFAULT_THUMB_WIDTH; if (thumbwidth < MIN_THUMB_WIDTH) { L_WARNING("thumbwidth too small; using min value\n", procName); thumbwidth = MIN_THUMB_WIDTH; } if (viewwidth == 0) viewwidth = DEFAULT_VIEW_WIDTH; if (viewwidth < MIN_VIEW_WIDTH) { L_WARNING("viewwidth too small; using min value\n", procName); viewwidth = MIN_VIEW_WIDTH; } /* Make the output directory if it doesn't already exist */ #ifndef _WIN32 snprintf(charbuf, sizeof(charbuf), "mkdir -p %s", dirout); ret = system(charbuf); #else ret = CreateDirectory(dirout, NULL) ? 0 : 1; #endif /* !_WIN32 */ if (ret) { L_ERROR("output directory %s not made\n", procName, dirout); return 1; } /* Capture the filenames in the input directory */ if ((safiles = getFilenamesInDirectory(dirin)) == NULL) return ERROR_INT("safiles not made", procName, 1); /* Generate output text file names */ sprintf(charbuf, "%s/%s.html", dirout, rootname); mainname = stringNew(charbuf); sprintf(charbuf, "%s/%s-links.html", dirout, rootname); linkname = stringNew(charbuf); linknameshort = stringJoin(rootname, "-links.html"); /* Generate the thumbs and views */ sathumbs = sarrayCreate(0); saviews = sarrayCreate(0); nfiles = sarrayGetCount(safiles); index = 0; for (i = 0; i < nfiles; i++) { fname = sarrayGetString(safiles, i, L_NOCOPY); fullname = genPathname(dirin, fname); fprintf(stderr, "name: %s\n", fullname); if ((pix = pixRead(fullname)) == NULL) { fprintf(stderr, "file %s not a readable image\n", fullname); lept_free(fullname); continue; } lept_free(fullname); /* Make and store the thumbnail images */ pixGetDimensions(pix, &w, NULL, &d); factor = (l_float32)thumbwidth / (l_float32)w; pixthumb = pixScale(pix, factor, factor); sprintf(charbuf, "%s_thumb_%03d", rootname, index); sarrayAddString(sathumbs, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixthumb); lept_free(outname); pixDestroy(&pixthumb); /* Make and store the view images */ factor = (l_float32)viewwidth / (l_float32)w; if (factor >= 1.0) pixview = pixClone(pix); /* no upscaling */ else pixview = pixScale(pix, factor, factor); snprintf(charbuf, sizeof(charbuf), "%s_view_%03d", rootname, index); sarrayAddString(saviews, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixview); lept_free(outname); pixDestroy(&pixview); pixDestroy(&pix); index++; } /* Generate the main html file */ sahtml = sarrayCreate(0); sarrayAddString(sahtml, htmlstring, L_COPY); sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"views\" src=\"%s\">", sarrayGetString(saviews, 0, L_NOCOPY)); sarrayAddString(sahtml, charbuf, L_COPY); sarrayAddString(sahtml, framestring, L_COPY); shtml = sarrayToString(sahtml, 1); l_binaryWrite(mainname, "w", shtml, strlen(shtml)); fprintf(stderr, "******************************************\n" "Writing html file: %s\n" "******************************************\n", mainname); lept_free(shtml); lept_free(mainname); /* Generate the link html file */ nimages = sarrayGetCount(saviews); fprintf(stderr, "num. images = %d\n", nimages); salink = sarrayCreate(0); for (i = 0; i < nimages; i++) { viewfile = sarrayGetString(saviews, i, L_NOCOPY); thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY); sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>", viewfile, thumbfile); sarrayAddString(salink, charbuf, L_COPY); } slink = sarrayToString(salink, 1); l_binaryWrite(linkname, "w", slink, strlen(slink)); lept_free(slink); lept_free(linkname); lept_free(linknameshort); sarrayDestroy(&safiles); sarrayDestroy(&sathumbs); sarrayDestroy(&saviews); sarrayDestroy(&sahtml); sarrayDestroy(&salink); return 0; } Commit Message: prog/htmlviewer: Catch unbound memory access (CID 1386222) rootname can have any size, so limit the amount of copied bytes. Signed-off-by: Stefan Weil <[email protected]> CWE ID: CWE-119
pixHtmlViewer(const char *dirin, const char *dirout, const char *rootname, l_int32 thumbwidth, l_int32 viewwidth) { char *fname, *fullname, *outname; char *mainname, *linkname, *linknameshort; char *viewfile, *thumbfile; char *shtml, *slink; char charbuf[512]; char htmlstring[] = "<html>"; char framestring[] = "</frameset></html>"; l_int32 i, nfiles, index, w, d, nimages, ret; l_float32 factor; PIX *pix, *pixthumb, *pixview; SARRAY *safiles, *sathumbs, *saviews, *sahtml, *salink; PROCNAME("pixHtmlViewer"); if (!dirin) return ERROR_INT("dirin not defined", procName, 1); if (!dirout) return ERROR_INT("dirout not defined", procName, 1); if (!rootname) return ERROR_INT("rootname not defined", procName, 1); if (thumbwidth == 0) thumbwidth = DEFAULT_THUMB_WIDTH; if (thumbwidth < MIN_THUMB_WIDTH) { L_WARNING("thumbwidth too small; using min value\n", procName); thumbwidth = MIN_THUMB_WIDTH; } if (viewwidth == 0) viewwidth = DEFAULT_VIEW_WIDTH; if (viewwidth < MIN_VIEW_WIDTH) { L_WARNING("viewwidth too small; using min value\n", procName); viewwidth = MIN_VIEW_WIDTH; } /* Make the output directory if it doesn't already exist */ #ifndef _WIN32 snprintf(charbuf, sizeof(charbuf), "mkdir -p %s", dirout); ret = system(charbuf); #else ret = CreateDirectory(dirout, NULL) ? 0 : 1; #endif /* !_WIN32 */ if (ret) { L_ERROR("output directory %s not made\n", procName, dirout); return 1; } /* Capture the filenames in the input directory */ if ((safiles = getFilenamesInDirectory(dirin)) == NULL) return ERROR_INT("safiles not made", procName, 1); /* Generate output text file names */ snprintf(charbuf, sizeof(charbuf), "%s/%s.html", dirout, rootname); mainname = stringNew(charbuf); snprintf(charbuf, sizeof(charbuf), "%s/%s-links.html", dirout, rootname); linkname = stringNew(charbuf); linknameshort = stringJoin(rootname, "-links.html"); /* Generate the thumbs and views */ sathumbs = sarrayCreate(0); saviews = sarrayCreate(0); nfiles = sarrayGetCount(safiles); index = 0; for (i = 0; i < nfiles; i++) { fname = sarrayGetString(safiles, i, L_NOCOPY); fullname = genPathname(dirin, fname); fprintf(stderr, "name: %s\n", fullname); if ((pix = pixRead(fullname)) == NULL) { fprintf(stderr, "file %s not a readable image\n", fullname); lept_free(fullname); continue; } lept_free(fullname); /* Make and store the thumbnail images */ pixGetDimensions(pix, &w, NULL, &d); factor = (l_float32)thumbwidth / (l_float32)w; pixthumb = pixScale(pix, factor, factor); snprintf(charbuf, sizeof(charbuf), "%s_thumb_%03d", rootname, index); sarrayAddString(sathumbs, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixthumb); lept_free(outname); pixDestroy(&pixthumb); /* Make and store the view images */ factor = (l_float32)viewwidth / (l_float32)w; if (factor >= 1.0) pixview = pixClone(pix); /* no upscaling */ else pixview = pixScale(pix, factor, factor); snprintf(charbuf, sizeof(charbuf), "%s_view_%03d", rootname, index); sarrayAddString(saviews, charbuf, L_COPY); outname = genPathname(dirout, charbuf); WriteFormattedPix(outname, pixview); lept_free(outname); pixDestroy(&pixview); pixDestroy(&pix); index++; } /* Generate the main html file */ sahtml = sarrayCreate(0); sarrayAddString(sahtml, htmlstring, L_COPY); sprintf(charbuf, "<frameset cols=\"%d, *\">", thumbwidth + 30); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"thumbs\" src=\"%s\">", linknameshort); sarrayAddString(sahtml, charbuf, L_COPY); sprintf(charbuf, "<frame name=\"views\" src=\"%s\">", sarrayGetString(saviews, 0, L_NOCOPY)); sarrayAddString(sahtml, charbuf, L_COPY); sarrayAddString(sahtml, framestring, L_COPY); shtml = sarrayToString(sahtml, 1); l_binaryWrite(mainname, "w", shtml, strlen(shtml)); fprintf(stderr, "******************************************\n" "Writing html file: %s\n" "******************************************\n", mainname); lept_free(shtml); lept_free(mainname); /* Generate the link html file */ nimages = sarrayGetCount(saviews); fprintf(stderr, "num. images = %d\n", nimages); salink = sarrayCreate(0); for (i = 0; i < nimages; i++) { viewfile = sarrayGetString(saviews, i, L_NOCOPY); thumbfile = sarrayGetString(sathumbs, i, L_NOCOPY); sprintf(charbuf, "<a href=\"%s\" TARGET=views><img src=\"%s\"></a>", viewfile, thumbfile); sarrayAddString(salink, charbuf, L_COPY); } slink = sarrayToString(salink, 1); l_binaryWrite(linkname, "w", slink, strlen(slink)); lept_free(slink); lept_free(linkname); lept_free(linknameshort); sarrayDestroy(&safiles); sarrayDestroy(&sathumbs); sarrayDestroy(&saviews); sarrayDestroy(&sahtml); sarrayDestroy(&salink); return 0; }
169,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
lspci_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; struct stream packet = *s; if (!s_check(s)) { rdp_protocol_error("lspci_process(), stream is in unstable state", &packet); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, lspci_process_line, NULL); xfree(buf); }
169,798
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err = -EIO; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) goto out; symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out: up_read(&iinfo->i_data_sem); SetPageError(page); kunmap(page); unlock_page(page); return err; } Commit Message: udf: Verify symlink size before loading it UDF specification allows arbitrarily large symlinks. However we support only symlinks at most one block large. Check the length of the symlink so that we don't access memory beyond end of the symlink block. CC: [email protected] Reported-by: Carl Henrik Lunde <[email protected]> Signed-off-by: Jan Kara <[email protected]> CWE ID: CWE-119
static int udf_symlink_filler(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct buffer_head *bh = NULL; unsigned char *symlink; int err; unsigned char *p = kmap(page); struct udf_inode_info *iinfo; uint32_t pos; /* We don't support symlinks longer than one block */ if (inode->i_size > inode->i_sb->s_blocksize) { err = -ENAMETOOLONG; goto out_unmap; } iinfo = UDF_I(inode); pos = udf_block_map(inode, 0); down_read(&iinfo->i_data_sem); if (iinfo->i_alloc_type == ICBTAG_FLAG_AD_IN_ICB) { symlink = iinfo->i_ext.i_data + iinfo->i_lenEAttr; } else { bh = sb_bread(inode->i_sb, pos); if (!bh) { err = -EIO; goto out_unlock_inode; } symlink = bh->b_data; } udf_pc_to_char(inode->i_sb, symlink, inode->i_size, p); brelse(bh); up_read(&iinfo->i_data_sem); SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; out_unlock_inode: up_read(&iinfo->i_data_sem); SetPageError(page); out_unmap: kunmap(page); unlock_page(page); return err; }
169,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static uint16_t transmit_data_on(int fd, uint8_t *data, uint16_t length) { assert(data != NULL); assert(length > 0); uint16_t transmitted_length = 0; while (length > 0) { ssize_t ret = write(fd, data + transmitted_length, length); switch (ret) { case -1: LOG_ERROR("In %s, error writing to the serial port with fd %d: %s", __func__, fd, strerror(errno)); return transmitted_length; case 0: return transmitted_length; default: transmitted_length += ret; length -= ret; break; } } return transmitted_length; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static uint16_t transmit_data_on(int fd, uint8_t *data, uint16_t length) { assert(data != NULL); assert(length > 0); uint16_t transmitted_length = 0; while (length > 0) { ssize_t ret = TEMP_FAILURE_RETRY(write(fd, data + transmitted_length, length)); switch (ret) { case -1: LOG_ERROR("In %s, error writing to the serial port with fd %d: %s", __func__, fd, strerror(errno)); return transmitted_length; case 0: return transmitted_length; default: transmitted_length += ret; length -= ret; break; } } return transmitted_length; }
173,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StorageHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { process_ = process_host; } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void StorageHandler::SetRenderer(RenderProcessHost* process_host, void StorageHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { RenderProcessHost* process = RenderProcessHost::FromID(process_host_id); storage_partition_ = process ? process->GetStoragePartition() : nullptr; }
172,774
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; mutex_lock(&tu->tread_sem); if (tu->timeri) { /* too late */ mutex_unlock(&tu->tread_sem); return -EBUSY; } if (get_user(xarg, p)) { mutex_unlock(&tu->tread_sem); return -EFAULT; } tu->tread = xarg ? 1 : 0; mutex_unlock(&tu->tread_sem); return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; } Commit Message: ALSA: timer: Fix race among timer ioctls ALSA timer ioctls have an open race and this may lead to a use-after-free of timer instance object. A simplistic fix is to make each ioctl exclusive. We have already tread_sem for controlling the tread, and extend this as a global mutex to be applied to each ioctl. The downside is, of course, the worse concurrency. But these ioctls aren't to be parallel accessible, in anyway, so it should be fine to serialize there. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362
static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, static long __snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; if (tu->timeri) /* too late */ return -EBUSY; if (get_user(xarg, p)) return -EFAULT; tu->tread = xarg ? 1 : 0; return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; }
167,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; } Commit Message: vfs: Test for and handle paths that are unreachable from their mnt_root In rare cases a directory can be renamed out from under a bind mount. In those cases without special handling it becomes possible to walk up the directory tree to the root dentry of the filesystem and down from the root dentry to every other file or directory on the filesystem. Like division by zero .. from an unconnected path can not be given a useful semantic as there is no predicting at which path component the code will realize it is unconnected. We certainly can not match the current behavior as the current behavior is a security hole. Therefore when encounting .. when following an unconnected path return -ENOENT. - Add a function path_connected to verify path->dentry is reachable from path->mnt.mnt_root. AKA to validate that rename did not do something nasty to the bind mount. To avoid races path_connected must be called after following a path component to it's next path component. Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-254
static int follow_dotdot_rcu(struct nameidata *nd) { struct inode *inode = nd->inode; if (!nd->root.mnt) set_root_rcu(nd); while (1) { if (path_equal(&nd->path, &nd->root)) break; if (nd->path.dentry != nd->path.mnt->mnt_root) { struct dentry *old = nd->path.dentry; struct dentry *parent = old->d_parent; unsigned seq; inode = parent->d_inode; seq = read_seqcount_begin(&parent->d_seq); if (unlikely(read_seqcount_retry(&old->d_seq, nd->seq))) return -ECHILD; nd->path.dentry = parent; nd->seq = seq; if (unlikely(!path_connected(&nd->path))) return -ENOENT; break; } else { struct mount *mnt = real_mount(nd->path.mnt); struct mount *mparent = mnt->mnt_parent; struct dentry *mountpoint = mnt->mnt_mountpoint; struct inode *inode2 = mountpoint->d_inode; unsigned seq = read_seqcount_begin(&mountpoint->d_seq); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (&mparent->mnt == nd->path.mnt) break; /* we know that mountpoint was pinned */ nd->path.dentry = mountpoint; nd->path.mnt = &mparent->mnt; inode = inode2; nd->seq = seq; } } while (unlikely(d_mountpoint(nd->path.dentry))) { struct mount *mounted; mounted = __lookup_mnt(nd->path.mnt, nd->path.dentry); if (unlikely(read_seqretry(&mount_lock, nd->m_seq))) return -ECHILD; if (!mounted) break; nd->path.mnt = &mounted->mnt; nd->path.dentry = mounted->mnt.mnt_root; inode = nd->path.dentry->d_inode; nd->seq = read_seqcount_begin(&nd->path.dentry->d_seq); } nd->inode = inode; return 0; }
166,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CreateSymbolicLink(const FilePath& target, const FilePath& symlink) { ASSERT_TRUE(file_util::CreateSymbolicLink(target, symlink)) << ": " << target.value() << ": " << symlink.value(); } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void CreateSymbolicLink(const FilePath& target, const FilePath& symlink) { virtual void TearDown() OVERRIDE { metadata_.reset(); }
170,870
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_parse_islice(dec_struct_t *ps_dec, UWORD16 u2_first_mb_in_slice) { dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst; UWORD32 u4_temp; WORD32 i_temp; WORD32 ret; /*--------------------------------------------------------------------*/ /* Read remaining contents of the slice header */ /*--------------------------------------------------------------------*/ /* dec_ref_pic_marking function */ /* G050 */ if(ps_slice->u1_nal_ref_idc != 0) { if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read) ps_dec->u4_bitoffset = ih264d_read_mmco_commands( ps_dec); else ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset; } /* G050 */ /* Read slice_qp_delta */ i_temp = ps_pps->u1_pic_init_qp + ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((i_temp < 0) || (i_temp > 51)) return ERROR_INV_RANGE_QP_T; ps_slice->u1_slice_qp = i_temp; COPYTHECONTEXT("SH: slice_qp_delta", ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp); if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp); if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED) { return ERROR_INV_SLICE_HDR_T; } ps_slice->u1_disable_dblk_filter_idc = u4_temp; if(u4_temp != 1) { i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_alpha_c0_offset = i_temp; COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2", ps_slice->i1_slice_alpha_c0_offset >> 1); i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_beta_offset = i_temp; COPYTHECONTEXT("SH: slice_beta_offset_div2", ps_slice->i1_slice_beta_offset >> 1); } else { ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } } else { ps_slice->u1_disable_dblk_filter_idc = 0; ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } /* Initialization to check if number of motion vector per 2 Mbs */ /* are exceeding the range or not */ ps_dec->u2_mv_2mb[0] = 0; ps_dec->u2_mv_2mb[1] = 0; /*set slice header cone to 2 ,to indicate correct header*/ ps_dec->u1_slice_header_done = 2; if(ps_pps->u1_entropy_coding_mode) { SWITCHOFFTRACE; SWITCHONTRACECABAC; if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff; } else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff; ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; SWITCHONTRACE; SWITCHOFFTRACECABAC; } else { if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff; } else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff; ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; } return OK; } Commit Message: Return error when there are more mmco params than allocated size Bug: 25818142 Change-Id: I5c1b23985eeca5192b42703c627ca3d060e4e13d CWE ID: CWE-119
WORD32 ih264d_parse_islice(dec_struct_t *ps_dec, UWORD16 u2_first_mb_in_slice) { dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps; dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst; UWORD32 u4_temp; WORD32 i_temp; WORD32 ret; /*--------------------------------------------------------------------*/ /* Read remaining contents of the slice header */ /*--------------------------------------------------------------------*/ /* dec_ref_pic_marking function */ /* G050 */ if(ps_slice->u1_nal_ref_idc != 0) { if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read) { i_temp = ih264d_read_mmco_commands(ps_dec); if (i_temp < 0) { return ERROR_DBP_MANAGER_T; } ps_dec->u4_bitoffset = i_temp; } else ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset; } /* G050 */ /* Read slice_qp_delta */ i_temp = ps_pps->u1_pic_init_qp + ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); if((i_temp < 0) || (i_temp > 51)) return ERROR_INV_RANGE_QP_T; ps_slice->u1_slice_qp = i_temp; COPYTHECONTEXT("SH: slice_qp_delta", ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp); if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1) { u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); COPYTHECONTEXT("SH: disable_deblocking_filter_idc", u4_temp); if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED) { return ERROR_INV_SLICE_HDR_T; } ps_slice->u1_disable_dblk_filter_idc = u4_temp; if(u4_temp != 1) { i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_alpha_c0_offset = i_temp; COPYTHECONTEXT("SH: slice_alpha_c0_offset_div2", ps_slice->i1_slice_alpha_c0_offset >> 1); i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) << 1; if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) { return ERROR_INV_SLICE_HDR_T; } ps_slice->i1_slice_beta_offset = i_temp; COPYTHECONTEXT("SH: slice_beta_offset_div2", ps_slice->i1_slice_beta_offset >> 1); } else { ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } } else { ps_slice->u1_disable_dblk_filter_idc = 0; ps_slice->i1_slice_alpha_c0_offset = 0; ps_slice->i1_slice_beta_offset = 0; } /* Initialization to check if number of motion vector per 2 Mbs */ /* are exceeding the range or not */ ps_dec->u2_mv_2mb[0] = 0; ps_dec->u2_mv_2mb[1] = 0; /*set slice header cone to 2 ,to indicate correct header*/ ps_dec->u1_slice_header_done = 2; if(ps_pps->u1_entropy_coding_mode) { SWITCHOFFTRACE; SWITCHONTRACECABAC; if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff; } else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff; ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; SWITCHONTRACE; SWITCHOFFTRACECABAC; } else { if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) { ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff; } else ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff; ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice, u2_first_mb_in_slice); if(ret != OK) return ret; } return OK; }
173,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void QuitMessageLoop() { base::RunLoop::QuitCurrentWhenIdleDeprecated(); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <[email protected]> Reviewed-by: Avi Drissman <[email protected]> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
static void QuitMessageLoop() { base::Unretained(this), on_launched)); }
172,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_slice(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_slice_vertical_position; UWORD32 u4_slice_vertical_position_extension; IMPEG2D_ERROR_CODES_T e_error; ps_stream = &ps_dec->s_bit_stream; /*------------------------------------------------------------------------*/ /* All the profiles supported require restricted slice structure. Hence */ /* there is no need to store slice_vertical_position. Note that max */ /* height supported does not exceed 2800 and scalablity is not supported */ /*------------------------------------------------------------------------*/ /* Remove the slice start code */ impeg2d_bit_stream_flush(ps_stream,START_CODE_PREFIX_LEN); u4_slice_vertical_position = impeg2d_bit_stream_get(ps_stream, 8); if(u4_slice_vertical_position > 2800) { u4_slice_vertical_position_extension = impeg2d_bit_stream_get(ps_stream, 3); u4_slice_vertical_position += (u4_slice_vertical_position_extension << 7); } if((u4_slice_vertical_position > ps_dec->u2_num_vert_mb) || (u4_slice_vertical_position == 0)) { return IMPEG2D_INVALID_VERT_SIZE; } u4_slice_vertical_position--; if (ps_dec->u2_mb_y != u4_slice_vertical_position) { ps_dec->u2_mb_y = u4_slice_vertical_position; ps_dec->u2_mb_x = 0; } ps_dec->u2_first_mb = 1; /*------------------------------------------------------------------------*/ /* Quant scale code decoding */ /*------------------------------------------------------------------------*/ { UWORD16 u2_quant_scale_code; u2_quant_scale_code = impeg2d_bit_stream_get(ps_stream,5); ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); } if (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); /* Flush extra bit information */ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); } } impeg2d_bit_stream_get_bit(ps_stream); /* Reset the DC predictors to reset values given in Table 7.2 at the start*/ /* of slice data */ ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; /*------------------------------------------------------------------------*/ /* dec->DecMBsinSlice() implements the following psuedo code from standard*/ /* do */ /* { */ /* macroblock() */ /* } while (impeg2d_bit_stream_nxt() != '000 0000 0000 0000 0000 0000') */ /*------------------------------------------------------------------------*/ e_error = ps_dec->pf_decode_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } /* Check for the MBy index instead of number of MBs left, because the * number of MBs left in case of multi-thread decode is the number of MBs * in that row only */ if(ps_dec->u2_mb_y < ps_dec->u2_num_vert_mb) impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
IMPEG2D_ERROR_CODES_T impeg2d_dec_slice(dec_state_t *ps_dec) { stream_t *ps_stream; UWORD32 u4_slice_vertical_position; UWORD32 u4_slice_vertical_position_extension; IMPEG2D_ERROR_CODES_T e_error; ps_stream = &ps_dec->s_bit_stream; /*------------------------------------------------------------------------*/ /* All the profiles supported require restricted slice structure. Hence */ /* there is no need to store slice_vertical_position. Note that max */ /* height supported does not exceed 2800 and scalablity is not supported */ /*------------------------------------------------------------------------*/ /* Remove the slice start code */ impeg2d_bit_stream_flush(ps_stream,START_CODE_PREFIX_LEN); u4_slice_vertical_position = impeg2d_bit_stream_get(ps_stream, 8); if(u4_slice_vertical_position > 2800) { u4_slice_vertical_position_extension = impeg2d_bit_stream_get(ps_stream, 3); u4_slice_vertical_position += (u4_slice_vertical_position_extension << 7); } if((u4_slice_vertical_position > ps_dec->u2_num_vert_mb) || (u4_slice_vertical_position == 0)) { return IMPEG2D_INVALID_VERT_SIZE; } u4_slice_vertical_position--; if (ps_dec->u2_mb_y != u4_slice_vertical_position) { ps_dec->u2_mb_y = u4_slice_vertical_position; ps_dec->u2_mb_x = 0; } ps_dec->u2_first_mb = 1; /*------------------------------------------------------------------------*/ /* Quant scale code decoding */ /*------------------------------------------------------------------------*/ { UWORD16 u2_quant_scale_code; u2_quant_scale_code = impeg2d_bit_stream_get(ps_stream,5); ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); } if (impeg2d_bit_stream_nxt(ps_stream,1) == 1) { impeg2d_bit_stream_flush(ps_stream,9); /* Flush extra bit information */ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 && ps_stream->u4_offset < ps_stream->u4_max_offset) { impeg2d_bit_stream_flush(ps_stream,9); } } impeg2d_bit_stream_get_bit(ps_stream); /* Reset the DC predictors to reset values given in Table 7.2 at the start*/ /* of slice data */ ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; /*------------------------------------------------------------------------*/ /* dec->DecMBsinSlice() implements the following psuedo code from standard*/ /* do */ /* { */ /* macroblock() */ /* } while (impeg2d_bit_stream_nxt() != '000 0000 0000 0000 0000 0000') */ /*------------------------------------------------------------------------*/ e_error = ps_dec->pf_decode_slice(ps_dec); if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) { return e_error; } /* Check for the MBy index instead of number of MBs left, because the * number of MBs left in case of multi-thread decode is the number of MBs * in that row only */ if(ps_dec->u2_mb_y < ps_dec->u2_num_vert_mb) impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }
173,947
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; } Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s. CWE ID: CWE-269
void *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; // Don't load any DLLs that end with the pk3 extension if (COM_CompareExtension(name, ".pk3")) { Com_Printf("Rejecting DLL named \"%s\"", name); return NULL; } if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; }
170,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Add(int original_content_length, int received_content_length) { AddInt64ToListPref( kNumDaysInHistory - 1, original_content_length, original_update_.Get()); AddInt64ToListPref( kNumDaysInHistory - 1, received_content_length, received_update_.Get()); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void Add(int original_content_length, int received_content_length) { original_.Add(original_content_length); received_.Add(received_content_length); }
171,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ManifestChangeNotifier::DidChangeManifest() { if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <[email protected]> Reviewed-by: Mounir Lamouri <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#531121} CWE ID:
void ManifestChangeNotifier::DidChangeManifest() { // Manifests are not considered when the current page has a unique origin. if (!ManifestManager::CanFetchManifest(render_frame())) return; if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); }
172,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void registerURL(const char* file, const char* mimeType) { registerURL(file, file, mimeType); } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void registerURL(const char* file, const char* mimeType) { registerMockedURLLoad(KURL(m_baseUrl, file), WebString::fromUTF8(file), m_folder, WebString::fromUTF8(mimeType)); }
171,575
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_for_each(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event_context *ctx = event->ctx; struct perf_event *sibling; WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); event = event->group_leader; perf_event_for_each_child(event, func); list_for_each_entry(sibling, &event->sibling_list, group_entry) perf_event_for_each_child(sibling, func); mutex_unlock(&ctx->mutex); } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
static void perf_event_for_each(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event_context *ctx = event->ctx; struct perf_event *sibling; lockdep_assert_held(&ctx->mutex); event = event->group_leader; perf_event_for_each_child(event, func); list_for_each_entry(sibling, &event->sibling_list, group_entry) perf_event_for_each_child(sibling, func); }
166,984
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IsBlockedNavigation(net::Error error_code) { switch (error_code) { case net::ERR_BLOCKED_BY_CLIENT: case net::ERR_BLOCKED_BY_RESPONSE: case net::ERR_BLOCKED_BY_XSS_AUDITOR: case net::ERR_UNSAFE_REDIRECT: return true; default: return false; } } Commit Message: Do not use NavigationEntry to block history navigations. This is no longer necessary after r477371. BUG=777419 TEST=See bug for repro steps. Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: I701e4d4853858281b43e3743b12274dbeadfbf18 Reviewed-on: https://chromium-review.googlesource.com/733959 Reviewed-by: Devlin <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#511942} CWE ID: CWE-20
bool IsBlockedNavigation(net::Error error_code) {
172,931
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_rx_bufs(struct vhost_virtqueue *vq, struct vring_used_elem *heads, int datalen, unsigned *iovcount, struct vhost_log *log, unsigned *log_num, unsigned int quota) { unsigned int out, in; int seg = 0; int headcount = 0; unsigned d; int r, nlogs = 0; while (datalen > 0 && headcount < quota) { if (unlikely(seg >= UIO_MAXIOV)) { r = -ENOBUFS; goto err; } d = vhost_get_vq_desc(vq->dev, vq, vq->iov + seg, ARRAY_SIZE(vq->iov) - seg, &out, &in, log, log_num); if (d == vq->num) { r = 0; goto err; } if (unlikely(out || in <= 0)) { vq_err(vq, "unexpected descriptor format for RX: " "out %d, in %d\n", out, in); r = -EINVAL; goto err; } if (unlikely(log)) { nlogs += *log_num; log += *log_num; } heads[headcount].id = d; heads[headcount].len = iov_length(vq->iov + seg, in); datalen -= heads[headcount].len; ++headcount; seg += in; } heads[headcount - 1].len += datalen; *iovcount = seg; if (unlikely(log)) *log_num = nlogs; return headcount; err: vhost_discard_vq_desc(vq, headcount); return r; } Commit Message: vhost: fix total length when packets are too short When mergeable buffers are disabled, and the incoming packet is too large for the rx buffer, get_rx_bufs returns success. This was intentional in order for make recvmsg truncate the packet and then handle_rx would detect err != sock_len and drop it. Unfortunately we pass the original sock_len to recvmsg - which means we use parts of iov not fully validated. Fix this up by detecting this overrun and doing packet drop immediately. CVE-2014-0077 Signed-off-by: Michael S. Tsirkin <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int get_rx_bufs(struct vhost_virtqueue *vq, struct vring_used_elem *heads, int datalen, unsigned *iovcount, struct vhost_log *log, unsigned *log_num, unsigned int quota) { unsigned int out, in; int seg = 0; int headcount = 0; unsigned d; int r, nlogs = 0; while (datalen > 0 && headcount < quota) { if (unlikely(seg >= UIO_MAXIOV)) { r = -ENOBUFS; goto err; } d = vhost_get_vq_desc(vq->dev, vq, vq->iov + seg, ARRAY_SIZE(vq->iov) - seg, &out, &in, log, log_num); if (d == vq->num) { r = 0; goto err; } if (unlikely(out || in <= 0)) { vq_err(vq, "unexpected descriptor format for RX: " "out %d, in %d\n", out, in); r = -EINVAL; goto err; } if (unlikely(log)) { nlogs += *log_num; log += *log_num; } heads[headcount].id = d; heads[headcount].len = iov_length(vq->iov + seg, in); datalen -= heads[headcount].len; ++headcount; seg += in; } heads[headcount - 1].len += datalen; *iovcount = seg; if (unlikely(log)) *log_num = nlogs; /* Detect overrun */ if (unlikely(datalen > 0)) { r = UIO_MAXIOV + 1; goto err; } return headcount; err: vhost_discard_vq_desc(vq, headcount); return r; }
166,460
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int pf_detect(void) { struct pf_unit *pf = units; int k, unit; printk("%s: %s version %s, major %d, cluster %d, nice %d\n", name, name, PF_VERSION, major, cluster, nice); par_drv = pi_register_driver(name); if (!par_drv) { pr_err("failed to register %s driver\n", name); return -1; } k = 0; if (pf_drive_count == 0) { if (pi_init(pf->pi, 1, -1, -1, -1, -1, -1, pf_scratch, PI_PF, verbose, pf->name)) { if (!pf_probe(pf) && pf->disk) { pf->present = 1; k++; } else pi_release(pf->pi); } } else for (unit = 0; unit < PF_UNITS; unit++, pf++) { int *conf = *drives[unit]; if (!conf[D_PRT]) continue; if (pi_init(pf->pi, 0, conf[D_PRT], conf[D_MOD], conf[D_UNI], conf[D_PRO], conf[D_DLY], pf_scratch, PI_PF, verbose, pf->name)) { if (pf->disk && !pf_probe(pf)) { pf->present = 1; k++; } else pi_release(pf->pi); } } if (k) return 0; printk("%s: No ATAPI disk detected\n", name); for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { blk_cleanup_queue(pf->disk->queue); pf->disk->queue = NULL; blk_mq_free_tag_set(&pf->tag_set); put_disk(pf->disk); } pi_unregister_driver(par_drv); return -1; } Commit Message: paride/pf: Fix potential NULL pointer dereference Syzkaller report this: pf: pf version 1.04, major 47, cluster 64, nice 0 pf: No ATAPI disk detected kasan: CONFIG_KASAN_INLINE enabled kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:pf_init+0x7af/0x1000 [pf] Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34 RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202 RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788 RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580 RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59 R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000 R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020 FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: ? 0xffffffffc1e50000 do_one_initcall+0xbc/0x47d init/main.c:901 do_init_module+0x1b5/0x547 kernel/module.c:3456 load_module+0x6405/0x8c10 kernel/module.c:3804 __do_sys_finit_module+0x162/0x190 kernel/module.c:3898 do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003 RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp c ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp td glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace 7a818cf5f210d79e ]--- If alloc_disk fails in pf_init_units, pf->disk will be NULL, however in pf_detect and pf_exit, it's not check this before free.It may result a NULL pointer dereference. Also when register_blkdev failed, blk_cleanup_queue() and blk_mq_free_tag_set() should be called to free resources. Reported-by: Hulk Robot <[email protected]> Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails") Signed-off-by: YueHaibing <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-476
static int pf_detect(void) { struct pf_unit *pf = units; int k, unit; printk("%s: %s version %s, major %d, cluster %d, nice %d\n", name, name, PF_VERSION, major, cluster, nice); par_drv = pi_register_driver(name); if (!par_drv) { pr_err("failed to register %s driver\n", name); return -1; } k = 0; if (pf_drive_count == 0) { if (pi_init(pf->pi, 1, -1, -1, -1, -1, -1, pf_scratch, PI_PF, verbose, pf->name)) { if (!pf_probe(pf) && pf->disk) { pf->present = 1; k++; } else pi_release(pf->pi); } } else for (unit = 0; unit < PF_UNITS; unit++, pf++) { int *conf = *drives[unit]; if (!conf[D_PRT]) continue; if (pi_init(pf->pi, 0, conf[D_PRT], conf[D_MOD], conf[D_UNI], conf[D_PRO], conf[D_DLY], pf_scratch, PI_PF, verbose, pf->name)) { if (pf->disk && !pf_probe(pf)) { pf->present = 1; k++; } else pi_release(pf->pi); } } if (k) return 0; printk("%s: No ATAPI disk detected\n", name); for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) { if (!pf->disk) continue; blk_cleanup_queue(pf->disk->queue); pf->disk->queue = NULL; blk_mq_free_tag_set(&pf->tag_set); put_disk(pf->disk); } pi_unregister_driver(par_drv); return -1; }
169,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual size_t GetNumActiveInputMethods() { scoped_ptr<InputMethodDescriptors> input_methods(GetActiveInputMethods()); return input_methods->size(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual size_t GetNumActiveInputMethods() { scoped_ptr<input_method::InputMethodDescriptors> input_methods( GetActiveInputMethods()); return input_methods->size(); }
170,490
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LayerWebKitThread::setNeedsCommit() { if (m_owner) m_owner->notifySyncRequired(); } Commit Message: [BlackBerry] GraphicsLayer: rename notifySyncRequired to notifyFlushRequired https://bugs.webkit.org/show_bug.cgi?id=111997 Patch by Alberto Garcia <[email protected]> on 2013-03-11 Reviewed by Rob Buis. This changed in r130439 but the old name was introduced again by mistake in r144465. * platform/graphics/blackberry/GraphicsLayerBlackBerry.h: (WebCore::GraphicsLayerBlackBerry::notifyFlushRequired): * platform/graphics/blackberry/LayerWebKitThread.cpp: (WebCore::LayerWebKitThread::setNeedsCommit): git-svn-id: svn://svn.chromium.org/blink/trunk@145363 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
void LayerWebKitThread::setNeedsCommit() { // Call notifyFlushRequired(), which in this implementation plumbs through to if (m_owner) m_owner->notifyFlushRequired(); }
171,591
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunInvTxfm(int16_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride, tx_type_); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunInvTxfm(int16_t *out, uint8_t *dst, int stride) { void RunInvTxfm(tran_low_t *out, uint8_t *dst, int stride) { inv_txfm_(out, dst, stride, tx_type_); }
174,525
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */ { #ifdef PHP_WIN32 unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC); #else unsigned long key = realpath_cache_key(path, path_len); #endif unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0])); realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n]; while (*bucket != NULL) { if (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) { realpath_cache_bucket *r = *bucket; *bucket = (*bucket)->next; /* if the pointers match then only subtract the length of the path */ if(r->path == r->realpath) { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1; } else { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1; } free(r); } else if (key == (*bucket)->key && path_len == (*bucket)->path_len && memcmp(path, (*bucket)->path, path_len) == 0) { return *bucket; } else { bucket = &(*bucket)->next; } } return NULL; } /* }}} */ Commit Message: CWE ID: CWE-190
static inline realpath_cache_bucket* realpath_cache_find(const char *path, int path_len, time_t t TSRMLS_DC) /* {{{ */ { #ifdef PHP_WIN32 unsigned long key = realpath_cache_key(path, path_len TSRMLS_CC); #else unsigned long key = realpath_cache_key(path, path_len); #endif unsigned long n = key % (sizeof(CWDG(realpath_cache)) / sizeof(CWDG(realpath_cache)[0])); realpath_cache_bucket **bucket = &CWDG(realpath_cache)[n]; while (*bucket != NULL) { if (CWDG(realpath_cache_ttl) && (*bucket)->expires < t) { realpath_cache_bucket *r = *bucket; *bucket = (*bucket)->next; /* if the pointers match then only subtract the length of the path */ if(r->path == r->realpath) { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1; } else { CWDG(realpath_cache_size) -= sizeof(realpath_cache_bucket) + r->path_len + 1 + r->realpath_len + 1; } free(r); } else if (key == (*bucket)->key && path_len == (*bucket)->path_len && memcmp(path, (*bucket)->path, path_len) == 0) { return *bucket; } else { bucket = &(*bucket)->next; } } return NULL; } /* }}} */
164,983
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: test_standard(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, int bdlo, int PNG_CONST bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, interlace_type, 0, 0, 0), 0/*do_interlace*/, pm->use_update_info); if (fail(pm)) return 0; } } return 1; /* keep going */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
test_standard(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, test_standard(png_modifier* const pm, png_byte const colour_type, int bdlo, int const bdhi) { for (; bdlo <= bdhi; ++bdlo) { int interlace_type; for (interlace_type = PNG_INTERLACE_NONE; interlace_type < INTERLACE_LAST; ++interlace_type) { standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info); if (fail(pm)) return 0; } } return 1; /* keep going */ }
173,710
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int board_early_init_r(void) { int ret = 0; /* Flush d-cache and invalidate i-cache of any FLASH data */ flush_dcache(); invalidate_icache(); set_liodns(); setup_qbman_portals(); ret = trigger_fpga_config(); if (ret) printf("error triggering PCIe FPGA config\n"); /* enable the Unit LED (red) & Boot LED (on) */ qrio_set_leds(); /* enable Application Buffer */ qrio_enable_app_buffer(); return ret; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
int board_early_init_r(void) { int ret = 0; /* Flush d-cache and invalidate i-cache of any FLASH data */ flush_dcache(); invalidate_icache(); set_liodns(); setup_qbman_portals(); ret = trigger_fpga_config(); if (ret) printf("error triggering PCIe FPGA config\n"); /* enable the Unit LED (red) & Boot LED (on) */ qrio_set_leds(); /* enable Application Buffer */ qrio_enable_app_buffer(); return 0; }
169,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { LOG(INFO) << "IBus connection is ready."; } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeCreateIBus() { if (ibus_) { return; } ibus_init(); ibus_ = ibus_bus_new(); if (!ibus_) { LOG(ERROR) << "ibus_bus_new() failed"; return; } ConnectIBusSignals(); ibus_bus_set_watch_dbus_signal(ibus_, TRUE); ibus_bus_set_watch_ibus_signal(ibus_, TRUE); if (ibus_bus_is_connected(ibus_)) { VLOG(1) << "IBus connection is ready."; } }
170,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ShouldUseNativeViews() { #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) return base::FeatureList::IsEnabled(kAutofillExpandedPopupViews) || base::FeatureList::IsEnabled(::features::kExperimentalUi); #else return false; #endif } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <[email protected]> Reviewed-by: Vasilii Sukhanov <[email protected]> Reviewed-by: Fabio Tirelo <[email protected]> Reviewed-by: Tommy Martino <[email protected]> Commit-Queue: Mathieu Perreault <[email protected]> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
bool ShouldUseNativeViews() {
172,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int parse_arguments(int *argc_p, const char ***argv_p) { static poptContext pc; char *ref = lp_refuse_options(module_id); const char *arg, **argv = *argv_p; int argc = *argc_p; int opt; if (ref && *ref) set_refuse_options(ref); set_refuse_options("log-file*"); #ifdef ICONV_OPTION if (!*lp_charset(module_id)) set_refuse_options("iconv"); #endif } Commit Message: CWE ID:
int parse_arguments(int *argc_p, const char ***argv_p) { static poptContext pc; char *ref = lp_refuse_options(module_id); const char *arg, **argv = *argv_p; int argc = *argc_p; int opt; int orig_protect_args = protect_args; if (ref && *ref) set_refuse_options(ref); set_refuse_options("log-file*"); #ifdef ICONV_OPTION if (!*lp_charset(module_id)) set_refuse_options("iconv"); #endif }
165,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeRemoteBase(const std::string& value) { GURL url(value); std::string path = url.path(); std::vector<std::string> parts = base::SplitString( path, "/", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); std::string revision = parts.size() > 2 ? parts[2] : ""; revision = SanitizeRevision(revision); path = base::StringPrintf("/%s/%s/", kRemoteFrontendPath, revision.c_str()); return SanitizeFrontendURL(url, url::kHttpsScheme, kRemoteFrontendDomain, path, false).spec(); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
std::string SanitizeRemoteBase(const std::string& value) {
172,462
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: prep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ) { krb5_error_code retval = KRB5KRB_AP_ERR_BADMATCH; char **realms, **cpp, *temp_buf=NULL; krb5_data *comp1 = NULL, *comp2 = NULL; char *comp1_str = NULL; /* By now we know that server principal name is unknown. * If CANONICALIZE flag is set in the request * If req is not U2U authn. req * the requested server princ. has exactly two components * either * the name type is NT-SRV-HST * or name type is NT-UNKNOWN and * the 1st component is listed in conf file under host_based_services * the 1st component is not in a list in conf under "no_host_referral" * the 2d component looks like fully-qualified domain name (FQDN) * If all of these conditions are satisfied - try mapping the FQDN and * re-process the request as if client had asked for cross-realm TGT. */ if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE) && !isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY) && krb5_princ_size(kdc_context, request->server) == 2) { comp1 = krb5_princ_component(kdc_context, request->server, 0); comp2 = krb5_princ_component(kdc_context, request->server, 1); comp1_str = calloc(1,comp1->length+1); if (!comp1_str) { retval = ENOMEM; goto cleanup; } strlcpy(comp1_str,comp1->data,comp1->length+1); if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST || krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST || (krb5_princ_type(kdc_context, request->server) == KRB5_NT_UNKNOWN && kdc_active_realm->realm_host_based_services != NULL && (krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, comp1_str) == TRUE || krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, KRB5_CONF_ASTERISK) == TRUE))) && (kdc_active_realm->realm_no_host_referral == NULL || (krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, KRB5_CONF_ASTERISK) == FALSE && krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, comp1_str) == FALSE))) { if (memchr(comp2->data, '.', comp2->length) == NULL) goto cleanup; temp_buf = calloc(1, comp2->length+1); if (!temp_buf) { retval = ENOMEM; goto cleanup; } strlcpy(temp_buf, comp2->data,comp2->length+1); retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms); free(temp_buf); if (retval) { /* no match found */ kdc_err(kdc_context, retval, "unable to find realm of host"); goto cleanup; } if (realms == 0) { retval = KRB5KRB_AP_ERR_BADMATCH; goto cleanup; } /* Don't return a referral to the null realm or the service * realm. */ if (realms[0] == 0 || data_eq_string(request->server->realm, realms[0])) { free(realms[0]); free(realms); retval = KRB5KRB_AP_ERR_BADMATCH; goto cleanup; } /* Modify request. * Construct cross-realm tgt : krbtgt/REMOTE_REALM@LOCAL_REALM * and use it as a principal in this req. */ retval = krb5_build_principal(kdc_context, krbtgt_princ, (*request->server).realm.length, (*request->server).realm.data, "krbtgt", realms[0], (char *)0); for (cpp = realms; *cpp; cpp++) free(*cpp); } } cleanup: free(comp1_str); return retval; } Commit Message: KDC TGS-REQ null deref [CVE-2013-1416] By sending an unusual but valid TGS-REQ, an authenticated remote attacker can cause the KDC process to crash by dereferencing a null pointer. prep_reprocess_req() can cause a null pointer dereference when processing a service principal name. Code in this function can inappropriately pass a null pointer to strlcpy(). Unmodified client software can trivially trigger this vulnerability, but the attacker must have already authenticated and received a valid Kerberos ticket. The vulnerable code was introduced by the implementation of new service principal realm referral functionality in krb5-1.7, but was corrected as a side effect of the KDC refactoring in krb5-1.11. CVSSv2 vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:H/RL:O/RC:C ticket: 7600 (new) version_fixed: 1.10.5 status: resolved CWE ID: CWE-119
prep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ) { krb5_error_code retval = KRB5KRB_AP_ERR_BADMATCH; char **realms, **cpp, *temp_buf=NULL; krb5_data *comp1 = NULL, *comp2 = NULL; char *comp1_str = NULL; /* By now we know that server principal name is unknown. * If CANONICALIZE flag is set in the request * If req is not U2U authn. req * the requested server princ. has exactly two components * either * the name type is NT-SRV-HST * or name type is NT-UNKNOWN and * the 1st component is listed in conf file under host_based_services * the 1st component is not in a list in conf under "no_host_referral" * the 2d component looks like fully-qualified domain name (FQDN) * If all of these conditions are satisfied - try mapping the FQDN and * re-process the request as if client had asked for cross-realm TGT. */ if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE) && !isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY) && krb5_princ_size(kdc_context, request->server) == 2) { comp1 = krb5_princ_component(kdc_context, request->server, 0); comp2 = krb5_princ_component(kdc_context, request->server, 1); comp1_str = calloc(1,comp1->length+1); if (!comp1_str) { retval = ENOMEM; goto cleanup; } if (comp1->data != NULL) memcpy(comp1_str, comp1->data, comp1->length); if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST || krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST || (krb5_princ_type(kdc_context, request->server) == KRB5_NT_UNKNOWN && kdc_active_realm->realm_host_based_services != NULL && (krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, comp1_str) == TRUE || krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, KRB5_CONF_ASTERISK) == TRUE))) && (kdc_active_realm->realm_no_host_referral == NULL || (krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, KRB5_CONF_ASTERISK) == FALSE && krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, comp1_str) == FALSE))) { if (memchr(comp2->data, '.', comp2->length) == NULL) goto cleanup; temp_buf = calloc(1, comp2->length+1); if (!temp_buf) { retval = ENOMEM; goto cleanup; } if (comp2->data != NULL) memcpy(temp_buf, comp2->data, comp2->length); retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms); free(temp_buf); if (retval) { /* no match found */ kdc_err(kdc_context, retval, "unable to find realm of host"); goto cleanup; } if (realms == 0) { retval = KRB5KRB_AP_ERR_BADMATCH; goto cleanup; } /* Don't return a referral to the null realm or the service * realm. */ if (realms[0] == 0 || data_eq_string(request->server->realm, realms[0])) { free(realms[0]); free(realms); retval = KRB5KRB_AP_ERR_BADMATCH; goto cleanup; } /* Modify request. * Construct cross-realm tgt : krbtgt/REMOTE_REALM@LOCAL_REALM * and use it as a principal in this req. */ retval = krb5_build_principal(kdc_context, krbtgt_princ, (*request->server).realm.length, (*request->server).realm.data, "krbtgt", realms[0], (char *)0); for (cpp = realms; *cpp; cpp++) free(*cpp); } } cleanup: free(comp1_str); return retval; }
166,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static blink::WebScreenOrientations stringToOrientations(const AtomicString& orientationString) { DEFINE_STATIC_LOCAL(const AtomicString, portrait, ("portrait", AtomicString::ConstructFromLiteral)); DEFINE_STATIC_LOCAL(const AtomicString, landscape, ("landscape", AtomicString::ConstructFromLiteral)); if (orientationString == portrait) return blink::WebScreenOrientationPortraitPrimary | blink::WebScreenOrientationPortraitSecondary; if (orientationString == landscape) return blink::WebScreenOrientationLandscapePrimary | blink::WebScreenOrientationLandscapeSecondary; unsigned length = 0; ScreenOrientationInfo* orientationMap = orientationsMap(length); for (unsigned i = 0; i < length; ++i) { if (orientationMap[i].name == orientationString) return orientationMap[i].orientation; } return 0; } Commit Message: Screen Orientation: use OrientationLockType enum for lockOrientation(). BUG=162827 Review URL: https://codereview.chromium.org/204653002 git-svn-id: svn://svn.chromium.org/blink/trunk@169972 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
static blink::WebScreenOrientations stringToOrientations(const AtomicString& orientationString) { DEFINE_STATIC_LOCAL(const AtomicString, any, ("any", AtomicString::ConstructFromLiteral)); DEFINE_STATIC_LOCAL(const AtomicString, portrait, ("portrait", AtomicString::ConstructFromLiteral)); DEFINE_STATIC_LOCAL(const AtomicString, landscape, ("landscape", AtomicString::ConstructFromLiteral)); if (orientationString == any) { return blink::WebScreenOrientationPortraitPrimary | blink::WebScreenOrientationPortraitSecondary | blink::WebScreenOrientationLandscapePrimary | blink::WebScreenOrientationLandscapeSecondary; } if (orientationString == portrait) return blink::WebScreenOrientationPortraitPrimary | blink::WebScreenOrientationPortraitSecondary; if (orientationString == landscape) return blink::WebScreenOrientationLandscapePrimary | blink::WebScreenOrientationLandscapeSecondary; unsigned length = 0; ScreenOrientationInfo* orientationMap = orientationsMap(length); for (unsigned i = 0; i < length; ++i) { if (orientationMap[i].name == orientationString) return orientationMap[i].orientation; } return 0; }
171,440
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool msr_mtrr_valid(unsigned msr) { switch (msr) { case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1: case MSR_MTRRfix64K_00000: case MSR_MTRRfix16K_80000: case MSR_MTRRfix16K_A0000: case MSR_MTRRfix4K_C0000: case MSR_MTRRfix4K_C8000: case MSR_MTRRfix4K_D0000: case MSR_MTRRfix4K_D8000: case MSR_MTRRfix4K_E0000: case MSR_MTRRfix4K_E8000: case MSR_MTRRfix4K_F0000: case MSR_MTRRfix4K_F8000: case MSR_MTRRdefType: case MSR_IA32_CR_PAT: return true; case 0x2f8: return true; } return false; } Commit Message: KVM: MTRR: remove MSR 0x2f8 MSR 0x2f8 accessed the 124th Variable Range MTRR ever since MTRR support was introduced by 9ba075a664df ("KVM: MTRR support"). 0x2f8 became harmful when 910a6aae4e2e ("KVM: MTRR: exactly define the size of variable MTRRs") shrinked the array of VR MTRRs from 256 to 8, which made access to index 124 out of bounds. The surrounding code only WARNs in this situation, thus the guest gained a limited read/write access to struct kvm_arch_vcpu. 0x2f8 is not a valid VR MTRR MSR, because KVM has/advertises only 16 VR MTRR MSRs, 0x200-0x20f. Every VR MTRR is set up using two MSRs, 0x2f8 was treated as a PHYSBASE and 0x2f9 would be its PHYSMASK, but 0x2f9 was not implemented in KVM, therefore 0x2f8 could never do anything useful and getting rid of it is safe. This fixes CVE-2016-3713. Fixes: 910a6aae4e2e ("KVM: MTRR: exactly define the size of variable MTRRs") Cc: [email protected] Reported-by: David Matlack <[email protected]> Signed-off-by: Andy Honig <[email protected]> Signed-off-by: Radim Krčmář <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-284
static bool msr_mtrr_valid(unsigned msr) { switch (msr) { case 0x200 ... 0x200 + 2 * KVM_NR_VAR_MTRR - 1: case MSR_MTRRfix64K_00000: case MSR_MTRRfix16K_80000: case MSR_MTRRfix16K_A0000: case MSR_MTRRfix4K_C0000: case MSR_MTRRfix4K_C8000: case MSR_MTRRfix4K_D0000: case MSR_MTRRfix4K_D8000: case MSR_MTRRfix4K_E0000: case MSR_MTRRfix4K_E8000: case MSR_MTRRfix4K_F0000: case MSR_MTRRfix4K_F8000: case MSR_MTRRdefType: case MSR_IA32_CR_PAT: return true; } return false; }
167,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ContentEncoding::ParseCompressionEntry( long long start, long long size, IMkvReader* pReader, ContentCompression* compression) { assert(pReader); assert(compression); long long pos = start; const long long stop = start + size; bool valid = false; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x254) { long long algo = UnserializeUInt(pReader, pos, size); if (algo < 0) return E_FILE_FORMAT_INVALID; compression->algo = algo; valid = true; } else if (id == 0x255) { if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, buflen, buf); if (read_status) { delete [] buf; return status; } compression->settings = buf; compression->settings_len = buflen; } pos += size; //consume payload assert(pos <= stop); } if (!valid) return E_FILE_FORMAT_INVALID; return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long ContentEncoding::ParseCompressionEntry( long ContentEncoding::ParseCompressionEntry(long long start, long long size, IMkvReader* pReader, ContentCompression* compression) { assert(pReader); assert(compression); long long pos = start; const long long stop = start + size; bool valid = false; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x254) { long long algo = UnserializeUInt(pReader, pos, size); if (algo < 0) return E_FILE_FORMAT_INVALID; compression->algo = algo; valid = true; } else if (id == 0x255) { if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } compression->settings = buf; compression->settings_len = buflen; } pos += size; // consume payload assert(pos <= stop); } if (!valid) return E_FILE_FORMAT_INVALID; return 0; }
174,417
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else if (n->mac_table.in_use) { uint8_t *buf = g_malloc0(n->mac_table.in_use); qemu_get_buffer(f, buf, n->mac_table.in_use * ETH_ALEN); g_free(buf); n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } } Commit Message: CWE ID: CWE-119
static int virtio_net_load(QEMUFile *f, void *opaque, int version_id) { VirtIONet *n = opaque; VirtIODevice *vdev = VIRTIO_DEVICE(n); int ret, i, link_down; if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION) return -EINVAL; ret = virtio_load(vdev, f); if (ret) { return ret; } qemu_get_buffer(f, n->mac, ETH_ALEN); n->vqs[0].tx_waiting = qemu_get_be32(f); virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f)); if (version_id >= 3) n->status = qemu_get_be16(f); if (version_id >= 4) { if (version_id < 8) { n->promisc = qemu_get_be32(f); n->allmulti = qemu_get_be32(f); } else { n->promisc = qemu_get_byte(f); n->allmulti = qemu_get_byte(f); } } if (version_id >= 5) { n->mac_table.in_use = qemu_get_be32(f); /* MAC_TABLE_ENTRIES may be different from the saved image */ if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) { qemu_get_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN); } else { int64_t i; /* Overflow detected - can happen if source has a larger MAC table. * We simply set overflow flag so there's no need to maintain the * table of addresses, discard them all. * Note: 64 bit math to avoid integer overflow. */ for (i = 0; i < (int64_t)n->mac_table.in_use * ETH_ALEN; ++i) { qemu_get_byte(f); } n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1; n->mac_table.in_use = 0; } error_report("virtio-net: saved image requires vnet_hdr=on"); return -1; } }
165,363
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, struct _7z_folder *f, size_t numFolders) { const unsigned char *p; uint64_t *usizes; size_t unpack_streams; int type; unsigned i; uint32_t numDigests; memset(ss, 0, sizeof(*ss)); for (i = 0; i < numFolders; i++) f[i].numUnpackStreams = 1; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kNumUnPackStream) { unpack_streams = 0; for (i = 0; i < numFolders; i++) { if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) return (-1); if (UMAX_ENTRY < f[i].numUnpackStreams) return (-1); unpack_streams += (size_t)f[i].numUnpackStreams; } if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } else unpack_streams = numFolders; ss->unpack_streams = unpack_streams; if (unpack_streams) { ss->unpackSizes = calloc(unpack_streams, sizeof(*ss->unpackSizes)); ss->digestsDefined = calloc(unpack_streams, sizeof(*ss->digestsDefined)); ss->digests = calloc(unpack_streams, sizeof(*ss->digests)); if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || ss->digests == NULL) return (-1); } usizes = ss->unpackSizes; for (i = 0; i < numFolders; i++) { unsigned pack; uint64_t sum; if (f[i].numUnpackStreams == 0) continue; sum = 0; if (type == kSize) { for (pack = 1; pack < f[i].numUnpackStreams; pack++) { if (parse_7zip_uint64(a, usizes) < 0) return (-1); sum += *usizes++; } } *usizes++ = folder_uncompressed_size(&f[i]) - sum; } if (type == kSize) { if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } for (i = 0; i < unpack_streams; i++) { ss->digestsDefined[i] = 0; ss->digests[i] = 0; } numDigests = 0; for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) numDigests += (uint32_t)f[i].numUnpackStreams; } if (type == kCRC) { struct _7z_digests tmpDigests; unsigned char *digestsDefined = ss->digestsDefined; uint32_t * digests = ss->digests; int di = 0; memset(&tmpDigests, 0, sizeof(tmpDigests)); if (read_Digests(a, &(tmpDigests), numDigests) < 0) { free_Digest(&tmpDigests); return (-1); } for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { *digestsDefined++ = 1; *digests++ = f[i].digest; } else { unsigned j; for (j = 0; j < f[i].numUnpackStreams; j++, di++) { *digestsDefined++ = tmpDigests.defineds[di]; *digests++ = tmpDigests.digests[di]; } } } free_Digest(&tmpDigests); if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } /* * Must be kEnd. */ if (type != kEnd) return (-1); return (0); } Commit Message: Issue #718: Fix TALOS-CAN-152 If a 7-Zip archive declares a rediculously large number of substreams, it can overflow an internal counter, leading a subsequent memory allocation to be too small for the substream data. Thanks to the Open Source and Threat Intelligence project at Cisco for reporting this issue. CWE ID: CWE-190
read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, struct _7z_folder *f, size_t numFolders) { const unsigned char *p; uint64_t *usizes; size_t unpack_streams; int type; unsigned i; uint32_t numDigests; memset(ss, 0, sizeof(*ss)); for (i = 0; i < numFolders; i++) f[i].numUnpackStreams = 1; if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; if (type == kNumUnPackStream) { unpack_streams = 0; for (i = 0; i < numFolders; i++) { if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) return (-1); if (UMAX_ENTRY < f[i].numUnpackStreams) return (-1); if (unpack_streams > SIZE_MAX - UMAX_ENTRY) { return (-1); } unpack_streams += (size_t)f[i].numUnpackStreams; } if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } else unpack_streams = numFolders; ss->unpack_streams = unpack_streams; if (unpack_streams) { ss->unpackSizes = calloc(unpack_streams, sizeof(*ss->unpackSizes)); ss->digestsDefined = calloc(unpack_streams, sizeof(*ss->digestsDefined)); ss->digests = calloc(unpack_streams, sizeof(*ss->digests)); if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || ss->digests == NULL) return (-1); } usizes = ss->unpackSizes; for (i = 0; i < numFolders; i++) { unsigned pack; uint64_t sum; if (f[i].numUnpackStreams == 0) continue; sum = 0; if (type == kSize) { for (pack = 1; pack < f[i].numUnpackStreams; pack++) { if (parse_7zip_uint64(a, usizes) < 0) return (-1); sum += *usizes++; } } *usizes++ = folder_uncompressed_size(&f[i]) - sum; } if (type == kSize) { if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } for (i = 0; i < unpack_streams; i++) { ss->digestsDefined[i] = 0; ss->digests[i] = 0; } numDigests = 0; for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) numDigests += (uint32_t)f[i].numUnpackStreams; } if (type == kCRC) { struct _7z_digests tmpDigests; unsigned char *digestsDefined = ss->digestsDefined; uint32_t * digests = ss->digests; int di = 0; memset(&tmpDigests, 0, sizeof(tmpDigests)); if (read_Digests(a, &(tmpDigests), numDigests) < 0) { free_Digest(&tmpDigests); return (-1); } for (i = 0; i < numFolders; i++) { if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { *digestsDefined++ = 1; *digests++ = f[i].digest; } else { unsigned j; for (j = 0; j < f[i].numUnpackStreams; j++, di++) { *digestsDefined++ = tmpDigests.defineds[di]; *digests++ = tmpDigests.digests[di]; } } } free_Digest(&tmpDigests); if ((p = header_bytes(a, 1)) == NULL) return (-1); type = *p; } /* * Must be kEnd. */ if (type != kEnd) return (-1); return (0); }
167,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string &element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { *upload_required_ = USE_UPLOAD_RATES; if (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string& element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { // We check for the upload required attribute below, but if it's not // present, we use the default upload rates. Likewise, by default we assume // an empty experiment id. *upload_required_ = USE_UPLOAD_RATES; *experiment_id_ = std::string(); // |attrs| is a NULL-terminated list of (attribute, value) pairs. while (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } else if (attribute_name.compare("experimentid") == 0) { *experiment_id_ = attrs[1]; } // Advance to the next (attribute, value) pair. attrs += 2; } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } }
170,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_GetObjectItem( cJSON *object, const char *string ) { cJSON *c = object->child; while ( c && cJSON_strcasecmp( c->string, string ) ) c = c->next; return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_GetObjectItem( cJSON *object, const char *string )
167,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: atm_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t llchdr; u_int hdrlen = 0; if (caplen < 1 || length < 1) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* Cisco Style NLPID ? */ if (*p == LLC_UI) { if (ndo->ndo_eflag) ND_PRINT((ndo, "CNLPID ")); isoclns_print(ndo, p + 1, length - 1, caplen - 1); return hdrlen; } /* * Must have at least a DSAP, an SSAP, and the first byte of the * control field. */ if (caplen < 3 || length < 3) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* * Extract the presumed LLC header into a variable, for quick * testing. * Then check for a header that's neither a header for a SNAP * packet nor an RFC 2684 routed NLPID-formatted PDU nor * an 802.2-but-no-SNAP IP packet. */ llchdr = EXTRACT_24BITS(p); if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) && llchdr != LLC_UI_HDR(LLCSAP_ISONS) && llchdr != LLC_UI_HDR(LLCSAP_IP)) { /* * XXX - assume 802.6 MAC header from Fore driver. * * Unfortunately, the above list doesn't check for * all known SAPs, doesn't check for headers where * the source and destination SAP aren't the same, * and doesn't check for non-UI frames. It also * runs the risk of an 802.6 MAC header that happens * to begin with one of those values being * incorrectly treated as an 802.2 header. * * So is that Fore driver still around? And, if so, * is it still putting 802.6 MAC headers on ATM * packets? If so, could it be changed to use a * new DLT_IEEE802_6 value if we added it? */ if (caplen < 20 || length < 20) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%08x%08x %08x%08x ", EXTRACT_32BITS(p), EXTRACT_32BITS(p+4), EXTRACT_32BITS(p+8), EXTRACT_32BITS(p+12))); p += 20; length -= 20; caplen -= 20; hdrlen += 20; } hdrlen += atm_llc_print(ndo, p, length, caplen); return (hdrlen); } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
atm_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t llchdr; u_int hdrlen = 0; if (caplen < 1 || length < 1) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* Cisco Style NLPID ? */ if (*p == LLC_UI) { if (ndo->ndo_eflag) ND_PRINT((ndo, "CNLPID ")); isoclns_print(ndo, p + 1, length - 1); return hdrlen; } /* * Must have at least a DSAP, an SSAP, and the first byte of the * control field. */ if (caplen < 3 || length < 3) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* * Extract the presumed LLC header into a variable, for quick * testing. * Then check for a header that's neither a header for a SNAP * packet nor an RFC 2684 routed NLPID-formatted PDU nor * an 802.2-but-no-SNAP IP packet. */ llchdr = EXTRACT_24BITS(p); if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) && llchdr != LLC_UI_HDR(LLCSAP_ISONS) && llchdr != LLC_UI_HDR(LLCSAP_IP)) { /* * XXX - assume 802.6 MAC header from Fore driver. * * Unfortunately, the above list doesn't check for * all known SAPs, doesn't check for headers where * the source and destination SAP aren't the same, * and doesn't check for non-UI frames. It also * runs the risk of an 802.6 MAC header that happens * to begin with one of those values being * incorrectly treated as an 802.2 header. * * So is that Fore driver still around? And, if so, * is it still putting 802.6 MAC headers on ATM * packets? If so, could it be changed to use a * new DLT_IEEE802_6 value if we added it? */ if (caplen < 20 || length < 20) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%08x%08x %08x%08x ", EXTRACT_32BITS(p), EXTRACT_32BITS(p+4), EXTRACT_32BITS(p+8), EXTRACT_32BITS(p+12))); p += 20; length -= 20; caplen -= 20; hdrlen += 20; } hdrlen += atm_llc_print(ndo, p, length, caplen); return (hdrlen); }
167,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunNestedLoopTask(int* counter) { RunLoop nested_run_loop; ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&nested_run_loop), Unretained(counter))); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, BindOnce(&ShouldNotRunTask), TimeDelta::FromDays(1)); std::unique_ptr<MessageLoop::ScopedNestableTaskAllower> allower; if (MessageLoop::current()) { allower = base::MakeUnique<MessageLoop::ScopedNestableTaskAllower>( MessageLoop::current()); } nested_run_loop.Run(); ++(*counter); } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). [email protected] Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <[email protected]> Reviewed-by: Robert Liao <[email protected]> Reviewed-by: danakj <[email protected]> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID:
void RunNestedLoopTask(int* counter) { RunLoop nested_run_loop(RunLoop::Type::kNestableTasksAllowed); ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, BindOnce(&QuitWhenIdleTask, Unretained(&nested_run_loop), Unretained(counter))); ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, BindOnce(&ShouldNotRunTask), TimeDelta::FromDays(1)); nested_run_loop.Run(); ++(*counter); }
171,870
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int command_write(struct pci_dev *dev, int offset, u16 value, void *data) { struct xen_pcibk_dev_data *dev_data; int err; dev_data = pci_get_drvdata(dev); if (!pci_is_enabled(dev) && is_enable_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: enable\n", pci_name(dev)); err = pci_enable_device(dev); if (err) return err; if (dev_data) dev_data->enable_intx = 1; } else if (pci_is_enabled(dev) && !is_enable_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: disable\n", pci_name(dev)); pci_disable_device(dev); if (dev_data) dev_data->enable_intx = 0; } if (!dev->is_busmaster && is_master_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: set bus master\n", pci_name(dev)); pci_set_master(dev); } if (value & PCI_COMMAND_INVALIDATE) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: enable memory-write-invalidate\n", pci_name(dev)); err = pci_set_mwi(dev); if (err) { pr_warn("%s: cannot enable memory-write-invalidate (%d)\n", pci_name(dev), err); value &= ~PCI_COMMAND_INVALIDATE; } } return pci_write_config_word(dev, offset, value); } Commit Message: xen-pciback: limit guest control of command register Otherwise the guest can abuse that control to cause e.g. PCIe Unsupported Request responses by disabling memory and/or I/O decoding and subsequently causing (CPU side) accesses to the respective address ranges, which (depending on system configuration) may be fatal to the host. Note that to alter any of the bits collected together as PCI_COMMAND_GUEST permissive mode is now required to be enabled globally or on the specific device. This is CVE-2015-2150 / XSA-120. Signed-off-by: Jan Beulich <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Cc: <[email protected]> Signed-off-by: David Vrabel <[email protected]> CWE ID: CWE-264
static int command_write(struct pci_dev *dev, int offset, u16 value, void *data) { struct xen_pcibk_dev_data *dev_data; int err; u16 val; struct pci_cmd_info *cmd = data; dev_data = pci_get_drvdata(dev); if (!pci_is_enabled(dev) && is_enable_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: enable\n", pci_name(dev)); err = pci_enable_device(dev); if (err) return err; if (dev_data) dev_data->enable_intx = 1; } else if (pci_is_enabled(dev) && !is_enable_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: disable\n", pci_name(dev)); pci_disable_device(dev); if (dev_data) dev_data->enable_intx = 0; } if (!dev->is_busmaster && is_master_cmd(value)) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: set bus master\n", pci_name(dev)); pci_set_master(dev); } if (value & PCI_COMMAND_INVALIDATE) { if (unlikely(verbose_request)) printk(KERN_DEBUG DRV_NAME ": %s: enable memory-write-invalidate\n", pci_name(dev)); err = pci_set_mwi(dev); if (err) { pr_warn("%s: cannot enable memory-write-invalidate (%d)\n", pci_name(dev), err); value &= ~PCI_COMMAND_INVALIDATE; } } cmd->val = value; if (!permissive && (!dev_data || !dev_data->permissive)) return 0; /* Only allow the guest to control certain bits. */ err = pci_read_config_word(dev, offset, &val); if (err || val == value) return err; value &= PCI_COMMAND_GUEST; value |= val & ~PCI_COMMAND_GUEST; return pci_write_config_word(dev, offset, value); }
166,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ip_queue_xmit(struct sk_buff *skb) { struct sock *sk = skb->sk; struct inet_sock *inet = inet_sk(sk); struct ip_options *opt = inet->opt; struct rtable *rt; struct iphdr *iph; int res; /* Skip all of this if the packet is already routed, * f.e. by something like SCTP. */ rcu_read_lock(); rt = skb_rtable(skb); if (rt != NULL) goto packet_routed; /* Make sure we can route this packet. */ rt = (struct rtable *)__sk_dst_check(sk, 0); if (rt == NULL) { __be32 daddr; /* Use correct destination address if we have options. */ daddr = inet->inet_daddr; if(opt && opt->srr) daddr = opt->faddr; /* If this fails, retransmit mechanism of transport layer will * keep trying until route appears or the connection times * itself out. */ rt = ip_route_output_ports(sock_net(sk), sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (IS_ERR(rt)) goto no_route; sk_setup_caps(sk, &rt->dst); } skb_dst_set_noref(skb, &rt->dst); packet_routed: if (opt && opt->is_strictroute && rt->rt_dst != rt->rt_gateway) goto no_route; /* OK, we know where to send it, allocate and build IP header. */ skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0)); skb_reset_network_header(skb); iph = ip_hdr(skb); *((__be16 *)iph) = htons((4 << 12) | (5 << 8) | (inet->tos & 0xff)); if (ip_dont_fragment(sk, &rt->dst) && !skb->local_df) iph->frag_off = htons(IP_DF); else iph->frag_off = 0; iph->ttl = ip_select_ttl(inet, &rt->dst); iph->protocol = sk->sk_protocol; iph->saddr = rt->rt_src; iph->daddr = rt->rt_dst; /* Transport layer set skb->h.foo itself. */ if (opt && opt->optlen) { iph->ihl += opt->optlen >> 2; ip_options_build(skb, opt, inet->inet_daddr, rt, 0); } ip_select_ident_more(iph, &rt->dst, sk, (skb_shinfo(skb)->gso_segs ?: 1) - 1); skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; res = ip_local_out(skb); rcu_read_unlock(); return res; no_route: rcu_read_unlock(); IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EHOSTUNREACH; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
int ip_queue_xmit(struct sk_buff *skb) { struct sock *sk = skb->sk; struct inet_sock *inet = inet_sk(sk); struct ip_options_rcu *inet_opt; struct rtable *rt; struct iphdr *iph; int res; /* Skip all of this if the packet is already routed, * f.e. by something like SCTP. */ rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); rt = skb_rtable(skb); if (rt != NULL) goto packet_routed; /* Make sure we can route this packet. */ rt = (struct rtable *)__sk_dst_check(sk, 0); if (rt == NULL) { __be32 daddr; /* Use correct destination address if we have options. */ daddr = inet->inet_daddr; if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; /* If this fails, retransmit mechanism of transport layer will * keep trying until route appears or the connection times * itself out. */ rt = ip_route_output_ports(sock_net(sk), sk, daddr, inet->inet_saddr, inet->inet_dport, inet->inet_sport, sk->sk_protocol, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if); if (IS_ERR(rt)) goto no_route; sk_setup_caps(sk, &rt->dst); } skb_dst_set_noref(skb, &rt->dst); packet_routed: if (inet_opt && inet_opt->opt.is_strictroute && rt->rt_dst != rt->rt_gateway) goto no_route; /* OK, we know where to send it, allocate and build IP header. */ skb_push(skb, sizeof(struct iphdr) + (inet_opt ? inet_opt->opt.optlen : 0)); skb_reset_network_header(skb); iph = ip_hdr(skb); *((__be16 *)iph) = htons((4 << 12) | (5 << 8) | (inet->tos & 0xff)); if (ip_dont_fragment(sk, &rt->dst) && !skb->local_df) iph->frag_off = htons(IP_DF); else iph->frag_off = 0; iph->ttl = ip_select_ttl(inet, &rt->dst); iph->protocol = sk->sk_protocol; iph->saddr = rt->rt_src; iph->daddr = rt->rt_dst; /* Transport layer set skb->h.foo itself. */ if (inet_opt && inet_opt->opt.optlen) { iph->ihl += inet_opt->opt.optlen >> 2; ip_options_build(skb, &inet_opt->opt, inet->inet_daddr, rt, 0); } ip_select_ident_more(iph, &rt->dst, sk, (skb_shinfo(skb)->gso_segs ?: 1) - 1); skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; res = ip_local_out(skb); rcu_read_unlock(); return res; no_route: rcu_read_unlock(); IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EHOSTUNREACH; }
165,563
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); unsigned long debugctlmsr; /* Record the guest's net vcpu time for enforced NMI injections. */ if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked)) vmx->entry_time = ktime_get(); /* Don't enter VMX if guest state is invalid, let the exit handler start emulation until we arrive back to a valid state */ if (vmx->emulation_required) return; if (vmx->ple_window_dirty) { vmx->ple_window_dirty = false; vmcs_write32(PLE_WINDOW, vmx->ple_window); } if (vmx->nested.sync_shadow_vmcs) { copy_vmcs12_to_shadow(vmx); vmx->nested.sync_shadow_vmcs = false; } if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty)) vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]); if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty)) vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]); /* When single-stepping over STI and MOV SS, we must clear the * corresponding interruptibility bits in the guest state. Otherwise * vmentry fails as it then expects bit 14 (BS) in pending debug * exceptions being set, but that's not correct for the guest debugging * case. */ if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) vmx_set_interrupt_shadow(vcpu, 0); atomic_switch_perf_msrs(vmx); debugctlmsr = get_debugctlmsr(); vmx->__launched = vmx->loaded_vmcs->launched; asm( /* Store host registers */ "push %%" _ASM_DX "; push %%" _ASM_BP ";" "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */ "push %%" _ASM_CX " \n\t" "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t" "je 1f \n\t" "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t" __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t" "1: \n\t" /* Reload cr2 if changed */ "mov %c[cr2](%0), %%" _ASM_AX " \n\t" "mov %%cr2, %%" _ASM_DX " \n\t" "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t" "je 2f \n\t" "mov %%" _ASM_AX", %%cr2 \n\t" "2: \n\t" /* Check if vmlaunch of vmresume is needed */ "cmpl $0, %c[launched](%0) \n\t" /* Load guest registers. Don't clobber flags. */ "mov %c[rax](%0), %%" _ASM_AX " \n\t" "mov %c[rbx](%0), %%" _ASM_BX " \n\t" "mov %c[rdx](%0), %%" _ASM_DX " \n\t" "mov %c[rsi](%0), %%" _ASM_SI " \n\t" "mov %c[rdi](%0), %%" _ASM_DI " \n\t" "mov %c[rbp](%0), %%" _ASM_BP " \n\t" #ifdef CONFIG_X86_64 "mov %c[r8](%0), %%r8 \n\t" "mov %c[r9](%0), %%r9 \n\t" "mov %c[r10](%0), %%r10 \n\t" "mov %c[r11](%0), %%r11 \n\t" "mov %c[r12](%0), %%r12 \n\t" "mov %c[r13](%0), %%r13 \n\t" "mov %c[r14](%0), %%r14 \n\t" "mov %c[r15](%0), %%r15 \n\t" #endif "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */ /* Enter guest mode */ "jne 1f \n\t" __ex(ASM_VMX_VMLAUNCH) "\n\t" "jmp 2f \n\t" "1: " __ex(ASM_VMX_VMRESUME) "\n\t" "2: " /* Save guest registers, load host registers, keep flags */ "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t" "pop %0 \n\t" "mov %%" _ASM_AX ", %c[rax](%0) \n\t" "mov %%" _ASM_BX ", %c[rbx](%0) \n\t" __ASM_SIZE(pop) " %c[rcx](%0) \n\t" "mov %%" _ASM_DX ", %c[rdx](%0) \n\t" "mov %%" _ASM_SI ", %c[rsi](%0) \n\t" "mov %%" _ASM_DI ", %c[rdi](%0) \n\t" "mov %%" _ASM_BP ", %c[rbp](%0) \n\t" #ifdef CONFIG_X86_64 "mov %%r8, %c[r8](%0) \n\t" "mov %%r9, %c[r9](%0) \n\t" "mov %%r10, %c[r10](%0) \n\t" "mov %%r11, %c[r11](%0) \n\t" "mov %%r12, %c[r12](%0) \n\t" "mov %%r13, %c[r13](%0) \n\t" "mov %%r14, %c[r14](%0) \n\t" "mov %%r15, %c[r15](%0) \n\t" #endif "mov %%cr2, %%" _ASM_AX " \n\t" "mov %%" _ASM_AX ", %c[cr2](%0) \n\t" "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t" "setbe %c[fail](%0) \n\t" ".pushsection .rodata \n\t" ".global vmx_return \n\t" "vmx_return: " _ASM_PTR " 2b \n\t" ".popsection" : : "c"(vmx), "d"((unsigned long)HOST_RSP), [launched]"i"(offsetof(struct vcpu_vmx, __launched)), [fail]"i"(offsetof(struct vcpu_vmx, fail)), [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)), [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])), [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])), [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])), [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])), [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])), [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])), [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])), #ifdef CONFIG_X86_64 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])), [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])), [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])), [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])), [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])), [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])), [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])), [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])), #endif [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)), [wordsize]"i"(sizeof(ulong)) : "cc", "memory" #ifdef CONFIG_X86_64 , "rax", "rbx", "rdi", "rsi" , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" #else , "eax", "ebx", "edi", "esi" #endif ); /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */ if (debugctlmsr) update_debugctlmsr(debugctlmsr); #ifndef CONFIG_X86_64 /* * The sysexit path does not restore ds/es, so we must set them to * a reasonable value ourselves. * * We can't defer this to vmx_load_host_state() since that function * may be executed in interrupt context, which saves and restore segments * around it, nullifying its effect. */ loadsegment(ds, __USER_DS); loadsegment(es, __USER_DS); #endif vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP) | (1 << VCPU_EXREG_RFLAGS) | (1 << VCPU_EXREG_PDPTR) | (1 << VCPU_EXREG_SEGMENTS) | (1 << VCPU_EXREG_CR3)); vcpu->arch.regs_dirty = 0; vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD); vmx->loaded_vmcs->launched = 1; vmx->exit_reason = vmcs_read32(VM_EXIT_REASON); trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX); /* * the KVM_REQ_EVENT optimization bit is only on for one entry, and if * we did not inject a still-pending event to L1 now because of * nested_run_pending, we need to re-enable this bit. */ if (vmx->nested.nested_run_pending) kvm_make_request(KVM_REQ_EVENT, vcpu); vmx->nested.nested_run_pending = 0; vmx_complete_atomic_exit(vmx); vmx_recover_nmi_blocking(vmx); vmx_complete_interrupts(vmx); } Commit Message: x86,kvm,vmx: Preserve CR4 across VM entry CR4 isn't constant; at least the TSD and PCE bits can vary. TBH, treating CR0 and CR3 as constant scares me a bit, too, but it looks like it's correct. This adds a branch and a read from cr4 to each vm entry. Because it is extremely likely that consecutive entries into the same vcpu will have the same host cr4 value, this fixes up the vmcs instead of restoring cr4 after the fact. A subsequent patch will add a kernel-wide cr4 shadow, reducing the overhead in the common case to just two memory reads and a branch. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: Paolo Bonzini <[email protected]> Cc: [email protected] Cc: Petr Matousek <[email protected]> Cc: Gleb Natapov <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static void __noclone vmx_vcpu_run(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); unsigned long debugctlmsr, cr4; /* Record the guest's net vcpu time for enforced NMI injections. */ if (unlikely(!cpu_has_virtual_nmis() && vmx->soft_vnmi_blocked)) vmx->entry_time = ktime_get(); /* Don't enter VMX if guest state is invalid, let the exit handler start emulation until we arrive back to a valid state */ if (vmx->emulation_required) return; if (vmx->ple_window_dirty) { vmx->ple_window_dirty = false; vmcs_write32(PLE_WINDOW, vmx->ple_window); } if (vmx->nested.sync_shadow_vmcs) { copy_vmcs12_to_shadow(vmx); vmx->nested.sync_shadow_vmcs = false; } if (test_bit(VCPU_REGS_RSP, (unsigned long *)&vcpu->arch.regs_dirty)) vmcs_writel(GUEST_RSP, vcpu->arch.regs[VCPU_REGS_RSP]); if (test_bit(VCPU_REGS_RIP, (unsigned long *)&vcpu->arch.regs_dirty)) vmcs_writel(GUEST_RIP, vcpu->arch.regs[VCPU_REGS_RIP]); cr4 = read_cr4(); if (unlikely(cr4 != vmx->host_state.vmcs_host_cr4)) { vmcs_writel(HOST_CR4, cr4); vmx->host_state.vmcs_host_cr4 = cr4; } /* When single-stepping over STI and MOV SS, we must clear the * corresponding interruptibility bits in the guest state. Otherwise * vmentry fails as it then expects bit 14 (BS) in pending debug * exceptions being set, but that's not correct for the guest debugging * case. */ if (vcpu->guest_debug & KVM_GUESTDBG_SINGLESTEP) vmx_set_interrupt_shadow(vcpu, 0); atomic_switch_perf_msrs(vmx); debugctlmsr = get_debugctlmsr(); vmx->__launched = vmx->loaded_vmcs->launched; asm( /* Store host registers */ "push %%" _ASM_DX "; push %%" _ASM_BP ";" "push %%" _ASM_CX " \n\t" /* placeholder for guest rcx */ "push %%" _ASM_CX " \n\t" "cmp %%" _ASM_SP ", %c[host_rsp](%0) \n\t" "je 1f \n\t" "mov %%" _ASM_SP ", %c[host_rsp](%0) \n\t" __ex(ASM_VMX_VMWRITE_RSP_RDX) "\n\t" "1: \n\t" /* Reload cr2 if changed */ "mov %c[cr2](%0), %%" _ASM_AX " \n\t" "mov %%cr2, %%" _ASM_DX " \n\t" "cmp %%" _ASM_AX ", %%" _ASM_DX " \n\t" "je 2f \n\t" "mov %%" _ASM_AX", %%cr2 \n\t" "2: \n\t" /* Check if vmlaunch of vmresume is needed */ "cmpl $0, %c[launched](%0) \n\t" /* Load guest registers. Don't clobber flags. */ "mov %c[rax](%0), %%" _ASM_AX " \n\t" "mov %c[rbx](%0), %%" _ASM_BX " \n\t" "mov %c[rdx](%0), %%" _ASM_DX " \n\t" "mov %c[rsi](%0), %%" _ASM_SI " \n\t" "mov %c[rdi](%0), %%" _ASM_DI " \n\t" "mov %c[rbp](%0), %%" _ASM_BP " \n\t" #ifdef CONFIG_X86_64 "mov %c[r8](%0), %%r8 \n\t" "mov %c[r9](%0), %%r9 \n\t" "mov %c[r10](%0), %%r10 \n\t" "mov %c[r11](%0), %%r11 \n\t" "mov %c[r12](%0), %%r12 \n\t" "mov %c[r13](%0), %%r13 \n\t" "mov %c[r14](%0), %%r14 \n\t" "mov %c[r15](%0), %%r15 \n\t" #endif "mov %c[rcx](%0), %%" _ASM_CX " \n\t" /* kills %0 (ecx) */ /* Enter guest mode */ "jne 1f \n\t" __ex(ASM_VMX_VMLAUNCH) "\n\t" "jmp 2f \n\t" "1: " __ex(ASM_VMX_VMRESUME) "\n\t" "2: " /* Save guest registers, load host registers, keep flags */ "mov %0, %c[wordsize](%%" _ASM_SP ") \n\t" "pop %0 \n\t" "mov %%" _ASM_AX ", %c[rax](%0) \n\t" "mov %%" _ASM_BX ", %c[rbx](%0) \n\t" __ASM_SIZE(pop) " %c[rcx](%0) \n\t" "mov %%" _ASM_DX ", %c[rdx](%0) \n\t" "mov %%" _ASM_SI ", %c[rsi](%0) \n\t" "mov %%" _ASM_DI ", %c[rdi](%0) \n\t" "mov %%" _ASM_BP ", %c[rbp](%0) \n\t" #ifdef CONFIG_X86_64 "mov %%r8, %c[r8](%0) \n\t" "mov %%r9, %c[r9](%0) \n\t" "mov %%r10, %c[r10](%0) \n\t" "mov %%r11, %c[r11](%0) \n\t" "mov %%r12, %c[r12](%0) \n\t" "mov %%r13, %c[r13](%0) \n\t" "mov %%r14, %c[r14](%0) \n\t" "mov %%r15, %c[r15](%0) \n\t" #endif "mov %%cr2, %%" _ASM_AX " \n\t" "mov %%" _ASM_AX ", %c[cr2](%0) \n\t" "pop %%" _ASM_BP "; pop %%" _ASM_DX " \n\t" "setbe %c[fail](%0) \n\t" ".pushsection .rodata \n\t" ".global vmx_return \n\t" "vmx_return: " _ASM_PTR " 2b \n\t" ".popsection" : : "c"(vmx), "d"((unsigned long)HOST_RSP), [launched]"i"(offsetof(struct vcpu_vmx, __launched)), [fail]"i"(offsetof(struct vcpu_vmx, fail)), [host_rsp]"i"(offsetof(struct vcpu_vmx, host_rsp)), [rax]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RAX])), [rbx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBX])), [rcx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RCX])), [rdx]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDX])), [rsi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RSI])), [rdi]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RDI])), [rbp]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_RBP])), #ifdef CONFIG_X86_64 [r8]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R8])), [r9]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R9])), [r10]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R10])), [r11]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R11])), [r12]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R12])), [r13]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R13])), [r14]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R14])), [r15]"i"(offsetof(struct vcpu_vmx, vcpu.arch.regs[VCPU_REGS_R15])), #endif [cr2]"i"(offsetof(struct vcpu_vmx, vcpu.arch.cr2)), [wordsize]"i"(sizeof(ulong)) : "cc", "memory" #ifdef CONFIG_X86_64 , "rax", "rbx", "rdi", "rsi" , "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" #else , "eax", "ebx", "edi", "esi" #endif ); /* MSR_IA32_DEBUGCTLMSR is zeroed on vmexit. Restore it if needed */ if (debugctlmsr) update_debugctlmsr(debugctlmsr); #ifndef CONFIG_X86_64 /* * The sysexit path does not restore ds/es, so we must set them to * a reasonable value ourselves. * * We can't defer this to vmx_load_host_state() since that function * may be executed in interrupt context, which saves and restore segments * around it, nullifying its effect. */ loadsegment(ds, __USER_DS); loadsegment(es, __USER_DS); #endif vcpu->arch.regs_avail = ~((1 << VCPU_REGS_RIP) | (1 << VCPU_REGS_RSP) | (1 << VCPU_EXREG_RFLAGS) | (1 << VCPU_EXREG_PDPTR) | (1 << VCPU_EXREG_SEGMENTS) | (1 << VCPU_EXREG_CR3)); vcpu->arch.regs_dirty = 0; vmx->idt_vectoring_info = vmcs_read32(IDT_VECTORING_INFO_FIELD); vmx->loaded_vmcs->launched = 1; vmx->exit_reason = vmcs_read32(VM_EXIT_REASON); trace_kvm_exit(vmx->exit_reason, vcpu, KVM_ISA_VMX); /* * the KVM_REQ_EVENT optimization bit is only on for one entry, and if * we did not inject a still-pending event to L1 now because of * nested_run_pending, we need to re-enable this bit. */ if (vmx->nested.nested_run_pending) kvm_make_request(KVM_REQ_EVENT, vcpu); vmx->nested.nested_run_pending = 0; vmx_complete_atomic_exit(vmx); vmx_recover_nmi_blocking(vmx); vmx_complete_interrupts(vmx); }
166,329
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseCharRef(xmlParserCtxtPtr ctxt) { unsigned int val = 0; int count = 0; unsigned int outofrange = 0; /* * Using RAW/CUR/NEXT is okay since we are working on ASCII range here */ if ((RAW == '&') && (NXT(1) == '#') && (NXT(2) == 'x')) { SKIP(3); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; } if ((RAW >= '0') && (RAW <= '9')) val = val * 16 + (CUR - '0'); else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20)) val = val * 16 + (CUR - 'a') + 10; else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20)) val = val * 16 + (CUR - 'A') + 10; else { xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else if ((RAW == '&') && (NXT(1) == '#')) { SKIP(2); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; } if ((RAW >= '0') && (RAW <= '9')) val = val * 10 + (CUR - '0'); else { xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else { xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL); } /* * [ WFC: Legal Character ] * Characters referred to using character references must match the * production for Char. */ if ((IS_CHAR(val) && (outofrange == 0))) { return(val); } else { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseCharRef: invalid xmlChar value %d\n", val); } return(0); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseCharRef(xmlParserCtxtPtr ctxt) { unsigned int val = 0; int count = 0; unsigned int outofrange = 0; /* * Using RAW/CUR/NEXT is okay since we are working on ASCII range here */ if ((RAW == '&') && (NXT(1) == '#') && (NXT(2) == 'x')) { SKIP(3); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(0); } if ((RAW >= '0') && (RAW <= '9')) val = val * 16 + (CUR - '0'); else if ((RAW >= 'a') && (RAW <= 'f') && (count < 20)) val = val * 16 + (CUR - 'a') + 10; else if ((RAW >= 'A') && (RAW <= 'F') && (count < 20)) val = val * 16 + (CUR - 'A') + 10; else { xmlFatalErr(ctxt, XML_ERR_INVALID_HEX_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else if ((RAW == '&') && (NXT(1) == '#')) { SKIP(2); GROW; while (RAW != ';') { /* loop blocked by count */ if (count++ > 20) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) return(0); } if ((RAW >= '0') && (RAW <= '9')) val = val * 10 + (CUR - '0'); else { xmlFatalErr(ctxt, XML_ERR_INVALID_DEC_CHARREF, NULL); val = 0; break; } if (val > 0x10FFFF) outofrange = val; NEXT; count++; } if (RAW == ';') { /* on purpose to avoid reentrancy problems with NEXT and SKIP */ ctxt->input->col++; ctxt->nbChars ++; ctxt->input->cur++; } } else { xmlFatalErr(ctxt, XML_ERR_INVALID_CHARREF, NULL); } /* * [ WFC: Legal Character ] * Characters referred to using character references must match the * production for Char. */ if ((IS_CHAR(val) && (outofrange == 0))) { return(val); } else { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlParseCharRef: invalid xmlChar value %d\n", val); } return(0); }
171,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: write_message( RenderState state ) { ADisplay adisplay = (ADisplay)state->display.disp; if ( state->message == NULL ) { FontFace face = &state->faces[state->face_index]; int idx, total; idx = face->index; total = 1; while ( total + state->face_index < state->num_faces && face[total].filepath == face[0].filepath ) total++; total += idx; state->message = state->message0; if ( total > 1 ) sprintf( state->message0, "%s %d/%d @ %5.1fpt", state->filename, idx + 1, total, state->char_size ); else sprintf( state->message0, "%s @ %5.1fpt", state->filename, state->char_size ); } grWriteCellString( adisplay->bitmap, 0, DIM_Y - 10, state->message, adisplay->fore_color ); state->message = NULL; } Commit Message: CWE ID: CWE-119
write_message( RenderState state ) { ADisplay adisplay = (ADisplay)state->display.disp; if ( state->message == NULL ) { FontFace face = &state->faces[state->face_index]; int idx, total; idx = face->index; total = 1; while ( total + state->face_index < state->num_faces && face[total].filepath == face[0].filepath ) total++; total += idx; state->message = state->message0; if ( total > 1 ) sprintf( state->message0, "%.100s %d/%d @ %5.1fpt", state->filename, idx + 1, total, state->char_size ); else sprintf( state->message0, "%.100s @ %5.1fpt", state->filename, state->char_size ); } grWriteCellString( adisplay->bitmap, 0, DIM_Y - 10, state->message, adisplay->fore_color ); state->message = NULL; }
164,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(data_reduction_proxy_service_->compression_stats()); if (spdy_proxy_auth_enabled_.GetValue() != enabled) { spdy_proxy_auth_enabled_.SetValue(enabled); OnProxyEnabledPrefChange(); #if defined(OS_ANDROID) data_reduction_proxy_service_->compression_stats() ->SetDataUsageReportingEnabled(enabled); #endif // defined(OS_ANDROID) } } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
void DataReductionProxySettings::SetDataReductionProxyEnabled(bool enabled) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(data_reduction_proxy_service_->compression_stats()); if (GetOriginalProfilePrefs()->GetBoolean(prefs::kDataSaverEnabled) != enabled) { GetOriginalProfilePrefs()->SetBoolean(prefs::kDataSaverEnabled, enabled); OnProxyEnabledPrefChange(); #if defined(OS_ANDROID) data_reduction_proxy_service_->compression_stats() ->SetDataUsageReportingEnabled(enabled); #endif // defined(OS_ANDROID) } }
172,558
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) { #if LUA_VERSION_NUM < 502 size_t len = lua_objlen(L,-1), j; #else size_t len = lua_rawlen(L,-1), j; #endif mp_encode_array(L,buf,len); for (j = 1; j <= len; j++) { lua_pushnumber(L,j); lua_gettable(L,-2); mp_encode_lua_type(L,buf,level+1); } } Commit Message: Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems. CWE ID: CWE-119
void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) { #if LUA_VERSION_NUM < 502 size_t len = lua_objlen(L,-1), j; #else size_t len = lua_rawlen(L,-1), j; #endif mp_encode_array(L,buf,len); luaL_checkstack(L, 1, "in function mp_encode_lua_table_as_array"); for (j = 1; j <= len; j++) { lua_pushnumber(L,j); lua_gettable(L,-2); mp_encode_lua_type(L,buf,level+1); } }
169,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const { return url.SchemeIs(chrome::kChromeDevToolsScheme) || url.SchemeIs(chrome::kChromeInternalScheme) || url.SchemeIs(chrome::kChromeUIScheme); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ChromeWebUIControllerFactory::HasWebUIScheme(const GURL& url) const {
171,008
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScriptPromise Bluetooth::requestDevice(ScriptState* script_state, const RequestDeviceOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_MACOSX) && \ !defined(OS_WIN) context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); #endif CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } if (!service_) { frame->GetInterfaceProvider().GetInterface(mojo::MakeRequest( &service_, context->GetTaskRunner(TaskType::kMiscPlatformAPI))); } auto device_options = mojom::blink::WebBluetoothRequestDeviceOptions::New(); ConvertRequestDeviceOptions(options, device_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); service_->RequestDevice( std::move(device_options), WTF::Bind(&Bluetooth::RequestDeviceCallback, WrapPersistent(this), WrapPersistent(resolver))); return promise; } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <[email protected]> Reviewed-by: Giovanni Ortuño Urquidi <[email protected]> Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <[email protected]> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
ScriptPromise Bluetooth::requestDevice(ScriptState* script_state, const RequestDeviceOptions* options, ExceptionState& exception_state) { ExecutionContext* context = ExecutionContext::From(script_state); #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID) && !defined(OS_MACOSX) && \ !defined(OS_WIN) context->AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kInfo, "Web Bluetooth is experimental on this platform. See " "https://github.com/WebBluetoothCG/web-bluetooth/blob/gh-pages/" "implementation-status.md")); #endif CHECK(context->IsSecureContext()); auto& doc = *To<Document>(context); auto* frame = doc.GetFrame(); if (!frame) { return ScriptPromise::Reject( script_state, V8ThrowException::CreateTypeError( script_state->GetIsolate(), "Document not active")); } if (!LocalFrame::HasTransientUserActivation(frame)) { return ScriptPromise::RejectWithDOMException( script_state, MakeGarbageCollected<DOMException>( DOMExceptionCode::kSecurityError, "Must be handling a user gesture to show a permission request.")); } EnsureServiceConnection(); auto device_options = mojom::blink::WebBluetoothRequestDeviceOptions::New(); ConvertRequestDeviceOptions(options, device_options, exception_state); if (exception_state.HadException()) return ScriptPromise(); Platform::Current()->RecordRapporURL("Bluetooth.APIUsage.Origin", doc.Url()); auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state); ScriptPromise promise = resolver->Promise(); service_->RequestDevice( std::move(device_options), WTF::Bind(&Bluetooth::RequestDeviceCallback, WrapPersistent(this), WrapPersistent(resolver))); return promise; }
172,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool BackingStoreGtk::CopyFromBackingStore(const gfx::Rect& rect, skia::PlatformCanvas* output) { base::TimeTicks begin_time = base::TimeTicks::Now(); if (visual_depth_ < 24) { return false; } const int width = std::min(size().width(), rect.width()); const int height = std::min(size().height(), rect.height()); XImage* image; XShmSegmentInfo shminfo; // Used only when shared memory is enabled. if (shared_memory_support_ != ui::SHARED_MEMORY_NONE) { Visual* visual = static_cast<Visual*>(visual_); memset(&shminfo, 0, sizeof(shminfo)); image = XShmCreateImage(display_, visual, 32, ZPixmap, NULL, &shminfo, width, height); if (!image) { return false; } if (image->bytes_per_line == 0 || image->height == 0 || static_cast<size_t>(image->height) > (std::numeric_limits<size_t>::max() / image->bytes_per_line)) { XDestroyImage(image); return false; } shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT|0666); if (shminfo.shmid == -1) { XDestroyImage(image); return false; } void* mapped_memory = shmat(shminfo.shmid, NULL, SHM_RDONLY); shmctl(shminfo.shmid, IPC_RMID, 0); if (mapped_memory == (void*)-1) { XDestroyImage(image); return false; } shminfo.shmaddr = image->data = static_cast<char*>(mapped_memory); if (!XShmAttach(display_, &shminfo) || !XShmGetImage(display_, pixmap_, image, rect.x(), rect.y(), AllPlanes)) { DestroySharedImage(display_, image, &shminfo); return false; } } else { image = XGetImage(display_, pixmap_, rect.x(), rect.y(), width, height, AllPlanes, ZPixmap); } if (!output->initialize(width, height, true) || image->bits_per_pixel != 32) { if (shared_memory_support_ != ui::SHARED_MEMORY_NONE) DestroySharedImage(display_, image, &shminfo); else XDestroyImage(image); return false; } SkBitmap bitmap = skia::GetTopDevice(*output)->accessBitmap(true); SkAutoLockPixels alp(bitmap); for (int y = 0; y < height; y++) { const uint32* src_row = reinterpret_cast<uint32*>( &image->data[image->bytes_per_line * y]); uint32* dest_row = bitmap.getAddr32(0, y); for (int x = 0; x < width; ++x, ++dest_row) { *dest_row = src_row[x] | 0xff000000; } } if (shared_memory_support_ != ui::SHARED_MEMORY_NONE) DestroySharedImage(display_, image, &shminfo); else XDestroyImage(image); HISTOGRAM_TIMES("BackingStore.RetrievalFromX", base::TimeTicks::Now() - begin_time); return true; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool BackingStoreGtk::CopyFromBackingStore(const gfx::Rect& rect, skia::PlatformCanvas* output) { base::TimeTicks begin_time = base::TimeTicks::Now(); if (visual_depth_ < 24) { return false; } const int width = std::min(size().width(), rect.width()); const int height = std::min(size().height(), rect.height()); XImage* image; XShmSegmentInfo shminfo; // Used only when shared memory is enabled. if (shared_memory_support_ != ui::SHARED_MEMORY_NONE) { Visual* visual = static_cast<Visual*>(visual_); memset(&shminfo, 0, sizeof(shminfo)); image = XShmCreateImage(display_, visual, 32, ZPixmap, NULL, &shminfo, width, height); if (!image) { return false; } if (image->bytes_per_line == 0 || image->height == 0 || static_cast<size_t>(image->height) > (std::numeric_limits<size_t>::max() / image->bytes_per_line)) { XDestroyImage(image); return false; } shminfo.shmid = shmget(IPC_PRIVATE, image->bytes_per_line * image->height, IPC_CREAT|0600); if (shminfo.shmid == -1) { XDestroyImage(image); LOG(WARNING) << "Failed to get shared memory segment. " "Performance may be degraded."; return false; } else { VLOG(1) << "Got shared memory segment " << shminfo.shmid; } void* mapped_memory = shmat(shminfo.shmid, NULL, SHM_RDONLY); shmctl(shminfo.shmid, IPC_RMID, 0); if (mapped_memory == (void*)-1) { XDestroyImage(image); return false; } shminfo.shmaddr = image->data = static_cast<char*>(mapped_memory); if (!XShmAttach(display_, &shminfo) || !XShmGetImage(display_, pixmap_, image, rect.x(), rect.y(), AllPlanes)) { DestroySharedImage(display_, image, &shminfo); LOG(WARNING) << "X failed to get shared memory segment. " "Performance may be degraded."; return false; } VLOG(1) << "Using X shared memory segment " << shminfo.shmid; } else { LOG(WARNING) << "Not using X shared memory."; image = XGetImage(display_, pixmap_, rect.x(), rect.y(), width, height, AllPlanes, ZPixmap); } if (!output->initialize(width, height, true) || image->bits_per_pixel != 32) { if (shared_memory_support_ != ui::SHARED_MEMORY_NONE) DestroySharedImage(display_, image, &shminfo); else XDestroyImage(image); return false; } SkBitmap bitmap = skia::GetTopDevice(*output)->accessBitmap(true); SkAutoLockPixels alp(bitmap); for (int y = 0; y < height; y++) { const uint32* src_row = reinterpret_cast<uint32*>( &image->data[image->bytes_per_line * y]); uint32* dest_row = bitmap.getAddr32(0, y); for (int x = 0; x < width; ++x, ++dest_row) { *dest_row = src_row[x] | 0xff000000; } } if (shared_memory_support_ != ui::SHARED_MEMORY_NONE) DestroySharedImage(display_, image, &shminfo); else XDestroyImage(image); HISTOGRAM_TIMES("BackingStore.RetrievalFromX", base::TimeTicks::Now() - begin_time); return true; }
171,592
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::HasBlockEntries( const Segment* pSegment, long long off, //relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); //relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) //error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; //absolute if ((total >= 0) && (pos >= total)) return 0; //we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; //interpreted later to mean "unknown size" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id != 0x0F43B675) //weird: not cluster ID return -1; //generic error pos += len; //consume Cluster ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); if (size == 0) return 0; //cluster does not have entries pos += len; //consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) return 0; //cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; //no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) //error return static_cast<long>(id); if (id == 0x0F43B675) //Cluster ID return 0; //no entries found if (id == 0x0C53BB6B) //Cues ID return 0; //no entries found pos += len; //consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) //error return static_cast<long>(result); if (result > 0) //underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) //error return static_cast<long>(size); pos += len; //consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) //weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; //not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) //BlockGroup ID return 1; //have at least one entry if (id == 0x23) //SimpleBlock ID return 1; //have at least one entry pos += size; //consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::HasBlockEntries( const Segment* pSegment, long long off, // relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); // relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; // absolute if ((total >= 0) && (pos >= total)) return 0; // we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; // interpreted later to mean "unknown size" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id != 0x0F43B675) // weird: not cluster ID return -1; // generic error pos += len; // consume Cluster ID field // read size field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); if (size == 0) return 0; // cluster does not have entries pos += len; // consume size field // pos now points to start of payload const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) // return E_FILE_FORMAT_INVALID; //too conservative return 0; // cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; // no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); // This is the distinguished set of ID's we use to determine // that we have exhausted the sub-element's inside the cluster // whose ID we parsed earlier. if (id == 0x0F43B675) // Cluster ID return 0; // no entries found if (id == 0x0C53BB6B) // Cues ID return 0; // no entries found pos += len; // consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; // read size field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field // pos now points to start of payload if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; // not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) // BlockGroup ID return 1; // have at least one entry if (id == 0x23) // SimpleBlock ID return 1; // have at least one entry pos += size; // consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } }
174,384
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PluginChannel::~PluginChannel() { if (renderer_handle_) base::CloseProcessHandle(renderer_handle_); MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
PluginChannel::~PluginChannel() { MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&PluginReleaseCallback), base::TimeDelta::FromMinutes(kPluginReleaseTimeMinutes)); }
170,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SegmentInfo::~SegmentInfo() { delete[] m_pMuxingAppAsUTF8; m_pMuxingAppAsUTF8 = NULL; delete[] m_pWritingAppAsUTF8; m_pWritingAppAsUTF8 = NULL; delete[] m_pTitleAsUTF8; m_pTitleAsUTF8 = NULL; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
SegmentInfo::~SegmentInfo()
174,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *print_string_ptr( const char *str ) { const char *ptr; char *ptr2, *out; int len = 0; unsigned char token; if ( ! str ) return cJSON_strdup( "" ); ptr = str; while ( ( token = *ptr ) && ++len ) { if ( strchr( "\"\\\b\f\n\r\t", token ) ) ++len; else if ( token < 32 ) len += 5; ++ptr; } if ( ! ( out = (char*) cJSON_malloc( len + 3 ) ) ) return 0; ptr2 = out; ptr = str; *ptr2++ = '\"'; while ( *ptr ) { if ( (unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\' ) *ptr2++ = *ptr++; else { *ptr2++ = '\\'; switch ( token = *ptr++ ) { case '\\': *ptr2++ = '\\'; break; case '\"': *ptr2++ = '\"'; break; case '\b': *ptr2++ = 'b'; break; case '\f': *ptr2++ = 'f'; break; case '\n': *ptr2++ = 'n'; break; case '\r': *ptr2++ = 'r'; break; case '\t': *ptr2++ = 't'; break; default: /* Escape and print. */ sprintf( ptr2, "u%04x", token ); ptr2 += 5; break; } } } *ptr2++ = '\"'; *ptr2++ = 0; return out; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static char *print_string_ptr( const char *str ) static char *print_string_ptr(const char *str,printbuffer *p) { const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token; if (!str) { if (p) out=ensure(p,3); else out=(char*)cJSON_malloc(3); if (!out) return 0; strcpy(out,"\"\""); return out; } for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0; if (!flag) { len=ptr-str; if (p) out=ensure(p,len+3); else out=(char*)cJSON_malloc(len+3); if (!out) return 0; ptr2=out;*ptr2++='\"'; strcpy(ptr2,str); ptr2[len]='\"'; ptr2[len+1]=0; return out; } ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} if (p) out=ensure(p,len+3); else out=(char*)cJSON_malloc(len+3); if (!out) return 0; ptr2=out;ptr=str; *ptr2++='\"'; while (*ptr) { if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; else { *ptr2++='\\'; switch (token=*ptr++) { case '\\': *ptr2++='\\'; break; case '\"': *ptr2++='\"'; break; case '\b': *ptr2++='b'; break; case '\f': *ptr2++='f'; break; case '\n': *ptr2++='n'; break; case '\r': *ptr2++='r'; break; case '\t': *ptr2++='t'; break; default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ } } } *ptr2++='\"';*ptr2++=0; return out; }
167,310
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode) { struct sk_buff *skb; gfp_t gfp_mask; long timeo; int err; gfp_mask = sk->sk_allocation; if (gfp_mask & __GFP_WAIT) gfp_mask |= __GFP_REPEAT; timeo = sock_sndtimeo(sk, noblock); while (1) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { skb = alloc_skb(header_len, gfp_mask); if (skb) { int npages; int i; /* No pages, we're done... */ if (!data_len) break; npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; skb->truesize += data_len; skb_shinfo(skb)->nr_frags = npages; for (i = 0; i < npages; i++) { struct page *page; page = alloc_pages(sk->sk_allocation, 0); if (!page) { err = -ENOBUFS; skb_shinfo(skb)->nr_frags = i; kfree_skb(skb); goto failure; } __skb_fill_page_desc(skb, i, page, 0, (data_len >= PAGE_SIZE ? PAGE_SIZE : data_len)); data_len -= PAGE_SIZE; } /* Full success... */ break; } err = -ENOBUFS; goto failure; } set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; } Commit Message: net: sock: validate data_len before allocating skb in sock_alloc_send_pskb() We need to validate the number of pages consumed by data_len, otherwise frags array could be overflowed by userspace. So this patch validate data_len and return -EMSGSIZE when data_len may occupies more frags than MAX_SKB_FRAGS. Signed-off-by: Jason Wang <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len, unsigned long data_len, int noblock, int *errcode) { struct sk_buff *skb; gfp_t gfp_mask; long timeo; int err; int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT; err = -EMSGSIZE; if (npages > MAX_SKB_FRAGS) goto failure; gfp_mask = sk->sk_allocation; if (gfp_mask & __GFP_WAIT) gfp_mask |= __GFP_REPEAT; timeo = sock_sndtimeo(sk, noblock); while (1) { err = sock_error(sk); if (err != 0) goto failure; err = -EPIPE; if (sk->sk_shutdown & SEND_SHUTDOWN) goto failure; if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) { skb = alloc_skb(header_len, gfp_mask); if (skb) { int i; /* No pages, we're done... */ if (!data_len) break; skb->truesize += data_len; skb_shinfo(skb)->nr_frags = npages; for (i = 0; i < npages; i++) { struct page *page; page = alloc_pages(sk->sk_allocation, 0); if (!page) { err = -ENOBUFS; skb_shinfo(skb)->nr_frags = i; kfree_skb(skb); goto failure; } __skb_fill_page_desc(skb, i, page, 0, (data_len >= PAGE_SIZE ? PAGE_SIZE : data_len)); data_len -= PAGE_SIZE; } /* Full success... */ break; } err = -ENOBUFS; goto failure; } set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); err = -EAGAIN; if (!timeo) goto failure; if (signal_pending(current)) goto interrupted; timeo = sock_wait_for_wmem(sk, timeo); } skb_set_owner_w(skb, sk); return skb; interrupted: err = sock_intr_errno(timeo); failure: *errcode = err; return NULL; }
165,602
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int create_fixed_stream_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { struct audioformat *fp; struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; int stream, err; unsigned *rate_table = NULL; fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL); if (!fp) { usb_audio_err(chip, "cannot memdup\n"); return -ENOMEM; } if (fp->nr_rates > MAX_NR_RATES) { kfree(fp); return -EINVAL; } if (fp->nr_rates > 0) { rate_table = kmemdup(fp->rate_table, sizeof(int) * fp->nr_rates, GFP_KERNEL); if (!rate_table) { kfree(fp); return -ENOMEM; } fp->rate_table = rate_table; } stream = (fp->endpoint & USB_DIR_IN) ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK; err = snd_usb_add_audio_stream(chip, stream, fp); if (err < 0) { kfree(fp); kfree(rate_table); return err; } if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber || fp->altset_idx >= iface->num_altsetting) { kfree(fp); kfree(rate_table); return -EINVAL; } alts = &iface->altsetting[fp->altset_idx]; altsd = get_iface_desc(alts); fp->protocol = altsd->bInterfaceProtocol; if (fp->datainterval == 0) fp->datainterval = snd_usb_parse_datainterval(chip, alts); if (fp->maxpacksize == 0) fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize); usb_set_interface(chip->dev, fp->iface, 0); snd_usb_init_pitch(chip, fp->iface, alts, fp); snd_usb_init_sample_rate(chip, fp->iface, alts, fp, fp->rate_max); return 0; } Commit Message: ALSA: usb-audio: Fix NULL dereference in create_fixed_stream_quirk() create_fixed_stream_quirk() may cause a NULL-pointer dereference by accessing the non-existing endpoint when a USB device with a malformed USB descriptor is used. This patch avoids it simply by adding a sanity check of bNumEndpoints before the accesses. Bugzilla: https://bugzilla.suse.com/show_bug.cgi?id=971125 Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID:
static int create_fixed_stream_quirk(struct snd_usb_audio *chip, struct usb_interface *iface, struct usb_driver *driver, const struct snd_usb_audio_quirk *quirk) { struct audioformat *fp; struct usb_host_interface *alts; struct usb_interface_descriptor *altsd; int stream, err; unsigned *rate_table = NULL; fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL); if (!fp) { usb_audio_err(chip, "cannot memdup\n"); return -ENOMEM; } if (fp->nr_rates > MAX_NR_RATES) { kfree(fp); return -EINVAL; } if (fp->nr_rates > 0) { rate_table = kmemdup(fp->rate_table, sizeof(int) * fp->nr_rates, GFP_KERNEL); if (!rate_table) { kfree(fp); return -ENOMEM; } fp->rate_table = rate_table; } stream = (fp->endpoint & USB_DIR_IN) ? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK; err = snd_usb_add_audio_stream(chip, stream, fp); if (err < 0) { kfree(fp); kfree(rate_table); return err; } if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber || fp->altset_idx >= iface->num_altsetting) { kfree(fp); kfree(rate_table); return -EINVAL; } alts = &iface->altsetting[fp->altset_idx]; altsd = get_iface_desc(alts); if (altsd->bNumEndpoints < 1) { kfree(fp); kfree(rate_table); return -EINVAL; } fp->protocol = altsd->bInterfaceProtocol; if (fp->datainterval == 0) fp->datainterval = snd_usb_parse_datainterval(chip, alts); if (fp->maxpacksize == 0) fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize); usb_set_interface(chip->dev, fp->iface, 0); snd_usb_init_pitch(chip, fp->iface, alts, fp); snd_usb_init_sample_rate(chip, fp->iface, alts, fp, fp->rate_max); return 0; }
167,434
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: store_current_palette(png_store *ps, int *npalette) { /* This is an internal error (the call has been made outside a read * operation.) */ if (ps->current == NULL) store_log(ps, ps->pread, "no current stream for palette", 1); /* The result may be null if there is no palette. */ *npalette = ps->current->npalette; return ps->current->palette; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
store_current_palette(png_store *ps, int *npalette) { /* This is an internal error (the call has been made outside a read * operation.) */ if (ps->current == NULL) { store_log(ps, ps->pread, "no current stream for palette", 1); return NULL; } /* The result may be null if there is no palette. */ *npalette = ps->current->npalette; return ps->current->palette; }
173,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_le_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; } ; } /* header_put_le_short */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_le_short (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = x ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; } /* header_put_le_short */
170,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftRaw::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_decoder.raw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mChannelCount = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftRaw::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_decoder.raw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { const OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } mChannelCount = pcmParams->nChannels; mSampleRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,219
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; int interlaced = dctx->interlaced; int cur_field = dctx->cur_field; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; interlaced = (state&2)>>1; /* byte following the 5-byte header prefix */ cur_field = state&1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; if (cid <= 0) continue; dctx->remaining = avpriv_dnxhd_get_frame_size(cid); if (dctx->remaining <= 0) { dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (dctx->remaining <= 0) return dctx->remaining; } if (buf_size - i >= dctx->remaining && (!dctx->interlaced || dctx->cur_field)) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->interlaced = interlaced; dctx->cur_field = 0; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->interlaced = interlaced; dctx->cur_field = 0; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; dctx->interlaced = interlaced; dctx->cur_field = cur_field; return END_NOT_FOUND; } Commit Message: avcodec/dnxhd_parser: Do not return invalid value from dnxhd_find_frame_end() on error Fixes: Null pointer dereference Fixes: CVE-2017-9608 Found-by: Yihan Lian Signed-off-by: Michael Niedermayer <[email protected]> (cherry picked from commit 611b35627488a8d0763e75c25ee0875c5b7987dd) Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476
static int dnxhd_find_frame_end(DNXHDParserContext *dctx, const uint8_t *buf, int buf_size) { ParseContext *pc = &dctx->pc; uint64_t state = pc->state64; int pic_found = pc->frame_start_found; int i = 0; int interlaced = dctx->interlaced; int cur_field = dctx->cur_field; if (!pic_found) { for (i = 0; i < buf_size; i++) { state = (state << 8) | buf[i]; if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) { i++; pic_found = 1; interlaced = (state&2)>>1; /* byte following the 5-byte header prefix */ cur_field = state&1; dctx->cur_byte = 0; dctx->remaining = 0; break; } } } if (pic_found && !dctx->remaining) { if (!buf_size) /* EOF considered as end of frame */ return 0; for (; i < buf_size; i++) { dctx->cur_byte++; state = (state << 8) | buf[i]; if (dctx->cur_byte == 24) { dctx->h = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 26) { dctx->w = (state >> 32) & 0xFFFF; } else if (dctx->cur_byte == 42) { int cid = (state >> 32) & 0xFFFFFFFF; int remaining; if (cid <= 0) continue; remaining = avpriv_dnxhd_get_frame_size(cid); if (remaining <= 0) { remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h); if (remaining <= 0) continue; } dctx->remaining = remaining; if (buf_size - i >= dctx->remaining && (!dctx->interlaced || dctx->cur_field)) { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->interlaced = interlaced; dctx->cur_field = 0; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } else { dctx->remaining -= buf_size; } } } } else if (pic_found) { if (dctx->remaining > buf_size) { dctx->remaining -= buf_size; } else { int remaining = dctx->remaining; pc->frame_start_found = 0; pc->state64 = -1; dctx->interlaced = interlaced; dctx->cur_field = 0; dctx->cur_byte = 0; dctx->remaining = 0; return remaining; } } pc->frame_start_found = pic_found; pc->state64 = state; dctx->interlaced = interlaced; dctx->cur_field = cur_field; return END_NOT_FOUND; }
168,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) { if (!document_) return; LocalFrame* frame = document_->GetFrame(); if (!frame) return; if (info.IsMainResource()) { DCHECK(frame->Owner()); frame->Owner()->AddResourceTiming(info); frame->DidSendResourceTimingInfoToParent(); return; } DOMWindowPerformance::performance(*document_->domWindow()) ->GenerateAndAddResourceTiming(info); } Commit Message: Do not forward resource timing to parent frame after back-forward navigation LocalFrame has |should_send_resource_timing_info_to_parent_| flag not to send timing info to parent except for the first navigation. This flag is cleared when the first timing is sent to parent, however this does not happen if iframe's first navigation was by back-forward navigation. For such iframes, we shouldn't send timings to parent at all. Bug: 876822 Change-Id: I128b51a82ef278c439548afc8283ae63abdef5c5 Reviewed-on: https://chromium-review.googlesource.com/1186215 Reviewed-by: Kinuko Yasuda <[email protected]> Commit-Queue: Kunihiko Sakamoto <[email protected]> Cr-Commit-Position: refs/heads/master@{#585736} CWE ID: CWE-200
void FrameFetchContext::AddResourceTiming(const ResourceTimingInfo& info) { if (!document_) return; LocalFrame* frame = document_->GetFrame(); if (!frame) return; if (info.IsMainResource()) { DCHECK(frame->Owner()); frame->Owner()->AddResourceTiming(info); frame->SetShouldSendResourceTimingInfoToParent(false); return; } DOMWindowPerformance::performance(*document_->domWindow()) ->GenerateAndAddResourceTiming(info); }
172,656
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: poppler_page_prepare_output_dev (PopplerPage *page, double scale, int rotation, gboolean transparent, OutputDevData *output_dev_data) { CairoOutputDev *output_dev; cairo_surface_t *surface; double width, height; int cairo_width, cairo_height, cairo_rowstride, rotate; unsigned char *cairo_data; rotate = rotation + page->page->getRotate (); if (rotate == 90 || rotate == 270) { height = page->page->getCropWidth (); width = page->page->getCropHeight (); } else { width = page->page->getCropWidth (); height = page->page->getCropHeight (); } cairo_width = (int) ceil(width * scale); cairo_height = (int) ceil(height * scale); output_dev = page->document->output_dev; cairo_rowstride = cairo_width * 4; cairo_data = (guchar *) gmalloc (cairo_height * cairo_rowstride); if (transparent) memset (cairo_data, 0x00, cairo_height * cairo_rowstride); else memset (cairo_data, 0xff, cairo_height * cairo_rowstride); surface = cairo_image_surface_create_for_data(cairo_data, CAIRO_FORMAT_ARGB32, cairo_width, cairo_height, cairo_rowstride); output_dev_data->cairo_data = cairo_data; output_dev_data->surface = surface; output_dev_data->cairo = cairo_create (surface); output_dev->setCairo (output_dev_data->cairo); } Commit Message: CWE ID: CWE-189
poppler_page_prepare_output_dev (PopplerPage *page, double scale, int rotation, gboolean transparent, OutputDevData *output_dev_data) { CairoOutputDev *output_dev; cairo_surface_t *surface; double width, height; int cairo_width, cairo_height, cairo_rowstride, rotate; unsigned char *cairo_data; rotate = rotation + page->page->getRotate (); if (rotate == 90 || rotate == 270) { height = page->page->getCropWidth (); width = page->page->getCropHeight (); } else { width = page->page->getCropWidth (); height = page->page->getCropHeight (); } cairo_width = (int) ceil(width * scale); cairo_height = (int) ceil(height * scale); output_dev = page->document->output_dev; cairo_rowstride = cairo_width * 4; cairo_data = (guchar *) gmallocn (cairo_height, cairo_rowstride); if (transparent) memset (cairo_data, 0x00, cairo_height * cairo_rowstride); else memset (cairo_data, 0xff, cairo_height * cairo_rowstride); surface = cairo_image_surface_create_for_data(cairo_data, CAIRO_FORMAT_ARGB32, cairo_width, cairo_height, cairo_rowstride); output_dev_data->cairo_data = cairo_data; output_dev_data->surface = surface; output_dev_data->cairo = cairo_create (surface); output_dev->setCairo (output_dev_data->cairo); }
164,617
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { asn1_write_enumerated(data, result->resultcode); asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0); asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0); if (result->referral) { asn1_push_tag(data, ASN1_CONTEXT(3)); asn1_write_OctetString(data, result->referral, strlen(result->referral)); asn1_pop_tag(data); } } Commit Message: CWE ID: CWE-399
static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) static bool ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) { if (!asn1_write_enumerated(data, result->resultcode)) return false; if (!asn1_write_OctetString(data, result->dn, (result->dn) ? strlen(result->dn) : 0)) return false; if (!asn1_write_OctetString(data, result->errormessage, (result->errormessage) ? strlen(result->errormessage) : 0)) return false; if (result->referral) { if (!asn1_push_tag(data, ASN1_CONTEXT(3))) return false; if (!asn1_write_OctetString(data, result->referral, strlen(result->referral))) return false; if (!asn1_pop_tag(data)) return false; } return true; }
164,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AXTree::PopulateOrderedSetItems(const AXNode* ordered_set, const AXNode* local_parent, std::vector<const AXNode*>& items, bool node_is_radio_button) const { if (!(ordered_set == local_parent)) { if (local_parent->data().role == ordered_set->data().role) return; } for (int i = 0; i < local_parent->child_count(); ++i) { const AXNode* child = local_parent->GetUnignoredChildAtIndex(i); if (node_is_radio_button && child->data().role == ax::mojom::Role::kRadioButton) items.push_back(child); if (!node_is_radio_button && child->SetRoleMatchesItemRole(ordered_set)) items.push_back(child); if (child->data().role == ax::mojom::Role::kGenericContainer || child->data().role == ax::mojom::Role::kIgnored) { PopulateOrderedSetItems(ordered_set, child, items, node_is_radio_button); } } } Commit Message: Position info (item n of m) incorrect if hidden focusable items in list Bug: 836997 Change-Id: I971fa7076f72d51829b36af8e379260d48ca25ec Reviewed-on: https://chromium-review.googlesource.com/c/1450235 Commit-Queue: Aaron Leventhal <[email protected]> Reviewed-by: Nektarios Paisios <[email protected]> Cr-Commit-Position: refs/heads/master@{#628890} CWE ID: CWE-190
void AXTree::PopulateOrderedSetItems(const AXNode* ordered_set, const AXNode* local_parent, std::vector<const AXNode*>& items, bool node_is_radio_button) const { if (!(ordered_set == local_parent)) { if (local_parent->data().role == ordered_set->data().role) return; } for (int i = 0; i < local_parent->child_count(); ++i) { const AXNode* child = local_parent->GetUnignoredChildAtIndex(i); // Invisible children should not be counted. // However, in the collapsed container case (e.g. a combobox), items can // still be chosen/navigated. However, the options in these collapsed // containers are historically marked invisible. Therefore, in that case, // count the invisible items. Only check 2 levels up, as combobox containers // are never higher. if (child->data().HasState(ax::mojom::State::kInvisible) && !IsCollapsed(local_parent) && !IsCollapsed(local_parent->parent())) { continue; } if (node_is_radio_button && child->data().role == ax::mojom::Role::kRadioButton) items.push_back(child); if (!node_is_radio_button && child->SetRoleMatchesItemRole(ordered_set)) items.push_back(child); if (child->data().role == ax::mojom::Role::kGenericContainer || child->data().role == ax::mojom::Role::kIgnored) { PopulateOrderedSetItems(ordered_set, child, items, node_is_radio_button); } } }
172,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCacheUpdateJob::HandleUrlFetchCompleted(URLFetcher* fetcher, int net_error) { DCHECK(internal_state_ == DOWNLOADING); UpdateURLLoaderRequest* request = fetcher->request(); const GURL& url = request->GetURL(); pending_url_fetches_.erase(url); NotifyAllProgress(url); ++url_fetches_completed_; int response_code = net_error == net::OK ? request->GetResponseCode() : fetcher->redirect_response_code(); AppCacheEntry& entry = url_file_list_.find(url)->second; if (response_code / 100 == 2) { DCHECK(fetcher->response_writer()); entry.set_response_id(fetcher->response_writer()->response_id()); entry.set_response_size(fetcher->response_writer()->amount_written()); if (!inprogress_cache_->AddOrModifyEntry(url, entry)) duplicate_response_ids_.push_back(entry.response_id()); } else { VLOG(1) << "Request error: " << net_error << " response code: " << response_code; if (entry.IsExplicit() || entry.IsFallback() || entry.IsIntercept()) { if (response_code == 304 && fetcher->existing_entry().has_response_id()) { entry.set_response_id(fetcher->existing_entry().response_id()); entry.set_response_size(fetcher->existing_entry().response_size()); inprogress_cache_->AddOrModifyEntry(url, entry); } else { const char kFormatString[] = "Resource fetch failed (%d) %s"; std::string message = FormatUrlErrorMessage( kFormatString, url, fetcher->result(), response_code); ResultType result = fetcher->result(); bool is_cross_origin = url.GetOrigin() != manifest_url_.GetOrigin(); switch (result) { case DISKCACHE_ERROR: HandleCacheFailure( blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR, GURL(), 0, is_cross_origin), result, url); break; case NETWORK_ERROR: HandleCacheFailure( blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR, url, 0, is_cross_origin), result, url); break; default: HandleCacheFailure( blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR, url, response_code, is_cross_origin), result, url); break; } return; } } else if (response_code == 404 || response_code == 410) { } else if (update_type_ == UPGRADE_ATTEMPT && fetcher->existing_entry().has_response_id()) { entry.set_response_id(fetcher->existing_entry().response_id()); entry.set_response_size(fetcher->existing_entry().response_size()); inprogress_cache_->AddOrModifyEntry(url, entry); } } DCHECK(internal_state_ != CACHE_FAILURE); FetchUrls(); MaybeCompleteUpdate(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void AppCacheUpdateJob::HandleUrlFetchCompleted(URLFetcher* fetcher, int net_error) { DCHECK(internal_state_ == DOWNLOADING); UpdateURLLoaderRequest* request = fetcher->request(); const GURL& url = request->GetURL(); pending_url_fetches_.erase(url); NotifyAllProgress(url); ++url_fetches_completed_; int response_code = net_error == net::OK ? request->GetResponseCode() : fetcher->redirect_response_code(); AppCacheEntry& entry = url_file_list_.find(url)->second; if (response_code / 100 == 2) { DCHECK(fetcher->response_writer()); entry.set_response_id(fetcher->response_writer()->response_id()); entry.SetResponseAndPaddingSizes( fetcher->response_writer()->amount_written(), ComputeAppCacheResponsePadding(url, manifest_url_)); if (!inprogress_cache_->AddOrModifyEntry(url, entry)) duplicate_response_ids_.push_back(entry.response_id()); } else { VLOG(1) << "Request error: " << net_error << " response code: " << response_code; if (entry.IsExplicit() || entry.IsFallback() || entry.IsIntercept()) { if (response_code == 304 && fetcher->existing_entry().has_response_id()) { entry.set_response_id(fetcher->existing_entry().response_id()); entry.SetResponseAndPaddingSizes( fetcher->existing_entry().response_size(), fetcher->existing_entry().padding_size()); inprogress_cache_->AddOrModifyEntry(url, entry); } else { const char kFormatString[] = "Resource fetch failed (%d) %s"; std::string message = FormatUrlErrorMessage( kFormatString, url, fetcher->result(), response_code); ResultType result = fetcher->result(); bool is_cross_origin = url.GetOrigin() != manifest_url_.GetOrigin(); switch (result) { case DISKCACHE_ERROR: HandleCacheFailure( blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_UNKNOWN_ERROR, GURL(), 0, is_cross_origin), result, url); break; case NETWORK_ERROR: HandleCacheFailure( blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR, url, 0, is_cross_origin), result, url); break; default: HandleCacheFailure( blink::mojom::AppCacheErrorDetails( message, blink::mojom::AppCacheErrorReason::APPCACHE_RESOURCE_ERROR, url, response_code, is_cross_origin), result, url); break; } return; } } else if (response_code == 404 || response_code == 410) { } else if (update_type_ == UPGRADE_ATTEMPT && fetcher->existing_entry().has_response_id()) { entry.set_response_id(fetcher->existing_entry().response_id()); entry.SetResponseAndPaddingSizes( fetcher->existing_entry().response_size(), fetcher->existing_entry().padding_size()); inprogress_cache_->AddOrModifyEntry(url, entry); } } DCHECK(internal_state_ != CACHE_FAILURE); FetchUrls(); MaybeCompleteUpdate(); }
172,996
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mIsBackup(false), mPortIndex(portIndex) { } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
BufferMeta(const sp<GraphicBuffer> &graphicBuffer, OMX_U32 portIndex) : mGraphicBuffer(graphicBuffer), mCopyFromOmx(false), mCopyToOmx(false), mPortIndex(portIndex), mBackup(NULL) { }
174,126
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int serdes_probe(struct platform_device *pdev) { struct phy_provider *provider; struct serdes_ctrl *ctrl; unsigned int i; int ret; ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL); if (!ctrl) return -ENOMEM; ctrl->dev = &pdev->dev; ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node); if (IS_ERR(ctrl->regs)) return PTR_ERR(ctrl->regs); for (i = 0; i <= SERDES_MAX; i++) { ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]); if (ret) return ret; } dev_set_drvdata(&pdev->dev, ctrl); provider = devm_of_phy_provider_register(ctrl->dev, serdes_simple_xlate); return PTR_ERR_OR_ZERO(provider); } Commit Message: phy: ocelot-serdes: fix out-of-bounds read Currently, there is an out-of-bounds read on array ctrl->phys, once variable i reaches the maximum array size of SERDES_MAX in the for loop. Fix this by changing the condition in the for loop from i <= SERDES_MAX to i < SERDES_MAX. Addresses-Coverity-ID: 1473966 ("Out-of-bounds read") Addresses-Coverity-ID: 1473959 ("Out-of-bounds read") Fixes: 51f6b410fc22 ("phy: add driver for Microsemi Ocelot SerDes muxing") Reviewed-by: Quentin Schulz <[email protected]> Signed-off-by: Gustavo A. R. Silva <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-125
static int serdes_probe(struct platform_device *pdev) { struct phy_provider *provider; struct serdes_ctrl *ctrl; unsigned int i; int ret; ctrl = devm_kzalloc(&pdev->dev, sizeof(*ctrl), GFP_KERNEL); if (!ctrl) return -ENOMEM; ctrl->dev = &pdev->dev; ctrl->regs = syscon_node_to_regmap(pdev->dev.parent->of_node); if (IS_ERR(ctrl->regs)) return PTR_ERR(ctrl->regs); for (i = 0; i < SERDES_MAX; i++) { ret = serdes_phy_create(ctrl, i, &ctrl->phys[i]); if (ret) return ret; } dev_set_drvdata(&pdev->dev, ctrl); provider = devm_of_phy_provider_register(ctrl->dev, serdes_simple_xlate); return PTR_ERR_OR_ZERO(provider); }
169,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; size_t newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; }
168,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required) : field_types_(field_types), upload_required_(upload_required) { DCHECK(upload_required_); } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
AutoFillQueryXmlParser::AutoFillQueryXmlParser( std::vector<AutoFillFieldType>* field_types, UploadRequired* upload_required, std::string* experiment_id) : field_types_(field_types), upload_required_(upload_required), experiment_id_(experiment_id) { DCHECK(upload_required_); DCHECK(experiment_id_); }
170,653
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; uint64_t allocSize = numEntries * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; } Commit Message: Fix several ineffective integer overflow checks Commit edd4a76 (which addressed bugs 15328708, 15342615, 15342751) added several integer overflow checks. Unfortunately, those checks fail to take into account integer promotion rules and are thus themselves subject to an integer overflow. Cast the sizeof() operator to a uint64_t to force promotion while multiplying. Bug: 20139950 (cherry picked from commit e2e812e58e8d2716b00d7d82db99b08d3afb4b32) Change-Id: I080eb3fa147601f18cedab86e0360406c3963d7b CWE ID: CWE-189
status_t SampleTable::setCompositionTimeToSampleParams( off64_t data_offset, size_t data_size) { ALOGI("There are reordered frames present."); if (mCompositionTimeDeltaEntries != NULL || data_size < 8) { return ERROR_MALFORMED; } uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } size_t numEntries = U32_AT(&header[4]); if (data_size != (numEntries + 1) * 8) { return ERROR_MALFORMED; } mNumCompositionTimeDeltaEntries = numEntries; uint64_t allocSize = numEntries * 2 * (uint64_t)sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mCompositionTimeDeltaEntries = new uint32_t[2 * numEntries]; if (mDataSource->readAt( data_offset + 8, mCompositionTimeDeltaEntries, numEntries * 8) < (ssize_t)numEntries * 8) { delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; return ERROR_IO; } for (size_t i = 0; i < 2 * numEntries; ++i) { mCompositionTimeDeltaEntries[i] = ntohl(mCompositionTimeDeltaEntries[i]); } mCompositionDeltaLookup->setEntries( mCompositionTimeDeltaEntries, mNumCompositionTimeDeltaEntries); return OK; }
173,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior, UpdateFromElementBehavior update_behavior, const KURL& url, ReferrerPolicy referrer_policy, UpdateType update_type) { pending_task_.reset(); std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter; load_delay_counter.swap(delay_until_do_update_from_element_); Document& document = element_->GetDocument(); if (!document.IsActive()) return; AtomicString image_source_url = element_->ImageSourceURL(); ImageResourceContent* new_image_content = nullptr; if (!url.IsNull() && !url.IsEmpty()) { ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache); resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform); } if (referrer_policy != kReferrerPolicyDefault) { resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_policy, url, document.OutgoingReferrer())); } if (IsHTMLPictureElement(GetElement()->parentNode()) || !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); bool page_is_being_dismissed = document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; if (page_is_being_dismissed) { resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); resource_request.SetKeepalive(true); resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); } FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); if (update_behavior != kUpdateForcedReload && document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); if (page_is_being_dismissed) new_image_content = nullptr; ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) { DispatchErrorEvent(); } NoImageResourceToLoad(); } ImageResourceContent* old_image_content = image_content_.Get(); if (old_image_content != new_image_content) RejectPendingDecodes(update_type); if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() && element_->GetLayoutObject()->IsImage() && new_image_content == old_image_content) { ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged(); } else { if (pending_load_event_.IsActive()) pending_load_event_.Cancel(); if (pending_error_event_.IsActive() && new_image_content) pending_error_event_.Cancel(); UpdateImageState(new_image_content); UpdateLayoutObject(); if (new_image_content) { new_image_content->AddObserver(this); } if (old_image_content) { old_image_content->RemoveObserver(this); } } if (LayoutImageResource* image_resource = GetLayoutImageResource()) image_resource->ResetAnimation(); } Commit Message: Use correct Request Context when EMBED or OBJECT requests an image When an OBJECT or EMBED element requests an image, it does so using an ImageLoader. To ensure that Content-Security-Policy restrictions are applied correctly in this scenario, we must adjust the request's context to indicate the originating element. Bug: 811691 Change-Id: I0fd8010970a12e68e845a54310695acc0b3f7625 Reviewed-on: https://chromium-review.googlesource.com/924589 Commit-Queue: Eric Lawrence <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#537846} CWE ID: CWE-20
void ImageLoader::DoUpdateFromElement(BypassMainWorldBehavior bypass_behavior, UpdateFromElementBehavior update_behavior, const KURL& url, ReferrerPolicy referrer_policy, UpdateType update_type) { pending_task_.reset(); std::unique_ptr<IncrementLoadEventDelayCount> load_delay_counter; load_delay_counter.swap(delay_until_do_update_from_element_); Document& document = element_->GetDocument(); if (!document.IsActive()) return; AtomicString image_source_url = element_->ImageSourceURL(); ImageResourceContent* new_image_content = nullptr; if (!url.IsNull() && !url.IsEmpty()) { ResourceLoaderOptions resource_loader_options; resource_loader_options.initiator_info.name = GetElement()->localName(); ResourceRequest resource_request(url); if (update_behavior == kUpdateForcedReload) { resource_request.SetCacheMode(mojom::FetchCacheMode::kBypassCache); resource_request.SetPreviewsState(WebURLRequest::kPreviewsNoTransform); } if (referrer_policy != kReferrerPolicyDefault) { resource_request.SetHTTPReferrer(SecurityPolicy::GenerateReferrer( referrer_policy, url, document.OutgoingReferrer())); } // Correct the RequestContext if necessary. if (IsHTMLPictureElement(GetElement()->parentNode()) || !GetElement()->FastGetAttribute(HTMLNames::srcsetAttr).IsNull()) { resource_request.SetRequestContext( WebURLRequest::kRequestContextImageSet); } else if (IsHTMLObjectElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextObject); } else if (IsHTMLEmbedElement(GetElement())) { resource_request.SetRequestContext(WebURLRequest::kRequestContextEmbed); } bool page_is_being_dismissed = document.PageDismissalEventBeingDispatched() != Document::kNoDismissal; if (page_is_being_dismissed) { resource_request.SetHTTPHeaderField(HTTPNames::Cache_Control, "max-age=0"); resource_request.SetKeepalive(true); resource_request.SetRequestContext(WebURLRequest::kRequestContextPing); } FetchParameters params(resource_request, resource_loader_options); ConfigureRequest(params, bypass_behavior, *element_, document.GetClientHintsPreferences()); if (update_behavior != kUpdateForcedReload && document.GetFrame()) document.GetFrame()->MaybeAllowImagePlaceholder(params); new_image_content = ImageResourceContent::Fetch(params, document.Fetcher()); if (page_is_being_dismissed) new_image_content = nullptr; ClearFailedLoadURL(); } else { if (!image_source_url.IsNull()) { DispatchErrorEvent(); } NoImageResourceToLoad(); } ImageResourceContent* old_image_content = image_content_.Get(); if (old_image_content != new_image_content) RejectPendingDecodes(update_type); if (update_behavior == kUpdateSizeChanged && element_->GetLayoutObject() && element_->GetLayoutObject()->IsImage() && new_image_content == old_image_content) { ToLayoutImage(element_->GetLayoutObject())->IntrinsicSizeChanged(); } else { if (pending_load_event_.IsActive()) pending_load_event_.Cancel(); if (pending_error_event_.IsActive() && new_image_content) pending_error_event_.Cancel(); UpdateImageState(new_image_content); UpdateLayoutObject(); if (new_image_content) { new_image_content->AddObserver(this); } if (old_image_content) { old_image_content->RemoveObserver(this); } } if (LayoutImageResource* image_resource = GetLayoutImageResource()) image_resource->ResetAnimation(); }
172,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse( base::span<const uint8_t> buffer) { if (buffer.size() <= kResponseCodeLength || GetResponseCode(buffer) != CtapDeviceResponseCode::kSuccess) return base::nullopt; base::Optional<CBOR> decoded_response = cbor::CBORReader::Read(buffer.subspan(1)); if (!decoded_response || !decoded_response->is_map()) return base::nullopt; const auto& response_map = decoded_response->GetMap(); auto it = response_map.find(CBOR(1)); if (it == response_map.end() || !it->second.is_array() || it->second.GetArray().size() > 2) { return base::nullopt; } base::flat_set<ProtocolVersion> protocol_versions; for (const auto& version : it->second.GetArray()) { if (!version.is_string()) return base::nullopt; auto protocol = ConvertStringToProtocolVersion(version.GetString()); if (protocol == ProtocolVersion::kUnknown) { VLOG(2) << "Unexpected protocol version received."; continue; } if (!protocol_versions.insert(protocol).second) return base::nullopt; } if (protocol_versions.empty()) return base::nullopt; it = response_map.find(CBOR(3)); if (it == response_map.end() || !it->second.is_bytestring() || it->second.GetBytestring().size() != kAaguidLength) { return base::nullopt; } AuthenticatorGetInfoResponse response(std::move(protocol_versions), it->second.GetBytestring()); it = response_map.find(CBOR(2)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<std::string> extensions; for (const auto& extension : it->second.GetArray()) { if (!extension.is_string()) return base::nullopt; extensions.push_back(extension.GetString()); } response.SetExtensions(std::move(extensions)); } AuthenticatorSupportedOptions options; it = response_map.find(CBOR(4)); if (it != response_map.end()) { if (!it->second.is_map()) return base::nullopt; const auto& option_map = it->second.GetMap(); auto option_map_it = option_map.find(CBOR(kPlatformDeviceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetIsPlatformDevice(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kResidentKeyMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetSupportsResidentKey(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserPresenceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetUserPresenceRequired(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserVerificationMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured); } else { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedButNotConfigured); } } option_map_it = option_map.find(CBOR(kClientPinMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedAndPinSet); } else { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedButPinNotSet); } } response.SetOptions(std::move(options)); } it = response_map.find(CBOR(5)); if (it != response_map.end()) { if (!it->second.is_unsigned()) return base::nullopt; response.SetMaxMsgSize(it->second.GetUnsigned()); } it = response_map.find(CBOR(6)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<uint8_t> supported_pin_protocols; for (const auto& protocol : it->second.GetArray()) { if (!protocol.is_unsigned()) return base::nullopt; supported_pin_protocols.push_back(protocol.GetUnsigned()); } response.SetPinProtocols(std::move(supported_pin_protocols)); } return base::Optional<AuthenticatorGetInfoResponse>(std::move(response)); } Commit Message: [base] Make dynamic container to static span conversion explicit This change disallows implicit conversions from dynamic containers to static spans. This conversion can cause CHECK failures, and thus should be done carefully. Requiring explicit construction makes it more obvious when this happens. To aid usability, appropriate base::make_span<size_t> overloads are added. Bug: 877931 Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d Reviewed-on: https://chromium-review.googlesource.com/1189985 Reviewed-by: Ryan Sleevi <[email protected]> Reviewed-by: Balazs Engedy <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Commit-Queue: Jan Wilken Dörrie <[email protected]> Cr-Commit-Position: refs/heads/master@{#586657} CWE ID: CWE-22
base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse( base::span<const uint8_t> buffer) { if (buffer.size() <= kResponseCodeLength || GetResponseCode(buffer) != CtapDeviceResponseCode::kSuccess) return base::nullopt; base::Optional<CBOR> decoded_response = cbor::CBORReader::Read(buffer.subspan(1)); if (!decoded_response || !decoded_response->is_map()) return base::nullopt; const auto& response_map = decoded_response->GetMap(); auto it = response_map.find(CBOR(1)); if (it == response_map.end() || !it->second.is_array() || it->second.GetArray().size() > 2) { return base::nullopt; } base::flat_set<ProtocolVersion> protocol_versions; for (const auto& version : it->second.GetArray()) { if (!version.is_string()) return base::nullopt; auto protocol = ConvertStringToProtocolVersion(version.GetString()); if (protocol == ProtocolVersion::kUnknown) { VLOG(2) << "Unexpected protocol version received."; continue; } if (!protocol_versions.insert(protocol).second) return base::nullopt; } if (protocol_versions.empty()) return base::nullopt; it = response_map.find(CBOR(3)); if (it == response_map.end() || !it->second.is_bytestring() || it->second.GetBytestring().size() != kAaguidLength) { return base::nullopt; } AuthenticatorGetInfoResponse response( std::move(protocol_versions), base::make_span<kAaguidLength>(it->second.GetBytestring())); it = response_map.find(CBOR(2)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<std::string> extensions; for (const auto& extension : it->second.GetArray()) { if (!extension.is_string()) return base::nullopt; extensions.push_back(extension.GetString()); } response.SetExtensions(std::move(extensions)); } AuthenticatorSupportedOptions options; it = response_map.find(CBOR(4)); if (it != response_map.end()) { if (!it->second.is_map()) return base::nullopt; const auto& option_map = it->second.GetMap(); auto option_map_it = option_map.find(CBOR(kPlatformDeviceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetIsPlatformDevice(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kResidentKeyMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetSupportsResidentKey(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserPresenceMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; options.SetUserPresenceRequired(option_map_it->second.GetBool()); } option_map_it = option_map.find(CBOR(kUserVerificationMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedAndConfigured); } else { options.SetUserVerificationAvailability( AuthenticatorSupportedOptions::UserVerificationAvailability:: kSupportedButNotConfigured); } } option_map_it = option_map.find(CBOR(kClientPinMapKey)); if (option_map_it != option_map.end()) { if (!option_map_it->second.is_bool()) return base::nullopt; if (option_map_it->second.GetBool()) { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedAndPinSet); } else { options.SetClientPinAvailability( AuthenticatorSupportedOptions::ClientPinAvailability:: kSupportedButPinNotSet); } } response.SetOptions(std::move(options)); } it = response_map.find(CBOR(5)); if (it != response_map.end()) { if (!it->second.is_unsigned()) return base::nullopt; response.SetMaxMsgSize(it->second.GetUnsigned()); } it = response_map.find(CBOR(6)); if (it != response_map.end()) { if (!it->second.is_array()) return base::nullopt; std::vector<uint8_t> supported_pin_protocols; for (const auto& protocol : it->second.GetArray()) { if (!protocol.is_unsigned()) return base::nullopt; supported_pin_protocols.push_back(protocol.GetUnsigned()); } response.SetPinProtocols(std::move(supported_pin_protocols)); } return base::Optional<AuthenticatorGetInfoResponse>(std::move(response)); }
172,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SetUpCacheMetadata() { metadata_.reset(new GDataCacheMetadataMap( NULL, base::SequencedWorkerPool::SequenceToken())); metadata_->Initialize(cache_paths_); } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void SetUpCacheMetadata() { metadata_.reset(new GDataCacheMetadataMap( NULL, base::SequencedWorkerPool::SequenceToken()));
170,871
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); }
167,043
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int fsmVerify(const char *path, rpmfi fi) { int rc; int saveerrno = errno; struct stat dsb; mode_t mode = rpmfiFMode(fi); rc = fsmStat(path, 1, &dsb); if (rc) return rc; if (S_ISREG(mode)) { /* HP-UX (and other os'es) don't permit unlink on busy files. */ char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL); rc = fsmRename(path, rmpath); /* XXX shouldn't we take unlink return code here? */ if (!rc) (void) fsmUnlink(rmpath); else rc = RPMERR_UNLINK_FAILED; free(rmpath); return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } else if (S_ISDIR(mode)) { if (S_ISDIR(dsb.st_mode)) return 0; if (S_ISLNK(dsb.st_mode)) { rc = fsmStat(path, 0, &dsb); if (rc == RPMERR_ENOENT) rc = 0; if (rc) return rc; errno = saveerrno; if (S_ISDIR(dsb.st_mode)) return 0; } } else if (S_ISLNK(mode)) { if (S_ISLNK(dsb.st_mode)) { char buf[8 * BUFSIZ]; size_t len; rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len); errno = saveerrno; if (rc) return rc; if (rstreq(rpmfiFLink(fi), buf)) return 0; } } else if (S_ISFIFO(mode)) { if (S_ISFIFO(dsb.st_mode)) return 0; } else if (S_ISCHR(mode) || S_ISBLK(mode)) { if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) && (dsb.st_rdev == rpmfiFRdev(fi))) return 0; } else if (S_ISSOCK(mode)) { if (S_ISSOCK(dsb.st_mode)) return 0; } /* XXX shouldn't do this with commit/undo. */ rc = fsmUnlink(path); if (rc == 0) rc = RPMERR_ENOENT; return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } Commit Message: Restrict following symlinks to directories by ownership (CVE-2017-7500) Only follow directory symlinks owned by target directory owner or root. This prevents privilege escalation from user-writable directories via directory symlinks to privileged directories on package upgrade, while still allowing admin to arrange disk usage with symlinks. The rationale is that if you can create symlinks owned by user X you *are* user X (or root), and if you also own directory Y you can do whatever with it already, including change permissions. So when you create a symlink to that directory, the link ownership acts as a simple stamp of authority that you indeed want rpm to treat this symlink as it were the directory that you own. Such a permission can only be given by you or root, which is just the way we want it. Plus it's almost ridiculously simple as far as rules go, compared to trying to calculate something from the source vs destination directory permissions etc. In the normal case, the user arranging diskspace with symlinks is indeed root so nothing changes, the only real change here is to links created by non-privileged users which should be few and far between in practise. Unfortunately our test-suite runs as a regular user via fakechroot and thus the testcase for this fails under the new rules. Adjust the testcase to get the ownership straight and add a second case for the illegal behavior, basically the same as the old one but with different expectations. CWE ID: CWE-59
static int fsmVerify(const char *path, rpmfi fi) static int fsmVerify(const char *path, rpmfi fi, const struct stat *fsb) { int rc; int saveerrno = errno; struct stat dsb; mode_t mode = rpmfiFMode(fi); rc = fsmStat(path, 1, &dsb); if (rc) return rc; if (S_ISREG(mode)) { /* HP-UX (and other os'es) don't permit unlink on busy files. */ char *rmpath = rstrscat(NULL, path, "-RPMDELETE", NULL); rc = fsmRename(path, rmpath); /* XXX shouldn't we take unlink return code here? */ if (!rc) (void) fsmUnlink(rmpath); else rc = RPMERR_UNLINK_FAILED; free(rmpath); return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ } else if (S_ISDIR(mode)) { if (S_ISDIR(dsb.st_mode)) return 0; if (S_ISLNK(dsb.st_mode)) { uid_t luid = dsb.st_uid; rc = fsmStat(path, 0, &dsb); if (rc == RPMERR_ENOENT) rc = 0; if (rc) return rc; errno = saveerrno; /* Only permit directory symlinks by target owner and root */ if (S_ISDIR(dsb.st_mode) && (luid == 0 || luid == fsb->st_uid)) return 0; } } else if (S_ISLNK(mode)) { if (S_ISLNK(dsb.st_mode)) { char buf[8 * BUFSIZ]; size_t len; rc = fsmReadLink(path, buf, 8 * BUFSIZ, &len); errno = saveerrno; if (rc) return rc; if (rstreq(rpmfiFLink(fi), buf)) return 0; } } else if (S_ISFIFO(mode)) { if (S_ISFIFO(dsb.st_mode)) return 0; } else if (S_ISCHR(mode) || S_ISBLK(mode)) { if ((S_ISCHR(dsb.st_mode) || S_ISBLK(dsb.st_mode)) && (dsb.st_rdev == rpmfiFRdev(fi))) return 0; } else if (S_ISSOCK(mode)) { if (S_ISSOCK(dsb.st_mode)) return 0; } /* XXX shouldn't do this with commit/undo. */ rc = fsmUnlink(path); if (rc == 0) rc = RPMERR_ENOENT; return (rc ? rc : RPMERR_ENOENT); /* XXX HACK */ }
170,176
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Reverb_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData){ android::ReverbContext * pContext = (android::ReverbContext *) self; LVREV_ControlParams_st ActiveParams; /* Current control Parameters */ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */ if (pContext == NULL){ ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL"); return -EINVAL; } switch (cmdCode){ case EFFECT_CMD_INIT: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_INIT: ERROR"); return -EINVAL; } *(int *) pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_CONFIG: ERROR"); return -EINVAL; } *(int *) pReplyData = android::Reverb_setConfig(pContext, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_CONFIG: ERROR"); return -EINVAL; } android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: Reverb_setConfig(pContext, &pContext->config); break; case EFFECT_CMD_GET_PARAM:{ effect_param_t *p = (effect_param_t *)pCmdData; if (SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) { android_errorWriteLog(0x534e4554, "26347509"); return -EINVAL; } if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) || cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL || replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::Reverb_getParameter(pContext, (void *)p->data, &p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } break; case EFFECT_CMD_SET_PARAM:{ if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::Reverb_setParameter(pContext, (void *)p->data, p->data + p->psize); } break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_TRUE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR-Effect is already enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_TRUE; /* Get the current settings */ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE") pContext->SamplesToExitCount = (ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000; pContext->volumeMode = android::REVERB_VOLUME_FLAT; break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_FALSE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_FALSE; break; case EFFECT_CMD_SET_VOLUME: if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_VOLUME: ERROR"); return -EINVAL; } if (pReplyData != NULL) { // we have volume control pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12); pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12); *(uint32_t *)pReplyData = (1 << 24); *((uint32_t *)pReplyData + 1) = (1 << 24); if (pContext->volumeMode == android::REVERB_VOLUME_OFF) { pContext->volumeMode = android::REVERB_VOLUME_FLAT; } } else { // we don't have volume control pContext->leftVolume = REVERB_UNIT_VOLUME; pContext->rightVolume = REVERB_UNIT_VOLUME; pContext->volumeMode = android::REVERB_VOLUME_OFF; } ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d", pContext->leftVolume, pContext->rightVolume, pContext->volumeMode); break; case EFFECT_CMD_SET_DEVICE: case EFFECT_CMD_SET_AUDIO_MODE: break; default: ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "DEFAULT start %d ERROR",cmdCode); return -EINVAL; } return 0; } /* end Reverb_command */ Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking to Downmix and Reverb Bug: 63662938 Bug: 63526567 Test: Added CTS tests Change-Id: I8ed398cd62a9f461b0590e37f593daa3d8e4dbc4 (cherry picked from commit 804632afcdda6e80945bf27c384757bda50560cb) CWE ID: CWE-200
int Reverb_command(effect_handle_t self, uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData){ android::ReverbContext * pContext = (android::ReverbContext *) self; LVREV_ControlParams_st ActiveParams; /* Current control Parameters */ LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */ if (pContext == NULL){ ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL"); return -EINVAL; } switch (cmdCode){ case EFFECT_CMD_INIT: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_INIT: ERROR"); return -EINVAL; } *(int *) pReplyData = 0; break; case EFFECT_CMD_SET_CONFIG: if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_CONFIG: ERROR"); return -EINVAL; } *(int *) pReplyData = android::Reverb_setConfig(pContext, (effect_config_t *) pCmdData); break; case EFFECT_CMD_GET_CONFIG: if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_CONFIG: ERROR"); return -EINVAL; } android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData); break; case EFFECT_CMD_RESET: Reverb_setConfig(pContext, &pContext->config); break; case EFFECT_CMD_GET_PARAM:{ effect_param_t *p = (effect_param_t *)pCmdData; if (SIZE_MAX - sizeof(effect_param_t) < (size_t)p->psize) { android_errorWriteLog(0x534e4554, "26347509"); return -EINVAL; } if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) || cmdSize < (sizeof(effect_param_t) + p->psize) || pReplyData == NULL || replySize == NULL || *replySize < (sizeof(effect_param_t) + p->psize)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_GET_PARAM: ERROR"); return -EINVAL; } memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize); p = (effect_param_t *)pReplyData; int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t); p->status = android::Reverb_getParameter(pContext, (void *)p->data, &p->vsize, p->data + voffset); *replySize = sizeof(effect_param_t) + voffset + p->vsize; } break; case EFFECT_CMD_SET_PARAM:{ if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) || pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR"); return -EINVAL; } effect_param_t *p = (effect_param_t *) pCmdData; if (p->psize != sizeof(int32_t)){ ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)"); return -EINVAL; } *(int *)pReplyData = android::Reverb_setParameter(pContext, (void *)p->data, p->data + p->psize, p->vsize); } break; case EFFECT_CMD_ENABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_TRUE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_ENABLE: ERROR-Effect is already enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_TRUE; /* Get the current settings */ LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams); LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE") pContext->SamplesToExitCount = (ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000; pContext->volumeMode = android::REVERB_VOLUME_FLAT; break; case EFFECT_CMD_DISABLE: if (pReplyData == NULL || *replySize != sizeof(int)){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR"); return -EINVAL; } if(pContext->bEnabled == LVM_FALSE){ ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled"); return -EINVAL; } *(int *)pReplyData = 0; pContext->bEnabled = LVM_FALSE; break; case EFFECT_CMD_SET_VOLUME: if (pCmdData == NULL || cmdSize != 2 * sizeof(uint32_t)) { ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "EFFECT_CMD_SET_VOLUME: ERROR"); return -EINVAL; } if (pReplyData != NULL) { // we have volume control pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12); pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12); *(uint32_t *)pReplyData = (1 << 24); *((uint32_t *)pReplyData + 1) = (1 << 24); if (pContext->volumeMode == android::REVERB_VOLUME_OFF) { pContext->volumeMode = android::REVERB_VOLUME_FLAT; } } else { // we don't have volume control pContext->leftVolume = REVERB_UNIT_VOLUME; pContext->rightVolume = REVERB_UNIT_VOLUME; pContext->volumeMode = android::REVERB_VOLUME_OFF; } ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d", pContext->leftVolume, pContext->rightVolume, pContext->volumeMode); break; case EFFECT_CMD_SET_DEVICE: case EFFECT_CMD_SET_AUDIO_MODE: break; default: ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: " "DEFAULT start %d ERROR",cmdCode); return -EINVAL; } return 0; } /* end Reverb_command */
173,979
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DocumentInit& DocumentInit::WithPreviousDocumentCSP( const ContentSecurityPolicy* previous_csp) { DCHECK(!previous_csp_); previous_csp_ = previous_csp; return *this; } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
DocumentInit& DocumentInit::WithPreviousDocumentCSP(
173,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: VideoTrack::VideoTrack( Segment* pSegment, long long element_start, long long element_size) : Track(pSegment, element_start, element_size) { } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
VideoTrack::VideoTrack(
174,453
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; const int nonblock = flags & MSG_DONTWAIT; struct sk_buff *skb = NULL; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned long cpu_flags; size_t copied = 0; u32 peek_seq = 0; u32 *seq; unsigned long used; int target; /* Read at least this many bytes */ long timeo; lock_sock(sk); copied = -ENOTCONN; if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) goto out; timeo = sock_rcvtimeo(sk, nonblock); seq = &llc->copied_seq; if (flags & MSG_PEEK) { peek_seq = llc->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); copied = 0; do { u32 offset; /* * We need to check signals first, to get correct SIGURG * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { if (copied) break; copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } /* Next get a buffer. */ skb = skb_peek(&sk->sk_receive_queue); if (skb) { offset = *seq; goto found_ok_skb; } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || (flags & MSG_PEEK)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* * This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo); if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = llc->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; if (!(flags & MSG_TRUNC)) { int rc = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, used); if (rc) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; /* For non stream protcols we get one packet per recvmsg call */ if (sk->sk_type != SOCK_STREAM) goto copy_uaddr; if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } /* Partial read */ if (used + offset < skb->len) continue; } while (len > 0); out: release_sock(sk); return copied; copy_uaddr: if (uaddr != NULL && skb != NULL) { memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); msg->msg_namelen = sizeof(*uaddr); } if (llc_sk(sk)->cmsg_flags) llc_cmsg_rcv(msg, skb); if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } goto out; } Commit Message: llc: Fix missing msg_namelen update in llc_ui_recvmsg() For stream sockets the code misses to update the msg_namelen member to 0 and therefore makes net/socket.c leak the local, uninitialized sockaddr_storage variable to userland -- 128 bytes of kernel stack memory. The msg_namelen update is also missing for datagram sockets in case the socket is shutting down during receive. Fix both issues by setting msg_namelen to 0 early. It will be updated later if we're going to fill the msg_name member. Cc: Arnaldo Carvalho de Melo <[email protected]> Signed-off-by: Mathias Krause <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; const int nonblock = flags & MSG_DONTWAIT; struct sk_buff *skb = NULL; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned long cpu_flags; size_t copied = 0; u32 peek_seq = 0; u32 *seq; unsigned long used; int target; /* Read at least this many bytes */ long timeo; msg->msg_namelen = 0; lock_sock(sk); copied = -ENOTCONN; if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) goto out; timeo = sock_rcvtimeo(sk, nonblock); seq = &llc->copied_seq; if (flags & MSG_PEEK) { peek_seq = llc->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); copied = 0; do { u32 offset; /* * We need to check signals first, to get correct SIGURG * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { if (copied) break; copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } /* Next get a buffer. */ skb = skb_peek(&sk->sk_receive_queue); if (skb) { offset = *seq; goto found_ok_skb; } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || (flags & MSG_PEEK)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* * This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo); if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = llc->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; if (!(flags & MSG_TRUNC)) { int rc = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, used); if (rc) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; /* For non stream protcols we get one packet per recvmsg call */ if (sk->sk_type != SOCK_STREAM) goto copy_uaddr; if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } /* Partial read */ if (used + offset < skb->len) continue; } while (len > 0); out: release_sock(sk); return copied; copy_uaddr: if (uaddr != NULL && skb != NULL) { memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); msg->msg_namelen = sizeof(*uaddr); } if (llc_sk(sk)->cmsg_flags) llc_cmsg_rcv(msg, skb); if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } goto out; }
166,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread, base::Unretained(GetCacheStorageObserver()), url::Origin::Create(origin_url))); return Response::OK(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
Response StorageHandler::TrackCacheStorageForOrigin(const std::string& origin) { if (!storage_partition_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&CacheStorageObserver::TrackOriginOnIOThread, base::Unretained(GetCacheStorageObserver()), url::Origin::Create(origin_url))); return Response::OK(); }
172,776
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SchedulerObject::release(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Release: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!releaseJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction false, // Do not email the user about this action false // Do not email admin about this action )) { text = "Failed to release job"; return false; } return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::release(std::string key, std::string &reason, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Release: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } if (!releaseJob(id.cluster, id.proc, reason.c_str(), true, // Always perform this action within a transaction false, // Do not email the user about this action false // Do not email admin about this action )) { text = "Failed to release job"; return false; } return true; }
164,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2) { register const struct ip6_frag *dp; register const struct ip6_hdr *ip6; dp = (const struct ip6_frag *)bp; ip6 = (const struct ip6_hdr *)bp2; ND_TCHECK(dp->ip6f_offlg); if (ndo->ndo_vflag) { ND_PRINT((ndo, "frag (0x%08x:%d|%ld)", EXTRACT_32BITS(&dp->ip6f_ident), EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK, sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) - (long)(bp - bp2) - sizeof(struct ip6_frag))); } else { ND_PRINT((ndo, "frag (%d|%ld)", EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK, sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) - (long)(bp - bp2) - sizeof(struct ip6_frag))); } /* it is meaningless to decode non-first fragment */ if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0) return -1; else { ND_PRINT((ndo, " ")); return sizeof(struct ip6_frag); } trunc: ND_PRINT((ndo, "[|frag]")); return -1; } Commit Message: CVE-2017-13031/Check for the presence of the entire IPv6 fragment header. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. Clean up some whitespace in tests/TESTLIST while we're at it. CWE ID: CWE-125
frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2) { register const struct ip6_frag *dp; register const struct ip6_hdr *ip6; dp = (const struct ip6_frag *)bp; ip6 = (const struct ip6_hdr *)bp2; ND_TCHECK(*dp); if (ndo->ndo_vflag) { ND_PRINT((ndo, "frag (0x%08x:%d|%ld)", EXTRACT_32BITS(&dp->ip6f_ident), EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK, sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) - (long)(bp - bp2) - sizeof(struct ip6_frag))); } else { ND_PRINT((ndo, "frag (%d|%ld)", EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK, sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) - (long)(bp - bp2) - sizeof(struct ip6_frag))); } /* it is meaningless to decode non-first fragment */ if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0) return -1; else { ND_PRINT((ndo, " ")); return sizeof(struct ip6_frag); } trunc: ND_PRINT((ndo, "[|frag]")); return -1; }
167,852
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if (0 == u2_width || 0 == u2_height) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_FRM_HDR_DECODE_ERR; return e_error; } if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; if (0 == ps_dec->u4_frm_buf_stride) { ps_dec->u4_frm_buf_stride = (UWORD32) (u2_width); } } else { if (0 == ps_dec->i4_pic_count) { /* Decoder has not decoded a single frame since the last * reset/init. This implies that we have two headers in the * input stream. So, do not indicate a resolution change, since * this can take the decoder into an infinite loop. */ return (IMPEG2D_ERROR_CODES_T) IMPEG2D_FRM_HDR_DECODE_ERR; } else if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = ps_dec->u2_vertical_size; ps_dec->u2_reinit_max_width = ps_dec->u2_horizontal_size; return e_error; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Adding check for min_width and min_height Add check for min_wd and min_ht. Stride is updated if header decode is done. Bug: 74078669 Change-Id: Ided95395e1138335dbb4b05131a8551f6f7bbfcd (cherry picked from commit 84eba4863dd50083951db83ea3cc81e015bf51da) CWE ID: CWE-787
IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; UWORD16 u2_height; UWORD16 u2_width; if (impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != SEQUENCE_HEADER_CODE) { impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; } impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); u2_width = impeg2d_bit_stream_get(ps_stream,12); u2_height = impeg2d_bit_stream_get(ps_stream,12); if (0 == u2_width || 0 == u2_height) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_FRM_HDR_DECODE_ERR; return e_error; } if ((u2_width != ps_dec->u2_horizontal_size) || (u2_height != ps_dec->u2_vertical_size)) { if (0 == ps_dec->u2_header_done) { /* This is the first time we are reading the resolution */ ps_dec->u2_horizontal_size = u2_width; ps_dec->u2_vertical_size = u2_height; } else { if (0 == ps_dec->i4_pic_count) { /* Decoder has not decoded a single frame since the last * reset/init. This implies that we have two headers in the * input stream. So, do not indicate a resolution change, since * this can take the decoder into an infinite loop. */ return (IMPEG2D_ERROR_CODES_T) IMPEG2D_FRM_HDR_DECODE_ERR; } else if((u2_width > ps_dec->u2_create_max_width) || (u2_height > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = u2_height; ps_dec->u2_reinit_max_width = u2_width; return e_error; } else if((ps_dec->u2_horizontal_size < MIN_WIDTH) || (ps_dec->u2_vertical_size < MIN_HEIGHT)) { return IMPEG2D_UNSUPPORTED_DIMENSIONS; } else { /* The resolution has changed */ return (IMPEG2D_ERROR_CODES_T)IVD_RES_CHANGED; } } } if((ps_dec->u2_horizontal_size > ps_dec->u2_create_max_width) || (ps_dec->u2_vertical_size > ps_dec->u2_create_max_height)) { IMPEG2D_ERROR_CODES_T e_error = IMPEG2D_UNSUPPORTED_DIMENSIONS; ps_dec->u2_reinit_max_height = ps_dec->u2_vertical_size; ps_dec->u2_reinit_max_width = ps_dec->u2_horizontal_size; return e_error; } if((ps_dec->u2_horizontal_size < MIN_WIDTH) || (ps_dec->u2_vertical_size < MIN_HEIGHT)) { return IMPEG2D_UNSUPPORTED_DIMENSIONS; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* aspect_ratio_info (4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_aspect_ratio_info = impeg2d_bit_stream_get(ps_stream,4); /*------------------------------------------------------------------------*/ /* Frame rate code(4 bits) */ /*------------------------------------------------------------------------*/ ps_dec->u2_frame_rate_code = impeg2d_bit_stream_get(ps_stream,4); if (ps_dec->u2_frame_rate_code > MPEG2_MAX_FRAME_RATE_CODE) { return IMPEG2D_FRM_HDR_DECODE_ERR; } /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* bit_rate_value (18 bits) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,18); GET_MARKER_BIT(ps_dec,ps_stream); /*------------------------------------------------------------------------*/ /* Flush the following as they are not being used */ /* vbv_buffer_size_value(10 bits), constrained_parameter_flag (1 bit) */ /*------------------------------------------------------------------------*/ impeg2d_bit_stream_flush(ps_stream,11); /*------------------------------------------------------------------------*/ /* Quantization matrix for the intra blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_intra_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_intra_quant_matrix,gau1_impeg2_intra_quant_matrix_default, NUM_PELS_IN_BLOCK); } /*------------------------------------------------------------------------*/ /* Quantization matrix for the inter blocks */ /*------------------------------------------------------------------------*/ if(impeg2d_bit_stream_get_bit(ps_stream) == 1) { UWORD16 i; for(i = 0; i < NUM_PELS_IN_BLOCK; i++) { ps_dec->au1_inter_quant_matrix[gau1_impeg2_inv_scan_zig_zag[i]] = (UWORD8)impeg2d_bit_stream_get(ps_stream,8); } } else { memcpy(ps_dec->au1_inter_quant_matrix,gau1_impeg2_inter_quant_matrix_default, NUM_PELS_IN_BLOCK); } impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }
174,085
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next) { File* file = V8File::toNative(value.As<v8::Object>()); if (!file) return 0; if (file->hasBeenClosed()) return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.add(file->uuid(), file->blobDataHandle()); if (appendFileInfo(file, &blobIndex)) { ASSERT(blobIndex >= 0); m_writer.writeFileIndex(blobIndex); } else { m_writer.writeFile(*file); } return 0; } Commit Message: Replace further questionable HashMap::add usages in bindings BUG=390928 [email protected] Review URL: https://codereview.chromium.org/411273002 git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
StateBase* writeFile(v8::Handle<v8::Value> value, StateBase* next) { File* file = V8File::toNative(value.As<v8::Object>()); if (!file) return 0; if (file->hasBeenClosed()) return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.set(file->uuid(), file->blobDataHandle()); if (appendFileInfo(file, &blobIndex)) { ASSERT(blobIndex >= 0); m_writer.writeFileIndex(blobIndex); } else { m_writer.writeFile(*file); } return 0; }
171,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GfxImageColorMap::getGrayLine(Guchar *in, Guchar *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmalloc (length * nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getGrayLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getGrayLine(in, out, length); break; } } Commit Message: CWE ID: CWE-189
void GfxImageColorMap::getGrayLine(Guchar *in, Guchar *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmallocn (length, nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getGrayLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getGrayLine(in, out, length); break; } }
164,609
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( Reference ref) { PersistentHistogramData* data = memory_allocator_->GetAsObject<PersistentHistogramData>(ref); const size_t length = memory_allocator_->GetAllocSize(ref); if (!data || data->name[0] == '\0' || reinterpret_cast<char*>(data)[length - 1] != '\0' || data->samples_metadata.id == 0 || data->logged_metadata.id == 0 || (data->logged_metadata.id != data->samples_metadata.id && data->logged_metadata.id != data->samples_metadata.id + 1) || HashMetricName(data->name) != data->samples_metadata.id) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA); NOTREACHED(); return nullptr; } return CreateHistogram(data); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
std::unique_ptr<HistogramBase> PersistentHistogramAllocator::GetHistogram( Reference ref) { PersistentHistogramData* data = memory_allocator_->GetAsObject<PersistentHistogramData>(ref); const size_t length = memory_allocator_->GetAllocSize(ref); if (!data || data->name[0] == '\0' || reinterpret_cast<char*>(data)[length - 1] != '\0' || data->samples_metadata.id == 0 || data->logged_metadata.id == 0 || (data->logged_metadata.id != data->samples_metadata.id && data->logged_metadata.id != data->samples_metadata.id + 1) || HashMetricName(data->name) != data->samples_metadata.id) { NOTREACHED(); return nullptr; } return CreateHistogram(data); }
172,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) return -ENOKEY; p = key->payload.data[0]; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kzfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kzfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kzfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kzfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kzfree(datablob); kzfree(new_o); return ret; } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
static int trusted_update(struct key *key, struct key_preparsed_payload *prep) { struct trusted_key_payload *p; struct trusted_key_payload *new_p; struct trusted_key_options *new_o; size_t datalen = prep->datalen; char *datablob; int ret = 0; if (key_is_negative(key)) return -ENOKEY; p = key->payload.data[0]; if (!p->migratable) return -EPERM; if (datalen <= 0 || datalen > 32767 || !prep->data) return -EINVAL; datablob = kmalloc(datalen + 1, GFP_KERNEL); if (!datablob) return -ENOMEM; new_o = trusted_options_alloc(); if (!new_o) { ret = -ENOMEM; goto out; } new_p = trusted_payload_alloc(key); if (!new_p) { ret = -ENOMEM; goto out; } memcpy(datablob, prep->data, datalen); datablob[datalen] = '\0'; ret = datablob_parse(datablob, new_p, new_o); if (ret != Opt_update) { ret = -EINVAL; kzfree(new_p); goto out; } if (!new_o->keyhandle) { ret = -EINVAL; kzfree(new_p); goto out; } /* copy old key values, and reseal with new pcrs */ new_p->migratable = p->migratable; new_p->key_len = p->key_len; memcpy(new_p->key, p->key, p->key_len); dump_payload(p); dump_payload(new_p); ret = key_seal(new_p, new_o); if (ret < 0) { pr_info("trusted_key: key_seal failed (%d)\n", ret); kzfree(new_p); goto out; } if (new_o->pcrlock) { ret = pcrlock(new_o->pcrlock); if (ret < 0) { pr_info("trusted_key: pcrlock failed (%d)\n", ret); kzfree(new_p); goto out; } } rcu_assign_keypointer(key, new_p); call_rcu(&p->rcu, trusted_rcu_free); out: kzfree(datablob); kzfree(new_o); return ret; }
167,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem")) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } } } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); } Commit Message: Inherit CSP when self-navigating to local-scheme URL As the linked bug example shows, we should inherit CSP when we navigate to a local-scheme URL (even if we are in a main browsing context). Bug: 799747 Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02 Reviewed-on: https://chromium-review.googlesource.com/c/1234337 Reviewed-by: Mike West <[email protected]> Commit-Queue: Andy Paicu <[email protected]> Cr-Commit-Position: refs/heads/master@{#597889} CWE ID:
void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit, const ContentSecurityPolicy* previous_document_csp) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else { if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); } } // If we don't have an opener or parent, inherit from the previous // document CSP. if (!policy_to_inherit) policy_to_inherit = previous_document_csp; // We should inherit the relevant CSP if the document is loaded using // a local-scheme url. if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); }
172,615
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CronTab::initRegexObject() { if ( ! CronTab::regex.isInitialized() ) { const char *errptr; int erroffset; MyString pattern( CRONTAB_PARAMETER_PATTERN ) ; if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) { MyString error = "CronTab: Failed to compile Regex - "; error += pattern; EXCEPT( const_cast<char*>(error.Value())); } } } Commit Message: CWE ID: CWE-134
CronTab::initRegexObject() { if ( ! CronTab::regex.isInitialized() ) { const char *errptr; int erroffset; MyString pattern( CRONTAB_PARAMETER_PATTERN ) ; if ( ! CronTab::regex.compile( pattern, &errptr, &erroffset )) { MyString error = "CronTab: Failed to compile Regex - "; error += pattern; EXCEPT( "%s", const_cast<char*>(error.Value()) ); } } }
165,383
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mp_dss_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_dss *mdss = (const struct mp_dss *) opt; if ((opt_len != mp_dss_len(mdss, 1) && opt_len != mp_dss_len(mdss, 0)) || flags & TH_SYN) return 0; if (mdss->flags & MP_DSS_F) ND_PRINT((ndo, " fin")); opt += 4; if (mdss->flags & MP_DSS_A) { ND_PRINT((ndo, " ack ")); if (mdss->flags & MP_DSS_a) { ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; } else { ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; } } if (mdss->flags & MP_DSS_M) { ND_PRINT((ndo, " seq ")); if (mdss->flags & MP_DSS_m) { ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; } else { ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; } ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt))); opt += 4; ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt))); opt += 2; if (opt_len == mp_dss_len(mdss, 1)) ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt))); } return 1; } Commit Message: CVE-2017-13040/MPTCP: Clean up printing DSS suboption. Do the length checking inline; that means we print stuff up to the point at which we run out of option data. First check to make sure we have at least 4 bytes of option, so we have flags to check. This fixes a buffer over-read discovered by Kim Gwan Yeong. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
mp_dss_print(netdissect_options *ndo, const u_char *opt, u_int opt_len, u_char flags) { const struct mp_dss *mdss = (const struct mp_dss *) opt; /* We need the flags, at a minimum. */ if (opt_len < 4) return 0; if (flags & TH_SYN) return 0; if (mdss->flags & MP_DSS_F) ND_PRINT((ndo, " fin")); opt += 4; opt_len -= 4; if (mdss->flags & MP_DSS_A) { /* Ack present */ ND_PRINT((ndo, " ack ")); /* * If the a flag is set, we have an 8-byte ack; if it's * clear, we have a 4-byte ack. */ if (mdss->flags & MP_DSS_a) { if (opt_len < 8) return 0; ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; opt_len -= 8; } else { if (opt_len < 4) return 0; ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; } } if (mdss->flags & MP_DSS_M) { /* * Data Sequence Number (DSN), Subflow Sequence Number (SSN), * Data-Level Length present, and Checksum possibly present. */ ND_PRINT((ndo, " seq ")); /* * If the m flag is set, we have an 8-byte NDS; if it's clear, * we have a 4-byte DSN. */ if (mdss->flags & MP_DSS_m) { if (opt_len < 8) return 0; ND_PRINT((ndo, "%" PRIu64, EXTRACT_64BITS(opt))); opt += 8; opt_len -= 8; } else { if (opt_len < 4) return 0; ND_PRINT((ndo, "%u", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; } if (opt_len < 4) return 0; ND_PRINT((ndo, " subseq %u", EXTRACT_32BITS(opt))); opt += 4; opt_len -= 4; if (opt_len < 2) return 0; ND_PRINT((ndo, " len %u", EXTRACT_16BITS(opt))); opt += 2; opt_len -= 2; /* * The Checksum is present only if negotiated. * If there are at least 2 bytes left, process the next 2 * bytes as the Checksum. */ if (opt_len >= 2) { ND_PRINT((ndo, " csum 0x%x", EXTRACT_16BITS(opt))); opt_len -= 2; } } if (opt_len != 0) return 0; return 1; }
167,837
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host, DevToolsAgentHostClient* client) : binding_(this), agent_host_(agent_host), client_(client), process_(nullptr), host_(nullptr), dispatcher_(new protocol::UberDispatcher(this)), weak_factory_(this) { dispatcher_->setFallThroughForNotFound(true); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
DevToolsSession::DevToolsSession(DevToolsAgentHostImpl* agent_host, DevToolsAgentHostClient* client) : binding_(this), agent_host_(agent_host), client_(client), process_host_id_(ChildProcessHost::kInvalidUniqueID), host_(nullptr), dispatcher_(new protocol::UberDispatcher(this)), weak_factory_(this) { dispatcher_->setFallThroughForNotFound(true); }
172,741
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __net_random_once_deferred(struct work_struct *w) { struct __net_random_once_work *work = container_of(w, struct __net_random_once_work, work); if (!static_key_enabled(work->key)) static_key_slow_inc(work->key); kfree(work); } Commit Message: net: avoid dependency of net_get_random_once on nop patching net_get_random_once depends on the static keys infrastructure to patch up the branch to the slow path during boot. This was realized by abusing the static keys api and defining a new initializer to not enable the call site while still indicating that the branch point should get patched up. This was needed to have the fast path considered likely by gcc. The static key initialization during boot up normally walks through all the registered keys and either patches in ideal nops or enables the jump site but omitted that step on x86 if ideal nops where already placed at static_key branch points. Thus net_get_random_once branches not always became active. This patch switches net_get_random_once to the ordinary static_key api and thus places the kernel fast path in the - by gcc considered - unlikely path. Microbenchmarks on Intel and AMD x86-64 showed that the unlikely path actually beats the likely path in terms of cycle cost and that different nop patterns did not make much difference, thus this switch should not be noticeable. Fixes: a48e42920ff38b ("net: introduce new macro net_get_random_once") Reported-by: Tuomas Räsänen <[email protected]> Cc: Linus Torvalds <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static void __net_random_once_deferred(struct work_struct *w) { struct __net_random_once_work *work = container_of(w, struct __net_random_once_work, work); BUG_ON(!static_key_enabled(work->key)); static_key_slow_dec(work->key); kfree(work); }
166,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid()
167,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment) { int i, length; segment->nb_index_entries = avio_rb32(pb); length = avio_rb32(pb); if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) { av_freep(&segment->temporal_offset_entries); av_freep(&segment->flag_entries); return AVERROR(ENOMEM); } for (i = 0; i < segment->nb_index_entries; i++) { segment->temporal_offset_entries[i] = avio_r8(pb); avio_r8(pb); /* KeyFrameOffset */ segment->flag_entries[i] = avio_r8(pb); segment->stream_offset_entries[i] = avio_rb64(pb); avio_skip(pb, length - 11); } return 0; } Commit Message: avformat/mxfdec: Fix DoS issues in mxf_read_index_entry_array() Fixes: 20170829A.mxf Co-Author: 张洪亮(望初)" <[email protected]> Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment) { int i, length; segment->nb_index_entries = avio_rb32(pb); length = avio_rb32(pb); if(segment->nb_index_entries && length < 11) return AVERROR_INVALIDDATA; if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) { av_freep(&segment->temporal_offset_entries); av_freep(&segment->flag_entries); return AVERROR(ENOMEM); } for (i = 0; i < segment->nb_index_entries; i++) { if(avio_feof(pb)) return AVERROR_INVALIDDATA; segment->temporal_offset_entries[i] = avio_r8(pb); avio_r8(pb); /* KeyFrameOffset */ segment->flag_entries[i] = avio_r8(pb); segment->stream_offset_entries[i] = avio_rb64(pb); avio_skip(pb, length - 11); } return 0; }
167,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->GetAppListTargetVisibility()) return AUTO_HIDE_SHOWN; if (shell->system_tray() && shell->system_tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; if (launcher_widget()->IsActive() || status_->IsActive()) return AUTO_HIDE_SHOWN; if (event_filter_.get() && event_filter_->in_mouse_drag()) return AUTO_HIDE_HIDDEN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->GetAppListTargetVisibility()) return AUTO_HIDE_SHOWN; if (shell->system_tray() && shell->system_tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingOverflowBubble()) return AUTO_HIDE_SHOWN; if (launcher_widget()->IsActive() || status_->IsActive()) return AUTO_HIDE_SHOWN; if (event_filter_.get() && event_filter_->in_mouse_drag()) return AUTO_HIDE_HIDDEN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; }
170,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfsd4_layout_verify(struct svc_export *exp, unsigned int layout_type) { if (!exp->ex_layout_types) { dprintk("%s: export does not support pNFS\n", __func__); return NULL; } if (!(exp->ex_layout_types & (1 << layout_type))) { dprintk("%s: layout type %d not supported\n", __func__, layout_type); return NULL; } return nfsd4_layout_ops[layout_type]; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfsd4_layout_verify(struct svc_export *exp, unsigned int layout_type) { if (!exp->ex_layout_types) { dprintk("%s: export does not support pNFS\n", __func__); return NULL; } if (layout_type >= LAYOUT_TYPE_MAX || !(exp->ex_layout_types & (1 << layout_type))) { dprintk("%s: layout type %d not supported\n", __func__, layout_type); return NULL; } return nfsd4_layout_ops[layout_type]; }
168,144
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; bool partition_is_privileged = false; for (size_t i = 0; i < info->webview_privileged_partitions_.size(); ++i) { if (MatchPattern(partition_id, info->webview_privileged_partitions_[i])) { partition_is_privileged = true; break; } } return partition_is_privileged && extension->ResourceMatches( info->webview_accessible_resources_, relative_path); } Commit Message: <webview>: Update format for local file access in manifest.json The new format is: "webview" : { "partitions" : [ { "name" : "foo*", "accessible_resources" : ["a.html", "b.html"] }, { "name" : "bar", "accessible_resources" : ["a.html", "c.html"] } ] } BUG=340291 Review URL: https://codereview.chromium.org/151923005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249640 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool WebviewInfo::IsResourceWebviewAccessible( const Extension* extension, const std::string& partition_id, const std::string& relative_path) { if (!extension) return false; const WebviewInfo* info = GetResourcesInfo(*extension); if (!info) return false; for (size_t i = 0; i < info->partition_items_.size(); ++i) { const PartitionItem* const item = info->partition_items_[i]; if (item->Matches(partition_id) && extension->ResourceMatches(item->accessible_resources(), relative_path)) { return true; } } return false; } void WebviewInfo::AddPartitionItem(scoped_ptr<PartitionItem> item) { partition_items_.push_back(item.release()); }
171,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress_cb_t cb, M_uint32 progress_flags) { char *norm_path; char *join_path; M_fs_dir_entries_t *entries; const M_fs_dir_entry_t *entry; M_fs_info_t *info; M_fs_progress_t *progress = NULL; M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; M_fs_type_t type; /* The result that will be returned by this function. */ M_fs_error_t res; /* The result of the delete itself. */ M_fs_error_t res2; size_t len; size_t i; M_uint64 total_size = 0; M_uint64 total_size_progress = 0; M_uint64 entry_size; /* Normalize the path we are going to delete so we have a valid path to pass around. */ res = M_fs_path_norm(&norm_path, path, M_FS_PATH_NORM_HOME, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We need the info to determine if the path is valid and because we need the type. */ res = M_fs_info(&info, norm_path, M_FS_PATH_INFO_FLAGS_BASIC); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We must know the type because there are different functions for deleting a file and deleting a directory. */ type = M_fs_info_get_type(info); if (type == M_FS_TYPE_UNKNOWN) { M_fs_info_destroy(info); M_free(norm_path); return M_FS_ERROR_GENERIC; } /* Create a list of entries to store all the places we need to delete. */ entries = M_fs_dir_entries_create(); /* Recursive directory deletion isn't intuitive. We have to generate a list of files and delete the list. * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior * is undefined in Posix and HFS is known to skip files if the directory contents is modifies as the * directory is being walked. */ if (type == M_FS_TYPE_DIR && remove_children) { /* We need to read the basic info if the we need to report the size totals to the cb. */ if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; } M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path, NULL, filter)); } /* Add the original path to the list of entries. This may be the only entry in the list. We need to add * it after a potential walk because we can't delete a directory that isn't empty. * Note: * - The info will be owned by the entry and destroyed when it is destroyed. * - The basic info param doesn't get the info in this case. it's set so the info is stored in the entry. */ M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); len = M_fs_dir_entries_len(entries); if (cb) { /* Create the progress. The same progress will be used for the entire operation. It will be updated with * new info as necessary. */ progress = M_fs_progress_create(); /* Get the total size of all files to be deleted if using the progress cb and size totals is set. */ if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size += entry_size; } /* Change the progress total size to reflect all entries. */ M_fs_progress_set_size_total(progress, total_size); } /* Change the progress count to reflect the count. */ if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count_total(progress, len); } } /* Assume success. Set error if there is an error. */ res = M_FS_ERROR_SUCCESS; /* Loop though all entries and delete. */ for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); join_path = M_fs_path_join(norm_path, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); /* Call the appropriate delete function. */ if (M_fs_dir_entry_get_type(entry) == M_FS_TYPE_DIR) { res2 = M_fs_delete_dir(join_path); } else { res2 = M_fs_delete_file(join_path); } /* Set the return result to denote there was an error. The real error will be sent via the * progress callback for the entry. */ if (res2 != M_FS_ERROR_SUCCESS) { res = M_FS_ERROR_GENERIC; } /* Set the progress data for the entry. */ if (cb) { entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size_progress += entry_size; M_fs_progress_set_path(progress, join_path); M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry)); M_fs_progress_set_result(progress, res2); if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, i+1); } if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, total_size_progress); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current(progress, entry_size); M_fs_progress_set_size_current_progress(progress, entry_size); } } M_free(join_path); /* Call the callback and stop processing if requested. */ if (cb && !cb(progress)) { res = M_FS_ERROR_CANCELED; break; } } M_fs_dir_entries_destroy(entries); M_fs_progress_destroy(progress); M_free(norm_path); return res; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress_cb_t cb, M_uint32 progress_flags) { char *norm_path; char *join_path; M_fs_dir_entries_t *entries; const M_fs_dir_entry_t *entry; M_fs_info_t *info; M_fs_progress_t *progress = NULL; M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; M_fs_type_t type; /* The result that will be returned by this function. */ M_fs_error_t res; /* The result of the delete itself. */ M_fs_error_t res2; size_t len; size_t i; M_uint64 total_size = 0; M_uint64 total_size_progress = 0; M_uint64 entry_size; /* Normalize the path we are going to delete so we have a valid path to pass around. */ res = M_fs_path_norm(&norm_path, path, M_FS_PATH_NORM_HOME, M_FS_SYSTEM_AUTO); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We need the info to determine if the path is valid and because we need the type. */ res = M_fs_info(&info, norm_path, M_FS_PATH_INFO_FLAGS_BASIC); if (res != M_FS_ERROR_SUCCESS) { M_free(norm_path); return res; } /* We must know the type because there are different functions for deleting a file and deleting a directory. */ type = M_fs_info_get_type(info); if (type == M_FS_TYPE_UNKNOWN) { M_fs_info_destroy(info); M_free(norm_path); return M_FS_ERROR_GENERIC; } /* Create a list of entries to store all the places we need to delete. */ entries = M_fs_dir_entries_create(); /* Recursive directory deletion isn't intuitive. We have to generate a list of files and delete the list. * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior * is undefined in Posix and HFS is known to skip files if the directory contents is modifies as the * directory is being walked. */ if (type == M_FS_TYPE_DIR && remove_children) { /* We need to read the basic info if the we need to report the size totals to the cb. */ if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; } M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path, NULL, filter)); } /* Add the original path to the list of entries. This may be the only entry in the list. We need to add * it after a potential walk because we can't delete a directory that isn't empty. * Note: * - The info will be owned by the entry and destroyed when it is destroyed. * - The basic info param doesn't get the info in this case. it's set so the info is stored in the entry. */ M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); len = M_fs_dir_entries_len(entries); if (cb) { /* Create the progress. The same progress will be used for the entire operation. It will be updated with * new info as necessary. */ progress = M_fs_progress_create(); /* Get the total size of all files to be deleted if using the progress cb and size totals is set. */ if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size += entry_size; } /* Change the progress total size to reflect all entries. */ M_fs_progress_set_size_total(progress, total_size); } /* Change the progress count to reflect the count. */ if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count_total(progress, len); } } /* Assume success. Set error if there is an error. */ res = M_FS_ERROR_SUCCESS; /* Loop though all entries and delete. */ for (i=0; i<len; i++) { entry = M_fs_dir_entries_at(entries, i); join_path = M_fs_path_join(norm_path, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO); /* Call the appropriate delete function. */ if (M_fs_dir_entry_get_type(entry) == M_FS_TYPE_DIR) { res2 = M_fs_delete_dir(join_path); } else { res2 = M_fs_delete_file(join_path); } /* Set the return result to denote there was an error. The real error will be sent via the * progress callback for the entry. */ if (res2 != M_FS_ERROR_SUCCESS) { res = M_FS_ERROR_GENERIC; } /* Set the progress data for the entry. */ if (cb) { entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry)); total_size_progress += entry_size; M_fs_progress_set_path(progress, join_path); M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry)); M_fs_progress_set_result(progress, res2); if (progress_flags & M_FS_PROGRESS_COUNT) { M_fs_progress_set_count(progress, i+1); } if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { M_fs_progress_set_size_total_progess(progress, total_size_progress); } if (progress_flags & M_FS_PROGRESS_SIZE_CUR) { M_fs_progress_set_size_current(progress, entry_size); M_fs_progress_set_size_current_progress(progress, entry_size); } } M_free(join_path); /* Call the callback and stop processing if requested. */ if (cb && !cb(progress)) { res = M_FS_ERROR_CANCELED; break; } } M_fs_dir_entries_destroy(entries); M_fs_progress_destroy(progress); M_free(norm_path); return res; }
169,143