instruction
stringclasses
1 value
input
stringlengths
90
9.3k
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 gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quantization) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { zend_error(E_ERROR, "Paletter image not supported by webp"); return; } if (quantization == -1) { quantization = 80; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quantization, &out); if (out_size == 0) { zend_error(E_ERROR, "gd-webp encoding failed"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); } Commit Message: Merge branch 'PHP-5.6' into PHP-7.0 CWE ID: CWE-190
void gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quantization) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { zend_error(E_ERROR, "Paletter image not supported by webp"); return; } if (quantization == -1) { quantization = 80; } if (overflow2(gdImageSX(im), 4)) { return; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quantization, &out); if (out_size == 0) { zend_error(E_ERROR, "gd-webp encoding failed"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); }
169,940
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: INST_HANDLER (lds) { // LDS Rd, k int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; __generic_ld_st (op, "ram", 0, 1, 0, k, 0); ESIL_A ("r%d,=,", d); } Commit Message: Fix crash in anal.avr CWE ID: CWE-125
INST_HANDLER (lds) { // LDS Rd, k if (len < 4) { return; } int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4); int k = (buf[3] << 8) | buf[2]; op->ptr = k; __generic_ld_st (op, "ram", 0, 1, 0, k, 0); ESIL_A ("r%d,=,", d); }
169,234
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: ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: ... CWE ID: CWE-20
ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
168,034
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 IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is terminated."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeDestroyIBusConfig(); if (self->connection_change_handler_) { LOG(INFO) << "Notifying Chrome that IBus is terminated."; self->connection_change_handler_(self->language_library_, false); } } 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
static void IBusBusDisconnectedCallback(IBusBus* bus, gpointer user_data) { void IBusBusDisconnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is terminated."; MaybeDestroyIBusConfig(); VLOG(1) << "Notifying Chrome that IBus is terminated."; FOR_EACH_OBSERVER(Observer, observers_, OnConnectionChange(false)); }
170,537
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 gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond) { PurpleXfer *xfer = data; struct im_connection *ic = purple_ic_by_pa(xfer->account); struct prpl_xfer_data *px = xfer->ui_data; PurpleBuddy *buddy; const char *who; buddy = purple_find_buddy(xfer->account, xfer->who); who = buddy ? purple_buddy_get_name(buddy) : xfer->who; /* TODO(wilmer): After spreading some more const goodness in BitlBee, remove the evil cast below. */ px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size); px->ft->data = px; px->ft->accept = prpl_xfer_accept; px->ft->canceled = prpl_xfer_canceled; px->ft->free = prpl_xfer_free; px->ft->write_request = prpl_xfer_write_request; return FALSE; } Commit Message: purple: Fix crash on ft requests from unknown contacts Followup to 701ab81 (included in 3.5) which was a partial fix which only improved things for non-libpurple file transfers (that is, just jabber) CWE ID: CWE-476
static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond) { PurpleXfer *xfer = data; struct im_connection *ic = purple_ic_by_pa(xfer->account); struct prpl_xfer_data *px = xfer->ui_data; PurpleBuddy *buddy; const char *who; buddy = purple_find_buddy(xfer->account, xfer->who); who = buddy ? purple_buddy_get_name(buddy) : xfer->who; /* TODO(wilmer): After spreading some more const goodness in BitlBee, remove the evil cast below. */ px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size); if (!px->ft) { return FALSE; } px->ft->data = px; px->ft->accept = prpl_xfer_accept; px->ft->canceled = prpl_xfer_canceled; px->ft->free = prpl_xfer_free; px->ft->write_request = prpl_xfer_write_request; return FALSE; }
168,380
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: JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA): JBIG2Segment(segNumA) { w = wA; h = hA; line = (wA + 7) >> 3; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmalloc(h * line + 1); data[h * line] = 0; } Commit Message: CWE ID: CWE-189
JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA): JBIG2Segment(segNumA) { w = wA; h = hA; line = (wA + 7) >> 3; if (w <= 0 || h <= 0 || line <= 0 || h >= (INT_MAX - 1) / line) { error(-1, "invalid width/height"); data = NULL; return; } data = (Guchar *)gmallocn(h, line + 1); data[h * line] = 0; }
164,612
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 WebContentsImpl::DetachInterstitialPage() { if (node_.OuterContentsFrameTreeNode()) { if (GetRenderManager()->GetProxyToOuterDelegate()) { DCHECK(static_cast<RenderWidgetHostViewBase*>( GetRenderManager()->current_frame_host()->GetView()) ->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* view = static_cast<RenderWidgetHostViewChildFrame*>( GetRenderManager()->current_frame_host()->GetView()); GetRenderManager()->SetRWHViewForInnerContents(view); } } bool interstitial_pausing_throbber = ShowingInterstitialPage() && GetRenderManager()->interstitial_page()->pause_throbber(); if (ShowingInterstitialPage()) GetRenderManager()->remove_interstitial_page(); for (auto& observer : observers_) observer.DidDetachInterstitialPage(); if (interstitial_pausing_throbber && frame_tree_.IsLoading()) LoadingStateChanged(true, true, nullptr); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void WebContentsImpl::DetachInterstitialPage() { if (node_.OuterContentsFrameTreeNode()) { if (GetRenderManager()->GetProxyToOuterDelegate()) { DCHECK(static_cast<RenderWidgetHostViewBase*>( GetRenderManager()->current_frame_host()->GetView()) ->IsRenderWidgetHostViewChildFrame()); RenderWidgetHostViewChildFrame* view = static_cast<RenderWidgetHostViewChildFrame*>( GetRenderManager()->current_frame_host()->GetView()); GetRenderManager()->SetRWHViewForInnerContents(view); } } bool interstitial_pausing_throbber = ShowingInterstitialPage() && interstitial_page_->pause_throbber(); if (ShowingInterstitialPage()) interstitial_page_ = nullptr; for (auto& observer : observers_) observer.DidDetachInterstitialPage(); if (interstitial_pausing_throbber && frame_tree_.IsLoading()) LoadingStateChanged(true, true, nullptr); }
172,325
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: PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: convert_to_double_ex(zval_affine_elem); affine[i] = Z_DVAL_PP(zval_affine_elem); break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.x = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.y = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.width = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { convert_to_long_ex(tmp); rect.height = Z_LVAL_PP(tmp); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imageaffine) { zval *IM; gdImagePtr src; gdImagePtr dst; gdRect rect; gdRectPtr pRect = NULL; zval *z_rect = NULL; zval *z_affine; zval **tmp; double affine[6]; int i, nelems; zval **zval_affine_elem = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ra|a", &IM, &z_affine, &z_rect) == FAILURE) { return; } ZEND_FETCH_RESOURCE(src, gdImagePtr, &IM, -1, "Image", le_gd); if ((nelems = zend_hash_num_elements(Z_ARRVAL_P(z_affine))) != 6) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Affine array must have six elements"); RETURN_FALSE; } for (i = 0; i < nelems; i++) { if (zend_hash_index_find(Z_ARRVAL_P(z_affine), i, (void **) &zval_affine_elem) == SUCCESS) { switch (Z_TYPE_PP(zval_affine_elem)) { case IS_LONG: affine[i] = Z_LVAL_PP(zval_affine_elem); break; case IS_DOUBLE: affine[i] = Z_DVAL_PP(zval_affine_elem); break; case IS_STRING: { zval dval; dval = **zval_affine_elem; zval_copy_ctor(&dval); convert_to_double(&dval); affine[i] = Z_DVAL(dval); } break; default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid type for element %i", i); RETURN_FALSE; } } } if (z_rect != NULL) { if (zend_hash_find(HASH_OF(z_rect), "x", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.x = Z_LVAL(lval); } else { rect.x = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing x position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "y", sizeof("x"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.y = Z_LVAL(lval); } else { rect.y = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing y position"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "width", sizeof("width"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.width = Z_LVAL(lval); } else { rect.width = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing width"); RETURN_FALSE; } if (zend_hash_find(HASH_OF(z_rect), "height", sizeof("height"), (void **)&tmp) != FAILURE) { if (Z_TYPE_PP(tmp) != IS_LONG) { zval lval; lval = **tmp; zval_copy_ctor(&lval); convert_to_long(&lval); rect.height = Z_LVAL(lval); } else { rect.height = Z_LVAL_PP(tmp); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Missing height"); RETURN_FALSE; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = NULL; } if (gdTransformAffineGetImage(&dst, src, pRect, affine) != GD_TRUE) { RETURN_FALSE; } if (dst == NULL) { RETURN_FALSE; } else { ZEND_REGISTER_RESOURCE(return_value, dst, le_gd); } }
166,428
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 long AudioTrack::GetChannels() const { return m_channels; } 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 long AudioTrack::GetChannels() const Track** i = m_trackEntries; Track** const j = m_trackEntriesEnd; while (i != j) { Track* const pTrack = *i++; if (pTrack == NULL) continue; if (tn == pTrack->GetNumber()) return pTrack; } return NULL; // not found }
174,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: log2vis_encoded_string (PyObject * string, const char *encoding, FriBidiParType base_direction, int clean, int reordernsm) { PyObject *logical = NULL; /* logical unicode object */ PyObject *result = NULL; /* output string object */ /* Always needed for the string length */ logical = PyUnicode_Decode (PyString_AS_STRING (string), PyString_GET_SIZE (string), encoding, "strict"); if (logical == NULL) return NULL; if (strcmp (encoding, "utf-8") == 0) /* Shortcut for utf8 strings (little faster) */ result = log2vis_utf8 (string, PyUnicode_GET_SIZE (logical), base_direction, clean, reordernsm); else { /* Invoke log2vis_unicode and encode back to encoding */ PyObject *visual = log2vis_unicode (logical, base_direction, clean, reordernsm); if (visual) { result = PyUnicode_Encode (PyUnicode_AS_UNICODE (visual), PyUnicode_GET_SIZE (visual), encoding, "strict"); Py_DECREF (visual); } } Py_DECREF (logical); return result; } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119
log2vis_encoded_string (PyObject * string, const char *encoding,
165,640
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: xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI, xsltPreComputeFunction precomp, xsltTransformFunction transform) { int ret; xsltExtElementPtr ext; if ((name == NULL) || (URI == NULL) || (transform == NULL)) return (-1); if (xsltElementsHash == NULL) xsltElementsHash = xmlHashCreate(10); if (xsltElementsHash == NULL) return (-1); xmlMutexLock(xsltExtMutex); ext = xsltNewExtElement(precomp, transform); if (ext == NULL) { ret = -1; goto done; } xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext, (xmlHashDeallocator) xsltFreeExtElement); done: xmlMutexUnlock(xsltExtMutex); return (0); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltRegisterExtModuleElement(const xmlChar * name, const xmlChar * URI, xsltPreComputeFunction precomp, xsltTransformFunction transform) { int ret = 0; xsltExtElementPtr ext; if ((name == NULL) || (URI == NULL) || (transform == NULL)) return (-1); if (xsltElementsHash == NULL) xsltElementsHash = xmlHashCreate(10); if (xsltElementsHash == NULL) return (-1); xmlMutexLock(xsltExtMutex); ext = xsltNewExtElement(precomp, transform); if (ext == NULL) { ret = -1; goto done; } xmlHashUpdateEntry2(xsltElementsHash, name, URI, (void *) ext, (xmlHashDeallocator) xsltFreeExtElement); done: xmlMutexUnlock(xsltExtMutex); return (ret); }
173,300
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: BackendImpl::BackendImpl( const base::FilePath& path, uint32_t mask, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, net::NetLog* net_log) : background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(mask), max_size_(0), up_ticks_(0), cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(kMask), init_(false), restarted_(false), unit_test_(false), read_only_(false), disabled_(false), new_eviction_(false), first_timer_(true), user_load_(false), net_log_(net_log), done_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED), ptr_factory_(this) {} Commit Message: Blockfile cache: fix long-standing sparse + evict reentrancy problem Thanks to nedwilliamson@ (on gmail) for an alternative perspective plus a reduction to make fixing this much easier. Bug: 826626, 518908, 537063, 802886 Change-Id: Ibfa01416f9a8e7f7b361e4f93b4b6b134728b85f Reviewed-on: https://chromium-review.googlesource.com/985052 Reviewed-by: Matt Menke <mmenke@chromium.org> Commit-Queue: Maks Orlovich <morlovich@chromium.org> Cr-Commit-Position: refs/heads/master@{#547103} CWE ID: CWE-20
BackendImpl::BackendImpl( const base::FilePath& path, uint32_t mask, const scoped_refptr<base::SingleThreadTaskRunner>& cache_thread, net::NetLog* net_log) : background_queue_(this, FallbackToInternalIfNull(cache_thread)), path_(path), block_files_(path), mask_(mask), max_size_(0), up_ticks_(0), cache_type_(net::DISK_CACHE), uma_report_(0), user_flags_(kMask), init_(false), restarted_(false), unit_test_(false), read_only_(false), disabled_(false), new_eviction_(false), first_timer_(true), user_load_(false), consider_evicting_at_op_end_(false), net_log_(net_log), done_(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED), ptr_factory_(this) {}
172,697
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 MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615 CWE ID: CWE-119
static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, rows; rows=MagickMax(GetImageListLength(images), (size_t) GetMagickResourceLimit(ThreadResource)); pixels=(MagickPixelPacket **) AcquireQuantumMemory(rows,sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) rows; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); }
169,595
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 ParseCommon(map_string_t *settings, const char *conf_filename) { const char *value; value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir"); if (value) { g_settings_sWatchCrashdumpArchiveDir = xstrdup(value); remove_map_string_item(settings, "WatchCrashdumpArchiveDir"); } value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize"); if (value) { char *end; errno = 0; unsigned long ul = strtoul(value, &end, 10); if (errno || end == value || *end != '\0' || ul > INT_MAX) error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value); else g_settings_nMaxCrashReportsSize = ul; remove_map_string_item(settings, "MaxCrashReportsSize"); } value = get_map_string_item_or_NULL(settings, "DumpLocation"); if (value) { g_settings_dump_location = xstrdup(value); remove_map_string_item(settings, "DumpLocation"); } else g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION); value = get_map_string_item_or_NULL(settings, "DeleteUploaded"); if (value) { g_settings_delete_uploaded = string_to_bool(value); remove_map_string_item(settings, "DeleteUploaded"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled"); if (value) { g_settings_autoreporting = string_to_bool(value); remove_map_string_item(settings, "AutoreportingEnabled"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEvent"); if (value) { g_settings_autoreporting_event = xstrdup(value); remove_map_string_item(settings, "AutoreportingEvent"); } else g_settings_autoreporting_event = xstrdup("report_uReport"); value = get_map_string_item_or_NULL(settings, "ShortenedReporting"); if (value) { g_settings_shortenedreporting = string_to_bool(value); remove_map_string_item(settings, "ShortenedReporting"); } else g_settings_shortenedreporting = 0; GHashTableIter iter; const char *name; /*char *value; - already declared */ init_map_string_iter(&iter, settings); while (next_map_string_iter(&iter, &name, &value)) { error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename); } } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <jfilak@redhat.com> CWE ID: CWE-200
static void ParseCommon(map_string_t *settings, const char *conf_filename) { const char *value; value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir"); if (value) { g_settings_sWatchCrashdumpArchiveDir = xstrdup(value); remove_map_string_item(settings, "WatchCrashdumpArchiveDir"); } value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize"); if (value) { char *end; errno = 0; unsigned long ul = strtoul(value, &end, 10); if (errno || end == value || *end != '\0' || ul > INT_MAX) error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value); else g_settings_nMaxCrashReportsSize = ul; remove_map_string_item(settings, "MaxCrashReportsSize"); } value = get_map_string_item_or_NULL(settings, "DumpLocation"); if (value) { g_settings_dump_location = xstrdup(value); remove_map_string_item(settings, "DumpLocation"); } else g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION); value = get_map_string_item_or_NULL(settings, "DeleteUploaded"); if (value) { g_settings_delete_uploaded = string_to_bool(value); remove_map_string_item(settings, "DeleteUploaded"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled"); if (value) { g_settings_autoreporting = string_to_bool(value); remove_map_string_item(settings, "AutoreportingEnabled"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEvent"); if (value) { g_settings_autoreporting_event = xstrdup(value); remove_map_string_item(settings, "AutoreportingEvent"); } else g_settings_autoreporting_event = xstrdup("report_uReport"); value = get_map_string_item_or_NULL(settings, "ShortenedReporting"); if (value) { g_settings_shortenedreporting = string_to_bool(value); remove_map_string_item(settings, "ShortenedReporting"); } else g_settings_shortenedreporting = 0; value = get_map_string_item_or_NULL(settings, "PrivateReports"); if (value) { g_settings_privatereports = string_to_bool(value); remove_map_string_item(settings, "PrivateReports"); } GHashTableIter iter; const char *name; /*char *value; - already declared */ init_map_string_iter(&iter, settings); while (next_map_string_iter(&iter, &name, &value)) { error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename); } }
170,150
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 store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ int remaining = s->icy_metaint - s->icy_data_read; if (remaining < 0) return AVERROR_INVALIDDATA; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <paulcher@icloud.com>. CWE ID: CWE-119
static int store_icy(URLContext *h, int size) { HTTPContext *s = h->priv_data; /* until next metadata packet */ uint64_t remaining; if (s->icy_metaint < s->icy_data_read) return AVERROR_INVALIDDATA; remaining = s->icy_metaint - s->icy_data_read; if (!remaining) { /* The metadata packet is variable sized. It has a 1 byte header * which sets the length of the packet (divided by 16). If it's 0, * the metadata doesn't change. After the packet, icy_metaint bytes * of normal data follows. */ uint8_t ch; int len = http_read_stream_all(h, &ch, 1); if (len < 0) return len; if (ch > 0) { char data[255 * 16 + 1]; int ret; len = ch * 16; ret = http_read_stream_all(h, data, len); if (ret < 0) return ret; data[len + 1] = 0; if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0) return ret; update_metadata(s, data); } s->icy_data_read = 0; remaining = s->icy_metaint; } return FFMIN(size, remaining); }
168,505
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 cloop_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVCloopState *s = bs->opaque; uint32_t offsets_size, max_compressed_block_size = 1, i; int ret; bs->read_only = 1; /* read header */ ret = bdrv_pread(bs->file, 128, &s->block_size, 4); if (ret < 0) { return ret; } s->block_size = be32_to_cpu(s->block_size); if (s->block_size % 512) { error_setg(errp, "block_size %u must be a multiple of 512", s->block_size); return -EINVAL; } if (s->block_size == 0) { error_setg(errp, "block_size cannot be zero"); return -EINVAL; } /* cloop's create_compressed_fs.c warns about block sizes beyond 256 KB but * we can accept more. Prevent ridiculous values like 4 GB - 1 since we * need a buffer this big. */ if (s->block_size > MAX_BLOCK_SIZE) { error_setg(errp, "block_size %u must be %u MB or less", s->block_size, MAX_BLOCK_SIZE / (1024 * 1024)); return -EINVAL; } ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4); if (ret < 0) { return ret; } s->n_blocks = be32_to_cpu(s->n_blocks); /* read offsets */ offsets_size = s->n_blocks * sizeof(uint64_t); s->offsets = g_malloc(offsets_size); if (i > 0) { uint32_t size = s->offsets[i] - s->offsets[i - 1]; if (size > max_compressed_block_size) { max_compressed_block_size = size; } } } Commit Message: CWE ID: CWE-190
static int cloop_open(BlockDriverState *bs, QDict *options, int flags, Error **errp) { BDRVCloopState *s = bs->opaque; uint32_t offsets_size, max_compressed_block_size = 1, i; int ret; bs->read_only = 1; /* read header */ ret = bdrv_pread(bs->file, 128, &s->block_size, 4); if (ret < 0) { return ret; } s->block_size = be32_to_cpu(s->block_size); if (s->block_size % 512) { error_setg(errp, "block_size %u must be a multiple of 512", s->block_size); return -EINVAL; } if (s->block_size == 0) { error_setg(errp, "block_size cannot be zero"); return -EINVAL; } /* cloop's create_compressed_fs.c warns about block sizes beyond 256 KB but * we can accept more. Prevent ridiculous values like 4 GB - 1 since we * need a buffer this big. */ if (s->block_size > MAX_BLOCK_SIZE) { error_setg(errp, "block_size %u must be %u MB or less", s->block_size, MAX_BLOCK_SIZE / (1024 * 1024)); return -EINVAL; } ret = bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4); if (ret < 0) { return ret; } s->n_blocks = be32_to_cpu(s->n_blocks); /* read offsets */ if (s->n_blocks > UINT32_MAX / sizeof(uint64_t)) { /* Prevent integer overflow */ error_setg(errp, "n_blocks %u must be %zu or less", s->n_blocks, UINT32_MAX / sizeof(uint64_t)); return -EINVAL; } offsets_size = s->n_blocks * sizeof(uint64_t); s->offsets = g_malloc(offsets_size); if (i > 0) { uint32_t size = s->offsets[i] - s->offsets[i - 1]; if (size > max_compressed_block_size) { max_compressed_block_size = size; } } }
165,403
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 IsTraceEventArgsWhitelisted(const char* category_group_name, const char* event_name) { if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "whitelisted")) { return true; } return false; } Commit Message: Tracing: Add support for PII whitelisting of individual trace event arguments R=dsinclair,shatch BUG=546093 Review URL: https://codereview.chromium.org/1415013003 Cr-Commit-Position: refs/heads/master@{#356690} CWE ID: CWE-399
bool IsTraceEventArgsWhitelisted(const char* category_group_name, bool IsTraceEventArgsWhitelisted( const char* category_group_name, const char* event_name, base::trace_event::ArgumentNameFilterPredicate* arg_filter) { if (base::MatchPattern(category_group_name, "benchmark") && base::MatchPattern(event_name, "whitelisted")) { return true; } return false; }
171,681
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: CursorImpl::IDBThreadHelper::~IDBThreadHelper() { cursor_->RemoveCursorFromTransaction(); } Commit Message: [IndexedDB] Fix Cursor UAF If the connection is closed before we return a cursor, it dies in IndexedDBCallbacks::IOThreadHelper::SendSuccessCursor. It's deleted on the correct thread, but we also need to makes sure to remove it from its transaction. To make things simpler, we have the cursor remove itself from its transaction on destruction. R: pwnall@chromium.org Bug: 728887 Change-Id: I8c76e6195c2490137a05213e47c635d12f4d3dd2 Reviewed-on: https://chromium-review.googlesource.com/526284 Commit-Queue: Daniel Murphy <dmurph@chromium.org> Reviewed-by: Victor Costan <pwnall@chromium.org> Cr-Commit-Position: refs/heads/master@{#477504} CWE ID: CWE-416
CursorImpl::IDBThreadHelper::~IDBThreadHelper() {
172,306
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: v8::Local<v8::Object> V8Console::createCommandLineAPI(InspectedContext* inspectedContext) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> commandLineAPI = v8::Object::New(isolate); createBoundFunctionProperty(context, commandLineAPI, "dir", V8Console::dirCallback, "function dir(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "dirxml", V8Console::dirxmlCallback, "function dirxml(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profile", V8Console::profileCallback, "function profile(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profileEnd", V8Console::profileEndCallback, "function profileEnd(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "clear", V8Console::clearCallback, "function clear() { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "table", V8Console::tableCallback, "function table(data, [columns]) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "keys", V8Console::keysCallback, "function keys(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "values", V8Console::valuesCallback, "function values(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "debug", V8Console::debugFunctionCallback, "function debug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "undebug", V8Console::undebugFunctionCallback, "function undebug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "monitor", V8Console::monitorFunctionCallback, "function monitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "unmonitor", V8Console::unmonitorFunctionCallback, "function unmonitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "inspect", V8Console::inspectCallback, "function inspect(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "copy", V8Console::copyCallback, "function copy(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "$_", V8Console::lastEvaluationResultCallback); createBoundFunctionProperty(context, commandLineAPI, "$0", V8Console::inspectedObject0); createBoundFunctionProperty(context, commandLineAPI, "$1", V8Console::inspectedObject1); createBoundFunctionProperty(context, commandLineAPI, "$2", V8Console::inspectedObject2); createBoundFunctionProperty(context, commandLineAPI, "$3", V8Console::inspectedObject3); createBoundFunctionProperty(context, commandLineAPI, "$4", V8Console::inspectedObject4); inspectedContext->inspector()->client()->installAdditionalCommandLineAPI(context, commandLineAPI); commandLineAPI->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return commandLineAPI; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Object> V8Console::createCommandLineAPI(InspectedContext* inspectedContext) { v8::Local<v8::Context> context = inspectedContext->context(); v8::Isolate* isolate = context->GetIsolate(); v8::MicrotasksScope microtasksScope(isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); v8::Local<v8::Object> commandLineAPI = v8::Object::New(isolate); bool success = commandLineAPI->SetPrototype(context, v8::Null(isolate)).FromMaybe(false); DCHECK(success); createBoundFunctionProperty(context, commandLineAPI, "dir", V8Console::dirCallback, "function dir(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "dirxml", V8Console::dirxmlCallback, "function dirxml(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profile", V8Console::profileCallback, "function profile(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "profileEnd", V8Console::profileEndCallback, "function profileEnd(title) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "clear", V8Console::clearCallback, "function clear() { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "table", V8Console::tableCallback, "function table(data, [columns]) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "keys", V8Console::keysCallback, "function keys(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "values", V8Console::valuesCallback, "function values(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "debug", V8Console::debugFunctionCallback, "function debug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "undebug", V8Console::undebugFunctionCallback, "function undebug(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "monitor", V8Console::monitorFunctionCallback, "function monitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "unmonitor", V8Console::unmonitorFunctionCallback, "function unmonitor(function) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "inspect", V8Console::inspectCallback, "function inspect(object) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "copy", V8Console::copyCallback, "function copy(value) { [Command Line API] }"); createBoundFunctionProperty(context, commandLineAPI, "$_", V8Console::lastEvaluationResultCallback); createBoundFunctionProperty(context, commandLineAPI, "$0", V8Console::inspectedObject0); createBoundFunctionProperty(context, commandLineAPI, "$1", V8Console::inspectedObject1); createBoundFunctionProperty(context, commandLineAPI, "$2", V8Console::inspectedObject2); createBoundFunctionProperty(context, commandLineAPI, "$3", V8Console::inspectedObject3); createBoundFunctionProperty(context, commandLineAPI, "$4", V8Console::inspectedObject4); inspectedContext->inspector()->client()->installAdditionalCommandLineAPI(context, commandLineAPI); commandLineAPI->SetPrivate(context, inspectedContextPrivateKey(isolate), v8::External::New(isolate, inspectedContext)); return commandLineAPI; }
172,062
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 signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); }
169,955
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 ThreadableBlobRegistry::registerStreamURL(const KURL& url, const String& type) { if (isMainThread()) { blobRegistry().registerStreamURL(url, type); } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type)); callOnMainThread(&registerStreamURLTask, context.leakPtr()); } } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void ThreadableBlobRegistry::registerStreamURL(const KURL& url, const String& type) void BlobRegistry::registerStreamURL(const KURL& url, const String& type) { if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) registry->registerStreamURL(url, type); } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type)); callOnMainThread(&registerStreamURLTask, context.leakPtr()); } }
170,688
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 cypress_open(struct tty_struct *tty, struct usb_serial_port *port) { struct cypress_private *priv = usb_get_serial_port_data(port); struct usb_serial *serial = port->serial; unsigned long flags; int result = 0; if (!priv->comm_is_ok) return -EIO; /* clear halts before open */ usb_clear_halt(serial->dev, 0x81); usb_clear_halt(serial->dev, 0x02); spin_lock_irqsave(&priv->lock, flags); /* reset read/write statistics */ priv->bytes_in = 0; priv->bytes_out = 0; priv->cmd_count = 0; priv->rx_flags = 0; spin_unlock_irqrestore(&priv->lock, flags); /* Set termios */ cypress_send(port); if (tty) cypress_set_termios(tty, port, &priv->tmp_termios); /* setup the port and start reading from the device */ if (!port->interrupt_in_urb) { dev_err(&port->dev, "%s - interrupt_in_urb is empty!\n", __func__); return -1; } usb_fill_int_urb(port->interrupt_in_urb, serial->dev, usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress), port->interrupt_in_urb->transfer_buffer, port->interrupt_in_urb->transfer_buffer_length, cypress_read_int_callback, port, priv->read_urb_interval); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); if (result) { dev_err(&port->dev, "%s - failed submitting read urb, error %d\n", __func__, result); cypress_set_dead(port); } return result; } /* cypress_open */ Commit Message: USB: cypress_m8: add endpoint sanity check An attack using missing endpoints exists. CVE-2016-3137 Signed-off-by: Oliver Neukum <ONeukum@suse.com> CC: stable@vger.kernel.org Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> CWE ID:
static int cypress_open(struct tty_struct *tty, struct usb_serial_port *port) { struct cypress_private *priv = usb_get_serial_port_data(port); struct usb_serial *serial = port->serial; unsigned long flags; int result = 0; if (!priv->comm_is_ok) return -EIO; /* clear halts before open */ usb_clear_halt(serial->dev, 0x81); usb_clear_halt(serial->dev, 0x02); spin_lock_irqsave(&priv->lock, flags); /* reset read/write statistics */ priv->bytes_in = 0; priv->bytes_out = 0; priv->cmd_count = 0; priv->rx_flags = 0; spin_unlock_irqrestore(&priv->lock, flags); /* Set termios */ cypress_send(port); if (tty) cypress_set_termios(tty, port, &priv->tmp_termios); /* setup the port and start reading from the device */ usb_fill_int_urb(port->interrupt_in_urb, serial->dev, usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress), port->interrupt_in_urb->transfer_buffer, port->interrupt_in_urb->transfer_buffer_length, cypress_read_int_callback, port, priv->read_urb_interval); result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL); if (result) { dev_err(&port->dev, "%s - failed submitting read urb, error %d\n", __func__, result); cypress_set_dead(port); } return result; } /* cypress_open */
167,360
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 AutofillExternalDelegate::OnSuggestionsReturned( int query_id, const std::vector<Suggestion>& input_suggestions, bool autoselect_first_suggestion, bool is_all_server_suggestions) { if (query_id != query_id_) return; std::vector<Suggestion> suggestions(input_suggestions); PossiblyRemoveAutofillWarnings(&suggestions); #if !defined(OS_ANDROID) if (!suggestions.empty() && !features::ShouldUseNativeViews()) { suggestions.push_back(Suggestion()); suggestions.back().frontend_id = POPUP_ITEM_ID_SEPARATOR; } #endif if (should_show_scan_credit_card_) { Suggestion scan_credit_card( l10n_util::GetStringUTF16(IDS_AUTOFILL_SCAN_CREDIT_CARD)); scan_credit_card.frontend_id = POPUP_ITEM_ID_SCAN_CREDIT_CARD; scan_credit_card.icon = base::ASCIIToUTF16("scanCreditCardIcon"); suggestions.push_back(scan_credit_card); } has_autofill_suggestions_ = false; for (size_t i = 0; i < suggestions.size(); ++i) { if (suggestions[i].frontend_id > 0) { has_autofill_suggestions_ = true; break; } } if (should_show_cards_from_account_option_) { suggestions.emplace_back( l10n_util::GetStringUTF16(IDS_AUTOFILL_SHOW_ACCOUNT_CARDS)); suggestions.back().frontend_id = POPUP_ITEM_ID_SHOW_ACCOUNT_CARDS; suggestions.back().icon = base::ASCIIToUTF16("google"); } if (has_autofill_suggestions_) ApplyAutofillOptions(&suggestions, is_all_server_suggestions); if (suggestions.empty() && should_show_cc_signin_promo_) { #if !defined(OS_ANDROID) if (has_autofill_suggestions_) { suggestions.push_back(Suggestion()); suggestions.back().frontend_id = POPUP_ITEM_ID_SEPARATOR; } #endif Suggestion signin_promo_suggestion( l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDIT_CARD_SIGNIN_PROMO)); signin_promo_suggestion.frontend_id = POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO; suggestions.push_back(signin_promo_suggestion); signin_metrics::RecordSigninImpressionUserActionForAccessPoint( signin_metrics::AccessPoint::ACCESS_POINT_AUTOFILL_DROPDOWN); } #if !defined(OS_ANDROID) if (!suggestions.empty() && suggestions.back().frontend_id == POPUP_ITEM_ID_SEPARATOR) { suggestions.pop_back(); } #endif InsertDataListValues(&suggestions); if (suggestions.empty()) { manager_->client()->HideAutofillPopup(); return; } if (query_field_.is_focusable) { manager_->client()->ShowAutofillPopup( element_bounds_, query_field_.text_direction, suggestions, autoselect_first_suggestion, GetWeakPtr()); } } 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 <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
void AutofillExternalDelegate::OnSuggestionsReturned( int query_id, const std::vector<Suggestion>& input_suggestions, bool autoselect_first_suggestion, bool is_all_server_suggestions) { if (query_id != query_id_) return; std::vector<Suggestion> suggestions(input_suggestions); PossiblyRemoveAutofillWarnings(&suggestions); if (should_show_scan_credit_card_) { Suggestion scan_credit_card( l10n_util::GetStringUTF16(IDS_AUTOFILL_SCAN_CREDIT_CARD)); scan_credit_card.frontend_id = POPUP_ITEM_ID_SCAN_CREDIT_CARD; scan_credit_card.icon = base::ASCIIToUTF16("scanCreditCardIcon"); suggestions.push_back(scan_credit_card); } has_autofill_suggestions_ = false; for (size_t i = 0; i < suggestions.size(); ++i) { if (suggestions[i].frontend_id > 0) { has_autofill_suggestions_ = true; break; } } if (should_show_cards_from_account_option_) { suggestions.emplace_back( l10n_util::GetStringUTF16(IDS_AUTOFILL_SHOW_ACCOUNT_CARDS)); suggestions.back().frontend_id = POPUP_ITEM_ID_SHOW_ACCOUNT_CARDS; suggestions.back().icon = base::ASCIIToUTF16("google"); } if (has_autofill_suggestions_) ApplyAutofillOptions(&suggestions, is_all_server_suggestions); if (suggestions.empty() && should_show_cc_signin_promo_) { Suggestion signin_promo_suggestion( l10n_util::GetStringUTF16(IDS_AUTOFILL_CREDIT_CARD_SIGNIN_PROMO)); signin_promo_suggestion.frontend_id = POPUP_ITEM_ID_CREDIT_CARD_SIGNIN_PROMO; suggestions.push_back(signin_promo_suggestion); signin_metrics::RecordSigninImpressionUserActionForAccessPoint( signin_metrics::AccessPoint::ACCESS_POINT_AUTOFILL_DROPDOWN); } InsertDataListValues(&suggestions); if (suggestions.empty()) { manager_->client()->HideAutofillPopup(); return; } if (query_field_.is_focusable) { manager_->client()->ShowAutofillPopup( element_bounds_, query_field_.text_direction, suggestions, autoselect_first_suggestion, GetWeakPtr()); } }
172,097
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 vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; if (s->has_alpha) avctx->pix_fmt = AV_PIX_FMT_YUVA420P; } s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <rsbultje@gmail.com> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static int vp8_lossy_decode_frame(AVCodecContext *avctx, AVFrame *p, int *got_frame, uint8_t *data_start, unsigned int data_size) { WebPContext *s = avctx->priv_data; AVPacket pkt; int ret; if (!s->initialized) { ff_vp8_decode_init(avctx); s->initialized = 1; } avctx->pix_fmt = s->has_alpha ? AV_PIX_FMT_YUVA420P : AV_PIX_FMT_YUV420P; s->lossless = 0; if (data_size > INT_MAX) { av_log(avctx, AV_LOG_ERROR, "unsupported chunk size\n"); return AVERROR_PATCHWELCOME; } av_init_packet(&pkt); pkt.data = data_start; pkt.size = data_size; ret = ff_vp8_decode_frame(avctx, p, got_frame, &pkt); if (ret < 0) return ret; update_canvas_size(avctx, avctx->width, avctx->height); if (s->has_alpha) { ret = vp8_lossy_decode_alpha(avctx, p, s->alpha_data, s->alpha_data_size); if (ret < 0) return ret; } return ret; }
168,072
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 cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item ) { cJSON_AddItemToArray( array, create_reference( item ) ); } 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 <bmah@es.net> CWE ID: CWE-119
void cJSON_AddItemReferenceToArray( cJSON *array, cJSON *item )
167,265
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::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != 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; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = mTimeToSampleCount * 2 * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } 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::setTimeToSampleParams( off64_t data_offset, size_t data_size) { if (mTimeToSample != 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; } mTimeToSampleCount = U32_AT(&header[4]); uint64_t allocSize = mTimeToSampleCount * 2 * (uint64_t)sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mTimeToSample = new uint32_t[mTimeToSampleCount * 2]; size_t size = sizeof(uint32_t) * mTimeToSampleCount * 2; if (mDataSource->readAt( data_offset + 8, mTimeToSample, size) < (ssize_t)size) { return ERROR_IO; } for (uint32_t i = 0; i < mTimeToSampleCount * 2; ++i) { mTimeToSample[i] = ntohl(mTimeToSample[i]); } return OK; }
173,339
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 ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size) { if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]); } /* Copy overread bytes from last frame into buffer. */ for(; pc->overread>0; pc->overread--){ pc->buffer[pc->index++]= pc->buffer[pc->overread_index++]; } /* flush remaining if EOF */ if(!*buf_size && next == END_NOT_FOUND){ next= 0; } pc->last_index= pc->index; /* copy into buffer end return */ if(next == END_NOT_FOUND){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; memcpy(&pc->buffer[pc->index], *buf, *buf_size); pc->index += *buf_size; return -1; } *buf_size= pc->overread_index= pc->index + next; /* append to buffer */ if(pc->index){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) return AVERROR(ENOMEM); pc->buffer = new_buffer; if (next > -FF_INPUT_BUFFER_PADDING_SIZE) memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE); pc->index = 0; *buf= pc->buffer; } /* store overread bytes */ for(;next < 0; next++){ pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next]; pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next]; pc->overread++; } if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]); } return 0; } Commit Message: avcodec/parser: reset indexes on realloc failure Fixes Ticket2982 Signed-off-by: Michael Niedermayer <michaelni@gmx.at> CWE ID: CWE-119
int ff_combine_frame(ParseContext *pc, int next, const uint8_t **buf, int *buf_size) { if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1], (*buf)[2], (*buf)[3]); } /* Copy overread bytes from last frame into buffer. */ for(; pc->overread>0; pc->overread--){ pc->buffer[pc->index++]= pc->buffer[pc->overread_index++]; } /* flush remaining if EOF */ if(!*buf_size && next == END_NOT_FOUND){ next= 0; } pc->last_index= pc->index; /* copy into buffer end return */ if(next == END_NOT_FOUND){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, (*buf_size) + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) { pc->index = 0; return AVERROR(ENOMEM); } pc->buffer = new_buffer; memcpy(&pc->buffer[pc->index], *buf, *buf_size); pc->index += *buf_size; return -1; } *buf_size= pc->overread_index= pc->index + next; /* append to buffer */ if(pc->index){ void* new_buffer = av_fast_realloc(pc->buffer, &pc->buffer_size, next + pc->index + FF_INPUT_BUFFER_PADDING_SIZE); if(!new_buffer) { pc->overread_index = pc->index = 0; return AVERROR(ENOMEM); } pc->buffer = new_buffer; if (next > -FF_INPUT_BUFFER_PADDING_SIZE) memcpy(&pc->buffer[pc->index], *buf, next + FF_INPUT_BUFFER_PADDING_SIZE); pc->index = 0; *buf= pc->buffer; } /* store overread bytes */ for(;next < 0; next++){ pc->state = (pc->state<<8) | pc->buffer[pc->last_index + next]; pc->state64 = (pc->state64<<8) | pc->buffer[pc->last_index + next]; pc->overread++; } if(pc->overread){ av_dlog(NULL, "overread %d, state:%X next:%d index:%d o_index:%d\n", pc->overread, pc->state, next, pc->index, pc->overread_index); av_dlog(NULL, "%X %X %X %X\n", (*buf)[0], (*buf)[1],(*buf)[2],(*buf)[3]); } return 0; }
165,914
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: IPV6BuildTestPacket(uint32_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; uint8_t *pcontent; IPV6Hdr ip6h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip6h.s_ip6_nxt = 44; ip6h.s_ip6_hlim = 2; /* Source and dest address - very bogus addresses. */ ip6h.s_ip6_src[0] = 0x01010101; ip6h.s_ip6_src[1] = 0x01010101; ip6h.s_ip6_src[2] = 0x01010101; ip6h.s_ip6_src[3] = 0x01010101; ip6h.s_ip6_dst[0] = 0x02020202; ip6h.s_ip6_dst[1] = 0x02020202; ip6h.s_ip6_dst[2] = 0x02020202; ip6h.s_ip6_dst[3] = 0x02020202; /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip6h, sizeof(IPV6Hdr)); p->ip6h = (IPV6Hdr *)GET_PKT_DATA(p); IPV6_SET_RAW_VER(p->ip6h, 6); /* Fragmentation header. */ IPV6FragHdr *fh = (IPV6FragHdr *)(GET_PKT_DATA(p) + sizeof(IPV6Hdr)); fh->ip6fh_nxt = IPPROTO_ICMP; fh->ip6fh_ident = htonl(id); fh->ip6fh_offlg = htons((off << 3) | mf); DecodeIPV6FragHeader(p, (uint8_t *)fh, 8, 8 + content_len, 0); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr), pcontent, content_len); SET_PKT_LEN(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr) + content_len); SCFree(pcontent); p->ip6h->s_ip6_plen = htons(sizeof(IPV6FragHdr) + content_len); SET_IPV6_SRC_ADDR(p, &p->src); SET_IPV6_DST_ADDR(p, &p->dst); /* Self test. */ if (IPV6_GET_VER(p) != 6) goto error; if (IPV6_GET_NH(p) != 44) goto error; if (IPV6_GET_PLEN(p) != sizeof(IPV6FragHdr) + content_len) goto error; return p; error: fprintf(stderr, "Error building test packet.\n"); if (p != NULL) SCFree(p); return NULL; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
IPV6BuildTestPacket(uint32_t id, uint16_t off, int mf, const char content, IPV6BuildTestPacket(uint8_t proto, uint32_t id, uint16_t off, int mf, const char content, int content_len) { Packet *p = NULL; uint8_t *pcontent; IPV6Hdr ip6h; p = SCCalloc(1, sizeof(*p) + default_packet_size); if (unlikely(p == NULL)) return NULL; PACKET_INITIALIZE(p); gettimeofday(&p->ts, NULL); ip6h.s_ip6_nxt = 44; ip6h.s_ip6_hlim = 2; /* Source and dest address - very bogus addresses. */ ip6h.s_ip6_src[0] = 0x01010101; ip6h.s_ip6_src[1] = 0x01010101; ip6h.s_ip6_src[2] = 0x01010101; ip6h.s_ip6_src[3] = 0x01010101; ip6h.s_ip6_dst[0] = 0x02020202; ip6h.s_ip6_dst[1] = 0x02020202; ip6h.s_ip6_dst[2] = 0x02020202; ip6h.s_ip6_dst[3] = 0x02020202; /* copy content_len crap, we need full length */ PacketCopyData(p, (uint8_t *)&ip6h, sizeof(IPV6Hdr)); p->ip6h = (IPV6Hdr *)GET_PKT_DATA(p); IPV6_SET_RAW_VER(p->ip6h, 6); /* Fragmentation header. */ IPV6FragHdr *fh = (IPV6FragHdr *)(GET_PKT_DATA(p) + sizeof(IPV6Hdr)); fh->ip6fh_nxt = proto; fh->ip6fh_ident = htonl(id); fh->ip6fh_offlg = htons((off << 3) | mf); DecodeIPV6FragHeader(p, (uint8_t *)fh, 8, 8 + content_len, 0); pcontent = SCCalloc(1, content_len); if (unlikely(pcontent == NULL)) return NULL; memset(pcontent, content, content_len); PacketCopyDataOffset(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr), pcontent, content_len); SET_PKT_LEN(p, sizeof(IPV6Hdr) + sizeof(IPV6FragHdr) + content_len); SCFree(pcontent); p->ip6h->s_ip6_plen = htons(sizeof(IPV6FragHdr) + content_len); SET_IPV6_SRC_ADDR(p, &p->src); SET_IPV6_DST_ADDR(p, &p->dst); /* Self test. */ if (IPV6_GET_VER(p) != 6) goto error; if (IPV6_GET_NH(p) != 44) goto error; if (IPV6_GET_PLEN(p) != sizeof(IPV6FragHdr) + content_len) goto error; return p; error: fprintf(stderr, "Error building test packet.\n"); if (p != NULL) SCFree(p); return NULL; }
168,307
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: ssize_t MPEG4DataSource::readAt(off64_t offset, void *data, size_t size) { Mutex::Autolock autoLock(mLock); if (offset >= mCachedOffset && offset + size <= mCachedOffset + mCachedSize) { memcpy(data, &mCache[offset - mCachedOffset], size); return size; } return mSource->readAt(offset, data, size); } Commit Message: Add AUtils::isInRange, and use it to detect malformed MPEG4 nal sizes Bug: 19641538 Change-Id: I5aae3f100846c125decc61eec7cd6563e3f33777 CWE ID: CWE-119
ssize_t MPEG4DataSource::readAt(off64_t offset, void *data, size_t size) { Mutex::Autolock autoLock(mLock); if (isInRange(mCachedOffset, mCachedSize, offset, size)) { memcpy(data, &mCache[offset - mCachedOffset], size); return size; } return mSource->readAt(offset, data, size); }
173,364
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: xsltShallowCopyElem(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr insert, int isLRE) { xmlNodePtr copy; if ((node->type == XML_DTD_NODE) || (insert == NULL)) return(NULL); if ((node->type == XML_TEXT_NODE) || (node->type == XML_CDATA_SECTION_NODE)) return(xsltCopyText(ctxt, insert, node, 0)); copy = xmlDocCopyNode(node, insert->doc, 0); if (copy != NULL) { copy->doc = ctxt->output; copy = xsltAddChild(insert, copy); if (node->type == XML_ELEMENT_NODE) { /* * Add namespaces as they are needed */ if (node->nsDef != NULL) { /* * TODO: Remove the LRE case in the refactored code * gets enabled. */ if (isLRE) xsltCopyNamespaceList(ctxt, copy, node->nsDef); else xsltCopyNamespaceListInternal(copy, node->nsDef); } /* * URGENT TODO: The problem with this is that it does not * copy over all namespace nodes in scope. * The damn thing about this is, that we would need to * use the xmlGetNsList(), for every single node; this is * also done in xsltCopyTreeInternal(), but only for the top node. */ if (node->ns != NULL) { if (isLRE) { /* * REVISIT TODO: Since the non-refactored code still does * ns-aliasing, we need to call xsltGetNamespace() here. * Remove this when ready. */ copy->ns = xsltGetNamespace(ctxt, node, node->ns, copy); } else { copy->ns = xsltGetSpecialNamespace(ctxt, node, node->ns->href, node->ns->prefix, copy); } } else if ((insert->type == XML_ELEMENT_NODE) && (insert->ns != NULL)) { /* * "Undeclare" the default namespace. */ xsltGetSpecialNamespace(ctxt, node, NULL, NULL, copy); } } } else { xsltTransformError(ctxt, NULL, node, "xsltShallowCopyElem: copy %s failed\n", node->name); } return(copy); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltShallowCopyElem(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr insert, int isLRE) { xmlNodePtr copy; if ((node->type == XML_DTD_NODE) || (insert == NULL)) return(NULL); if ((node->type == XML_TEXT_NODE) || (node->type == XML_CDATA_SECTION_NODE)) return(xsltCopyText(ctxt, insert, node, 0)); copy = xmlDocCopyNode(node, insert->doc, 0); if (copy != NULL) { copy->doc = ctxt->output; copy = xsltAddChild(insert, copy); if (copy == NULL) { xsltTransformError(ctxt, NULL, node, "xsltShallowCopyElem: copy failed\n"); return (copy); } if (node->type == XML_ELEMENT_NODE) { /* * Add namespaces as they are needed */ if (node->nsDef != NULL) { /* * TODO: Remove the LRE case in the refactored code * gets enabled. */ if (isLRE) xsltCopyNamespaceList(ctxt, copy, node->nsDef); else xsltCopyNamespaceListInternal(copy, node->nsDef); } /* * URGENT TODO: The problem with this is that it does not * copy over all namespace nodes in scope. * The damn thing about this is, that we would need to * use the xmlGetNsList(), for every single node; this is * also done in xsltCopyTreeInternal(), but only for the top node. */ if (node->ns != NULL) { if (isLRE) { /* * REVISIT TODO: Since the non-refactored code still does * ns-aliasing, we need to call xsltGetNamespace() here. * Remove this when ready. */ copy->ns = xsltGetNamespace(ctxt, node, node->ns, copy); } else { copy->ns = xsltGetSpecialNamespace(ctxt, node, node->ns->href, node->ns->prefix, copy); } } else if ((insert->type == XML_ELEMENT_NODE) && (insert->ns != NULL)) { /* * "Undeclare" the default namespace. */ xsltGetSpecialNamespace(ctxt, node, NULL, NULL, copy); } } } else { xsltTransformError(ctxt, NULL, node, "xsltShallowCopyElem: copy %s failed\n", node->name); } return(copy); }
173,330
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: get_control(png_const_structrp png_ptr) { /* This just returns the (file*). The chunk and idat control structures * don't always exist. */ struct control *control = png_voidcast(struct control*, png_get_error_ptr(png_ptr)); return &control->file; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
get_control(png_const_structrp png_ptr) { /* This just returns the (file*). The chunk and idat control structures * don't always exist. */ struct control *control = voidcast(struct control*, png_get_error_ptr(png_ptr)); return &control->file; }
173,732
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 MemBackendImpl::EvictIfNeeded() { if (current_size_ <= max_size_) return; int target_size = std::max(0, max_size_ - kDefaultEvictionSize); base::LinkNode<MemEntryImpl>* entry = lru_list_.head(); while (current_size_ > target_size && entry != lru_list_.end()) { MemEntryImpl* to_doom = entry->value(); entry = entry->next(); if (!to_doom->InUse()) to_doom->Doom(); } } Commit Message: [MemCache] Fix bug while iterating LRU list in eviction It was possible to reanalyze a previously doomed entry. Bug: 827492 Change-Id: I5d34d2ae87c96e0d2099e926e6eb2c1b30b01d63 Reviewed-on: https://chromium-review.googlesource.com/987919 Commit-Queue: Josh Karlin <jkarlin@chromium.org> Reviewed-by: Maks Orlovich <morlovich@chromium.org> Cr-Commit-Position: refs/heads/master@{#547236} CWE ID: CWE-416
void MemBackendImpl::EvictIfNeeded() { if (current_size_ <= max_size_) return; int target_size = std::max(0, max_size_ - kDefaultEvictionSize); base::LinkNode<MemEntryImpl>* entry = lru_list_.head(); while (current_size_ > target_size && entry != lru_list_.end()) { MemEntryImpl* to_doom = entry->value(); do { entry = entry->next(); // It's possible that entry now points to a child of to_doom, and the // parent is about to be deleted. Skip past any child entries. } while (entry != lru_list_.end() && entry->value()->parent() == to_doom); if (!to_doom->InUse()) to_doom->Doom(); } }
172,700
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: gplotRead(const char *filename) { char buf[L_BUF_SIZE]; char *rootname, *title, *xlabel, *ylabel, *ignores; l_int32 outformat, ret, version, ignore; FILE *fp; GPLOT *gplot; PROCNAME("gplotRead"); if (!filename) return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL); if ((fp = fopenReadStream(filename)) == NULL) return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL); ret = fscanf(fp, "Gplot Version %d\n", &version); if (ret != 1) { fclose(fp); return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL); } if (version != GPLOT_VERSION_NUMBER) { fclose(fp); return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL); } ignore = fscanf(fp, "Rootname: %s\n", buf); rootname = stringNew(buf); ignore = fscanf(fp, "Output format: %d\n", &outformat); ignores = fgets(buf, L_BUF_SIZE, fp); /* Title: ... */ title = stringNew(buf + 7); title[strlen(title) - 1] = '\0'; ignores = fgets(buf, L_BUF_SIZE, fp); /* X axis label: ... */ xlabel = stringNew(buf + 14); xlabel[strlen(xlabel) - 1] = '\0'; ignores = fgets(buf, L_BUF_SIZE, fp); /* Y axis label: ... */ ylabel = stringNew(buf + 14); ylabel[strlen(ylabel) - 1] = '\0'; gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel); LEPT_FREE(rootname); LEPT_FREE(title); LEPT_FREE(xlabel); LEPT_FREE(ylabel); if (!gplot) { fclose(fp); return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL); } sarrayDestroy(&gplot->cmddata); sarrayDestroy(&gplot->datanames); sarrayDestroy(&gplot->plotdata); sarrayDestroy(&gplot->plottitles); numaDestroy(&gplot->plotstyles); ignore = fscanf(fp, "Commandfile name: %s\n", buf); stringReplace(&gplot->cmdname, buf); ignore = fscanf(fp, "\nCommandfile data:"); gplot->cmddata = sarrayReadStream(fp); ignore = fscanf(fp, "\nDatafile names:"); gplot->datanames = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot data:"); gplot->plotdata = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot titles:"); gplot->plottitles = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot styles:"); gplot->plotstyles = numaReadStream(fp); ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots); ignore = fscanf(fp, "Output file name: %s\n", buf); stringReplace(&gplot->outname, buf); ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling); fclose(fp); return gplot; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotRead(const char *filename) { char buf[L_BUFSIZE]; char *rootname, *title, *xlabel, *ylabel, *ignores; l_int32 outformat, ret, version, ignore; FILE *fp; GPLOT *gplot; PROCNAME("gplotRead"); if (!filename) return (GPLOT *)ERROR_PTR("filename not defined", procName, NULL); if ((fp = fopenReadStream(filename)) == NULL) return (GPLOT *)ERROR_PTR("stream not opened", procName, NULL); ret = fscanf(fp, "Gplot Version %d\n", &version); if (ret != 1) { fclose(fp); return (GPLOT *)ERROR_PTR("not a gplot file", procName, NULL); } if (version != GPLOT_VERSION_NUMBER) { fclose(fp); return (GPLOT *)ERROR_PTR("invalid gplot version", procName, NULL); } ignore = fscanf(fp, "Rootname: %511s\n", buf); /* L_BUFSIZE - 1 */ rootname = stringNew(buf); ignore = fscanf(fp, "Output format: %d\n", &outformat); ignores = fgets(buf, L_BUFSIZE, fp); /* Title: ... */ title = stringNew(buf + 7); title[strlen(title) - 1] = '\0'; ignores = fgets(buf, L_BUFSIZE, fp); /* X axis label: ... */ xlabel = stringNew(buf + 14); xlabel[strlen(xlabel) - 1] = '\0'; ignores = fgets(buf, L_BUFSIZE, fp); /* Y axis label: ... */ ylabel = stringNew(buf + 14); ylabel[strlen(ylabel) - 1] = '\0'; gplot = gplotCreate(rootname, outformat, title, xlabel, ylabel); LEPT_FREE(rootname); LEPT_FREE(title); LEPT_FREE(xlabel); LEPT_FREE(ylabel); if (!gplot) { fclose(fp); return (GPLOT *)ERROR_PTR("gplot not made", procName, NULL); } sarrayDestroy(&gplot->cmddata); sarrayDestroy(&gplot->datanames); sarrayDestroy(&gplot->plotdata); sarrayDestroy(&gplot->plottitles); numaDestroy(&gplot->plotstyles); ignore = fscanf(fp, "Commandfile name: %511s\n", buf); /* L_BUFSIZE - 1 */ stringReplace(&gplot->cmdname, buf); ignore = fscanf(fp, "\nCommandfile data:"); gplot->cmddata = sarrayReadStream(fp); ignore = fscanf(fp, "\nDatafile names:"); gplot->datanames = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot data:"); gplot->plotdata = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot titles:"); gplot->plottitles = sarrayReadStream(fp); ignore = fscanf(fp, "\nPlot styles:"); gplot->plotstyles = numaReadStream(fp); ignore = fscanf(fp, "Number of plots: %d\n", &gplot->nplots); ignore = fscanf(fp, "Output file name: %511s\n", buf); stringReplace(&gplot->outname, buf); ignore = fscanf(fp, "Axis scaling: %d\n", &gplot->scaling); fclose(fp); return gplot; }
169,327
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: layer_resize(int layer, int x_size, int y_size) { int old_height; int old_width; struct map_tile* tile; int tile_width; int tile_height; struct map_tile* tilemap; struct map_trigger* trigger; struct map_zone* zone; int x, y, i; old_width = s_map->layers[layer].width; old_height = s_map->layers[layer].height; if (!(tilemap = malloc(x_size * y_size * sizeof(struct map_tile)))) return false; for (x = 0; x < x_size; ++x) { for (y = 0; y < y_size; ++y) { if (x < old_width && y < old_height) { tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width]; } else { tile = &tilemap[x + y * x_size]; tile->frames_left = tileset_get_delay(s_map->tileset, 0); tile->tile_index = 0; } } } free(s_map->layers[layer].tilemap); s_map->layers[layer].tilemap = tilemap; s_map->layers[layer].width = x_size; s_map->layers[layer].height = y_size; tileset_get_size(s_map->tileset, &tile_width, &tile_height); s_map->width = 0; s_map->height = 0; for (i = 0; i < s_map->num_layers; ++i) { if (!s_map->layers[i].is_parallax) { s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width); s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height); } } for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) { zone = vector_get(s_map->zones, i); if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height) vector_remove(s_map->zones, i); else { if (zone->bounds.x2 > s_map->width) zone->bounds.x2 = s_map->width; if (zone->bounds.y2 > s_map->height) zone->bounds.y2 = s_map->height; } } for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) { trigger = vector_get(s_map->triggers, i); if (trigger->x >= s_map->width || trigger->y >= s_map->height) vector_remove(s_map->triggers, i); } return true; } Commit Message: Fix integer overflow in layer_resize in map_engine.c (#268) * Fix integer overflow in layer_resize in map_engine.c There's a buffer overflow bug in the function layer_resize. It allocates a buffer `tilemap` with size `x_size * y_size * sizeof(struct map_tile)`. But it didn't check for integer overflow, so if x_size and y_size are very large, it's possible that the buffer size is smaller than needed, causing a buffer overflow later. PoC: `SetLayerSize(0, 0x7FFFFFFF, 0x7FFFFFFF);` * move malloc to a separate line CWE ID: CWE-190
layer_resize(int layer, int x_size, int y_size) { int old_height; int old_width; struct map_tile* tile; int tile_width; int tile_height; struct map_tile* tilemap; struct map_trigger* trigger; struct map_zone* zone; size_t tilemap_size; int x, y, i; old_width = s_map->layers[layer].width; old_height = s_map->layers[layer].height; tilemap_size = x_size * y_size * sizeof(struct map_tile); if (x_size == 0 || tilemap_size / x_size / sizeof(struct map_tile) != y_size || !(tilemap = malloc(tilemap_size))) return false; for (x = 0; x < x_size; ++x) { for (y = 0; y < y_size; ++y) { if (x < old_width && y < old_height) { tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width]; } else { tile = &tilemap[x + y * x_size]; tile->frames_left = tileset_get_delay(s_map->tileset, 0); tile->tile_index = 0; } } } free(s_map->layers[layer].tilemap); s_map->layers[layer].tilemap = tilemap; s_map->layers[layer].width = x_size; s_map->layers[layer].height = y_size; tileset_get_size(s_map->tileset, &tile_width, &tile_height); s_map->width = 0; s_map->height = 0; for (i = 0; i < s_map->num_layers; ++i) { if (!s_map->layers[i].is_parallax) { s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width); s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height); } } for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) { zone = vector_get(s_map->zones, i); if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height) vector_remove(s_map->zones, i); else { if (zone->bounds.x2 > s_map->width) zone->bounds.x2 = s_map->width; if (zone->bounds.y2 > s_map->height) zone->bounds.y2 = s_map->height; } } for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) { trigger = vector_get(s_map->triggers, i); if (trigger->x >= s_map->width || trigger->y >= s_map->height) vector_remove(s_map->triggers, i); } return true; }
168,941
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 <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> 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: UserCloudPolicyManagerFactoryChromeOS::CreateManagerForProfile( Profile* profile, bool force_immediate_load, scoped_refptr<base::SequencedTaskRunner> background_task_runner) { const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (chromeos::ProfileHelper::IsSigninProfile(profile)) return scoped_ptr<UserCloudPolicyManagerChromeOS>(); chromeos::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile); CHECK(user); const std::string& username = user->email(); if (user->GetType() != user_manager::USER_TYPE_REGULAR || BrowserPolicyConnector::IsNonEnterpriseUser(username)) { return scoped_ptr<UserCloudPolicyManagerChromeOS>(); } policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); UserAffiliation affiliation = connector->GetUserAffiliation(username); const bool is_managed_user = affiliation == USER_AFFILIATION_MANAGED; const bool is_browser_restart = command_line->HasSwitch(chromeos::switches::kLoginUser); const bool wait_for_initial_policy = is_managed_user && !is_browser_restart; DeviceManagementService* device_management_service = connector->device_management_service(); if (wait_for_initial_policy) device_management_service->ScheduleInitialization(0); base::FilePath profile_dir = profile->GetPath(); const base::FilePath legacy_dir = profile_dir.Append(kDeviceManagementDir); const base::FilePath policy_cache_file = legacy_dir.Append(kPolicy); const base::FilePath token_cache_file = legacy_dir.Append(kToken); const base::FilePath component_policy_cache_dir = profile_dir.Append(kPolicy).Append(kComponentsDir); const base::FilePath external_data_dir = profile_dir.Append(kPolicy).Append(kPolicyExternalDataDir); base::FilePath policy_key_dir; CHECK(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &policy_key_dir)); scoped_ptr<UserCloudPolicyStoreChromeOS> store( new UserCloudPolicyStoreChromeOS( chromeos::DBusThreadManager::Get()->GetCryptohomeClient(), chromeos::DBusThreadManager::Get()->GetSessionManagerClient(), background_task_runner, username, policy_key_dir, token_cache_file, policy_cache_file)); scoped_refptr<base::SequencedTaskRunner> backend_task_runner = content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( content::BrowserThread::GetBlockingPool()->GetSequenceToken()); scoped_refptr<base::SequencedTaskRunner> io_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO); scoped_ptr<CloudExternalDataManager> external_data_manager( new UserCloudExternalDataManager(base::Bind(&GetChromePolicyDetails), backend_task_runner, io_task_runner, external_data_dir, store.get())); if (force_immediate_load) store->LoadImmediately(); scoped_refptr<base::SequencedTaskRunner> file_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::FILE); scoped_ptr<UserCloudPolicyManagerChromeOS> manager( new UserCloudPolicyManagerChromeOS( store.PassAs<CloudPolicyStore>(), external_data_manager.Pass(), component_policy_cache_dir, wait_for_initial_policy, base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds), base::MessageLoopProxy::current(), file_task_runner, io_task_runner)); bool wildcard_match = false; if (connector->IsEnterpriseManaged() && chromeos::LoginUtils::IsWhitelisted(username, &wildcard_match) && wildcard_match && !connector->IsNonEnterpriseUser(username)) { manager->EnableWildcardLoginCheck(username); } manager->Init( SchemaRegistryServiceFactory::GetForContext(profile)->registry()); manager->Connect(g_browser_process->local_state(), device_management_service, g_browser_process->system_request_context(), affiliation); DCHECK(managers_.find(profile) == managers_.end()); managers_[profile] = manager.get(); return manager.Pass(); } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
UserCloudPolicyManagerFactoryChromeOS::CreateManagerForProfile( Profile* profile, bool force_immediate_load, scoped_refptr<base::SequencedTaskRunner> background_task_runner) { const CommandLine* command_line = CommandLine::ForCurrentProcess(); if (chromeos::ProfileHelper::IsSigninProfile(profile)) return scoped_ptr<UserCloudPolicyManagerChromeOS>(); chromeos::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile); CHECK(user); // Non-managed domains will be skipped by the below check const std::string& username = user->email(); if (user->GetType() != user_manager::USER_TYPE_REGULAR || BrowserPolicyConnector::IsNonEnterpriseUser(username)) { return scoped_ptr<UserCloudPolicyManagerChromeOS>(); } policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); UserAffiliation affiliation = connector->GetUserAffiliation(username); const bool is_affiliated_user = affiliation == USER_AFFILIATION_MANAGED; const bool is_browser_restart = command_line->HasSwitch(chromeos::switches::kLoginUser); const bool wait_for_initial_policy = !is_browser_restart && (chromeos::UserManager::Get()->IsCurrentUserNew() || is_affiliated_user); const base::TimeDelta initial_policy_fetch_timeout = chromeos::UserManager::Get()->IsCurrentUserNew() ? base::TimeDelta::Max() : base::TimeDelta::FromSeconds(kInitialPolicyFetchTimeoutSeconds); DeviceManagementService* device_management_service = connector->device_management_service(); if (wait_for_initial_policy) device_management_service->ScheduleInitialization(0); base::FilePath profile_dir = profile->GetPath(); const base::FilePath legacy_dir = profile_dir.Append(kDeviceManagementDir); const base::FilePath policy_cache_file = legacy_dir.Append(kPolicy); const base::FilePath token_cache_file = legacy_dir.Append(kToken); const base::FilePath component_policy_cache_dir = profile_dir.Append(kPolicy).Append(kComponentsDir); const base::FilePath external_data_dir = profile_dir.Append(kPolicy).Append(kPolicyExternalDataDir); base::FilePath policy_key_dir; CHECK(PathService::Get(chromeos::DIR_USER_POLICY_KEYS, &policy_key_dir)); scoped_ptr<UserCloudPolicyStoreChromeOS> store( new UserCloudPolicyStoreChromeOS( chromeos::DBusThreadManager::Get()->GetCryptohomeClient(), chromeos::DBusThreadManager::Get()->GetSessionManagerClient(), background_task_runner, username, policy_key_dir, token_cache_file, policy_cache_file)); scoped_refptr<base::SequencedTaskRunner> backend_task_runner = content::BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( content::BrowserThread::GetBlockingPool()->GetSequenceToken()); scoped_refptr<base::SequencedTaskRunner> io_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::IO); scoped_ptr<CloudExternalDataManager> external_data_manager( new UserCloudExternalDataManager(base::Bind(&GetChromePolicyDetails), backend_task_runner, io_task_runner, external_data_dir, store.get())); if (force_immediate_load) store->LoadImmediately(); scoped_refptr<base::SequencedTaskRunner> file_task_runner = content::BrowserThread::GetMessageLoopProxyForThread( content::BrowserThread::FILE); scoped_ptr<UserCloudPolicyManagerChromeOS> manager( new UserCloudPolicyManagerChromeOS( store.PassAs<CloudPolicyStore>(), external_data_manager.Pass(), component_policy_cache_dir, wait_for_initial_policy, initial_policy_fetch_timeout, base::MessageLoopProxy::current(), file_task_runner, io_task_runner)); bool wildcard_match = false; if (connector->IsEnterpriseManaged() && chromeos::LoginUtils::IsWhitelisted(username, &wildcard_match) && wildcard_match && !connector->IsNonEnterpriseUser(username)) { manager->EnableWildcardLoginCheck(username); } manager->Init( SchemaRegistryServiceFactory::GetForContext(profile)->registry()); manager->Connect(g_browser_process->local_state(), device_management_service, g_browser_process->system_request_context(), affiliation); DCHECK(managers_.find(profile) == managers_.end()); managers_[profile] = manager.get(); return manager.Pass(); }
171,150
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: char* _single_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( len + 1 ); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; return chr; } Commit Message: New Pre Source CWE ID: CWE-119
char* _single_string_alloc_and_copy( LPCWSTR in ) { char *chr; int len = 0; if ( !in ) { return NULL; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( len + 1 ); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = 0xFF & in[ len ]; len ++; } chr[ len ++ ] = '\0'; return chr; }
169,315
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: l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); }
167,899
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 ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (Stream_GetRemainingLength(s) < 8) return -1; Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */ Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */ Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ return 1; }
169,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: int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) { for (int page_index : visible_pages_) { if (pages_[page_index]->GetPage() == page) return page_index; } return -1; } Commit Message: Copy visible_pages_ when iterating over it. On this case, a call inside the loop may cause visible_pages_ to change. Bug: 822091 Change-Id: I41b0715faa6fe3e39203cd9142cf5ea38e59aefb Reviewed-on: https://chromium-review.googlesource.com/964592 Reviewed-by: dsinclair <dsinclair@chromium.org> Commit-Queue: Henrique Nakashima <hnakashima@chromium.org> Cr-Commit-Position: refs/heads/master@{#543494} CWE ID: CWE-20
int PDFiumEngine::GetVisiblePageIndex(FPDF_PAGE page) { // Copy visible_pages_ since it can change as a result of loading the page in // GetPage(). See https://crbug.com/822091. std::vector<int> visible_pages_copy(visible_pages_); for (int page_index : visible_pages_copy) { if (pages_[page_index]->GetPage() == page) return page_index; } return -1; }
172,701
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: XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return) { XIDeviceInfo *info = NULL; xXIQueryDeviceReq *req; xXIQueryDeviceReq *req; xXIQueryDeviceReply reply; char *ptr; int i; char *buf; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1) goto error_unlocked; GetReq(XIQueryDevice, req); req->reqType = extinfo->codes->major_opcode; req->ReqType = X_XIQueryDevice; req->deviceid = deviceid; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; *ndevices_return = reply.num_devices; info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo)); if (!info) goto error; buf = Xmalloc(reply.length * 4); _XRead(dpy, buf, reply.length * 4); ptr = buf; /* info is a null-terminated array */ info[reply.num_devices].name = NULL; nclasses = wire->num_classes; ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); XIDeviceInfo *lib = &info[i]; xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr; lib->deviceid = wire->deviceid; lib->use = wire->use; lib->attachment = wire->attachment; Xfree(buf); ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); strncpy(lib->name, ptr, wire->name_len); ptr += ((wire->name_len + 3)/4) * 4; sz = size_classes((xXIAnyInfo*)ptr, nclasses); lib->classes = Xmalloc(sz); ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses); /* We skip over unused classes */ lib->num_classes = nclasses; } Commit Message: CWE ID: CWE-284
XIQueryDevice(Display *dpy, int deviceid, int *ndevices_return) { XIDeviceInfo *info = NULL; xXIQueryDeviceReq *req; xXIQueryDeviceReq *req; xXIQueryDeviceReply reply; char *ptr; char *end; int i; char *buf; LockDisplay(dpy); if (_XiCheckExtInit(dpy, XInput_2_0, extinfo) == -1) goto error_unlocked; GetReq(XIQueryDevice, req); req->reqType = extinfo->codes->major_opcode; req->ReqType = X_XIQueryDevice; req->deviceid = deviceid; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (!_XReply(dpy, (xReply*) &reply, 0, xFalse)) goto error; if (reply.length < INT_MAX / 4) { *ndevices_return = reply.num_devices; info = Xmalloc((reply.num_devices + 1) * sizeof(XIDeviceInfo)); } else { *ndevices_return = 0; info = NULL; } if (!info) goto error; buf = Xmalloc(reply.length * 4); _XRead(dpy, buf, reply.length * 4); ptr = buf; end = buf + reply.length * 4; /* info is a null-terminated array */ info[reply.num_devices].name = NULL; nclasses = wire->num_classes; ptr += sizeof(xXIDeviceInfo); lib->name = Xcalloc(wire->name_len + 1, 1); XIDeviceInfo *lib = &info[i]; xXIDeviceInfo *wire = (xXIDeviceInfo*)ptr; if (ptr + sizeof(xXIDeviceInfo) > end) goto error_loop; lib->deviceid = wire->deviceid; lib->use = wire->use; lib->attachment = wire->attachment; Xfree(buf); ptr += sizeof(xXIDeviceInfo); if (ptr + wire->name_len > end) goto error_loop; lib->name = Xcalloc(wire->name_len + 1, 1); if (lib->name == NULL) goto error_loop; strncpy(lib->name, ptr, wire->name_len); lib->name[wire->name_len] = '\0'; ptr += ((wire->name_len + 3)/4) * 4; sz = size_classes((xXIAnyInfo*)ptr, nclasses); lib->classes = Xmalloc(sz); if (lib->classes == NULL) { Xfree(lib->name); goto error_loop; } ptr += copy_classes(lib, (xXIAnyInfo*)ptr, &nclasses); /* We skip over unused classes */ lib->num_classes = nclasses; }
164,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: static void php_snmp_object_free_storage(void *object TSRMLS_DC) { php_snmp_object *intern = (php_snmp_object *)object; if (!intern) { return; } netsnmp_session_free(&(intern->session)); zend_object_std_dtor(&intern->zo TSRMLS_CC); efree(intern); } Commit Message: CWE ID: CWE-416
static void php_snmp_object_free_storage(void *object TSRMLS_DC) { php_snmp_object *intern = (php_snmp_object *)object; if (!intern) { return; } netsnmp_session_free(&(intern->session)); zend_object_std_dtor(&intern->zo TSRMLS_CC); efree(intern); }
164,977
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: cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SEC_SIZE(h), i, j; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; } Commit Message: Fix bounds checks again. CWE ID: CWE-119
cdf_read_short_sector_chain(const cdf_header_t *h, const cdf_sat_t *ssat, const cdf_stream_t *sst, cdf_secid_t sid, size_t len, cdf_stream_t *scn) { size_t ss = CDF_SHORT_SEC_SIZE(h), i, j; scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h)); scn->sst_dirlen = len; if (sst->sst_tab == NULL || scn->sst_len == (size_t)-1) return -1; scn->sst_tab = calloc(scn->sst_len, ss); if (scn->sst_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sector chain loop limit")); errno = EFTYPE; goto out; } if (i >= scn->sst_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, scn->sst_len)); errno = EFTYPE; goto out; } if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sector chain %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]); } return 0; out: free(scn->sst_tab); return -1; }
165,625
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 GLES2DecoderImpl::CheckFramebufferValid( Framebuffer* framebuffer, GLenum target, const char* func_name) { if (!framebuffer) { if (backbuffer_needs_clear_bits_) { glClearColor(0, 0, 0, (GLES2Util::GetChannelsForFormat( offscreen_target_color_format_) & 0x0008) != 0 ? 0 : 1); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); glClear(backbuffer_needs_clear_bits_); backbuffer_needs_clear_bits_ = 0; RestoreClearState(); } return true; } if (framebuffer_manager()->IsComplete(framebuffer)) { return true; } GLenum completeness = framebuffer->IsPossiblyComplete(); if (completeness != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete"); return false; } if (renderbuffer_manager()->HaveUnclearedRenderbuffers() || texture_manager()->HaveUnclearedMips()) { if (!framebuffer->IsCleared()) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (clear)"); return false; } ClearUnclearedAttachments(target, framebuffer); } } if (!framebuffer_manager()->IsComplete(framebuffer)) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (check)"); return false; } framebuffer_manager()->MarkAsComplete(framebuffer); } return true; } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance R=kbr@chromium.org,bajones@chromium.org Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool GLES2DecoderImpl::CheckFramebufferValid( Framebuffer* framebuffer, GLenum target, const char* func_name) { if (!framebuffer) { if (backbuffer_needs_clear_bits_) { glClearColor(0, 0, 0, (GLES2Util::GetChannelsForFormat( offscreen_target_color_format_) & 0x0008) != 0 ? 0 : 1); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); bool reset_draw_buffer = false; if ((backbuffer_needs_clear_bits_ | GL_COLOR_BUFFER_BIT) != 0 && group_->draw_buffer() == GL_NONE) { reset_draw_buffer = true; GLenum buf = GL_BACK; if (GetBackbufferServiceId() != 0) // emulated backbuffer buf = GL_COLOR_ATTACHMENT0; glDrawBuffersARB(1, &buf); } glClear(backbuffer_needs_clear_bits_); if (reset_draw_buffer) { GLenum buf = GL_NONE; glDrawBuffersARB(1, &buf); } backbuffer_needs_clear_bits_ = 0; RestoreClearState(); } return true; } if (framebuffer_manager()->IsComplete(framebuffer)) { return true; } GLenum completeness = framebuffer->IsPossiblyComplete(); if (completeness != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete"); return false; } if (renderbuffer_manager()->HaveUnclearedRenderbuffers() || texture_manager()->HaveUnclearedMips()) { if (!framebuffer->IsCleared()) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (clear)"); return false; } ClearUnclearedAttachments(target, framebuffer); } } if (!framebuffer_manager()->IsComplete(framebuffer)) { if (framebuffer->GetStatus(texture_manager(), target) != GL_FRAMEBUFFER_COMPLETE) { LOCAL_SET_GL_ERROR( GL_INVALID_FRAMEBUFFER_OPERATION, func_name, "framebuffer incomplete (check)"); return false; } framebuffer_manager()->MarkAsComplete(framebuffer); } return true; }
171,657
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: mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; } Commit Message: CVE-2017-13023/IPv6 mobility: Add a bounds check before fetching data 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 cause 'tcpdump: pcap_loop: truncated dump file' CWE ID: CWE-125
mobility_opt_print(netdissect_options *ndo, const u_char *bp, const unsigned len) { unsigned i, optlen; for (i = 0; i < len; i += optlen) { ND_TCHECK(bp[i]); if (bp[i] == IP6MOPT_PAD1) optlen = 1; else { if (i + 1 < len) { ND_TCHECK(bp[i + 1]); optlen = bp[i + 1] + 2; } else goto trunc; } if (i + optlen > len) goto trunc; ND_TCHECK(bp[i + optlen]); switch (bp[i]) { case IP6MOPT_PAD1: ND_PRINT((ndo, "(pad1)")); break; case IP6MOPT_PADN: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(padn: trunc)")); goto trunc; } ND_PRINT((ndo, "(padn)")); break; case IP6MOPT_REFRESH: if (len - i < IP6MOPT_REFRESH_MINLEN) { ND_PRINT((ndo, "(refresh: trunc)")); goto trunc; } /* units of 4 secs */ ND_TCHECK_16BITS(&bp[i+2]); ND_PRINT((ndo, "(refresh: %u)", EXTRACT_16BITS(&bp[i+2]) << 2)); break; case IP6MOPT_ALTCOA: if (len - i < IP6MOPT_ALTCOA_MINLEN) { ND_PRINT((ndo, "(altcoa: trunc)")); goto trunc; } ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2]))); break; case IP6MOPT_NONCEID: if (len - i < IP6MOPT_NONCEID_MINLEN) { ND_PRINT((ndo, "(ni: trunc)")); goto trunc; } ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)", EXTRACT_16BITS(&bp[i+2]), EXTRACT_16BITS(&bp[i+4]))); break; case IP6MOPT_AUTH: if (len - i < IP6MOPT_AUTH_MINLEN) { ND_PRINT((ndo, "(auth: trunc)")); goto trunc; } ND_PRINT((ndo, "(auth)")); break; default: if (len - i < IP6MOPT_MINLEN) { ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i])); goto trunc; } ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1])); break; } } return 0; trunc: return 1; }
167,868
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 fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); free(name); return 0; } Commit Message: fsck: detect submodule urls starting with dash Urls with leading dashes can cause mischief on older versions of Git. We should detect them so that they can be rejected by receive.fsckObjects, preventing modern versions of git from being a vector by which attacks can spread. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com> CWE ID: CWE-20
static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); free(name); return 0; }
169,019
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 struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt = (struct rt6_info *)dst; if (!dst) goto out; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) { dst_release(dst); dst = NULL; } out: return dst; } Commit Message: ipv6: ip6_sk_dst_check() must not assume ipv6 dst It's possible to use AF_INET6 sockets and to connect to an IPv4 destination. After this, socket dst cache is a pointer to a rtable, not rt6_info. ip6_sk_dst_check() should check the socket dst cache is IPv6, or else various corruptions/crashes can happen. Dave Jones can reproduce immediate crash with trinity -q -l off -n -c sendmsg -c connect With help from Hannes Frederic Sowa Reported-by: Dave Jones <davej@redhat.com> Reported-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt; if (!dst) goto out; if (dst->ops->family != AF_INET6) { dst_release(dst); return NULL; } rt = (struct rt6_info *)dst; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) { dst_release(dst); dst = NULL; } out: return dst; }
166,076
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 encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, int flags, VpxVideoWriter *writer) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } } 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
static void encode_frame(vpx_codec_ctx_t *codec, static int encode_frame(vpx_codec_ctx_t *codec, vpx_image_t *img, int frame_index, int flags, VpxVideoWriter *writer) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, flags, VPX_DL_GOOD_QUALITY); if (res != VPX_CODEC_OK) die_codec(codec, "Failed to encode frame"); while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) { const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0; if (!vpx_video_writer_write_frame(writer, pkt->data.frame.buf, pkt->data.frame.sz, pkt->data.frame.pts)) { die_codec(codec, "Failed to write compressed frame"); } printf(keyframe ? "K" : "."); fflush(stdout); } } return got_pkts; }
174,488
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: iperf_on_connect(struct iperf_test *test) { time_t now_secs; const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT"; char now_str[100]; char ipr[INET6_ADDRSTRLEN]; int port; struct sockaddr_storage sa; struct sockaddr_in *sa_inP; struct sockaddr_in6 *sa_in6P; socklen_t len; int opt; now_secs = time((time_t*) 0); (void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs)); if (test->json_output) cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s timesecs: %d", now_str, (int64_t) now_secs)); else if (test->verbose) iprintf(test, report_time, now_str); if (test->role == 'c') { if (test->json_output) cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s port: %d", test->server_hostname, (int64_t) test->server_port)); else { iprintf(test, report_connecting, test->server_hostname, test->server_port); if (test->reverse) iprintf(test, report_reverse, test->server_hostname); } } else { len = sizeof(sa); getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len); if (getsockdomain(test->ctrl_sck) == AF_INET) { sa_inP = (struct sockaddr_in *) &sa; inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr)); port = ntohs(sa_inP->sin_port); } else { sa_in6P = (struct sockaddr_in6 *) &sa; inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr)); port = ntohs(sa_in6P->sin6_port); } mapped_v4_to_regular_v4(ipr); if (test->json_output) cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port)); else iprintf(test, report_accepted, ipr, port); } if (test->json_output) { cJSON_AddStringToObject(test->json_start, "cookie", test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) cJSON_AddIntToObject(test->json_start, "tcp_mss", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); cJSON_AddIntToObject(test->json_start, "tcp_mss_default", opt); } } } else if (test->verbose) { iprintf(test, report_cookie, test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) iprintf(test, " TCP MSS: %d\n", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); iprintf(test, " TCP MSS: %d (default)\n", opt); } } } } 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 <bmah@es.net> CWE ID: CWE-119
iperf_on_connect(struct iperf_test *test) { time_t now_secs; const char* rfc1123_fmt = "%a, %d %b %Y %H:%M:%S GMT"; char now_str[100]; char ipr[INET6_ADDRSTRLEN]; int port; struct sockaddr_storage sa; struct sockaddr_in *sa_inP; struct sockaddr_in6 *sa_in6P; socklen_t len; int opt; now_secs = time((time_t*) 0); (void) strftime(now_str, sizeof(now_str), rfc1123_fmt, gmtime(&now_secs)); if (test->json_output) cJSON_AddItemToObject(test->json_start, "timestamp", iperf_json_printf("time: %s timesecs: %d", now_str, (int64_t) now_secs)); else if (test->verbose) iprintf(test, report_time, now_str); if (test->role == 'c') { if (test->json_output) cJSON_AddItemToObject(test->json_start, "connecting_to", iperf_json_printf("host: %s port: %d", test->server_hostname, (int64_t) test->server_port)); else { iprintf(test, report_connecting, test->server_hostname, test->server_port); if (test->reverse) iprintf(test, report_reverse, test->server_hostname); } } else { len = sizeof(sa); getpeername(test->ctrl_sck, (struct sockaddr *) &sa, &len); if (getsockdomain(test->ctrl_sck) == AF_INET) { sa_inP = (struct sockaddr_in *) &sa; inet_ntop(AF_INET, &sa_inP->sin_addr, ipr, sizeof(ipr)); port = ntohs(sa_inP->sin_port); } else { sa_in6P = (struct sockaddr_in6 *) &sa; inet_ntop(AF_INET6, &sa_in6P->sin6_addr, ipr, sizeof(ipr)); port = ntohs(sa_in6P->sin6_port); } mapped_v4_to_regular_v4(ipr); if (test->json_output) cJSON_AddItemToObject(test->json_start, "accepted_connection", iperf_json_printf("host: %s port: %d", ipr, (int64_t) port)); else iprintf(test, report_accepted, ipr, port); } if (test->json_output) { cJSON_AddStringToObject(test->json_start, "cookie", test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) cJSON_AddNumberToObject(test->json_start, "tcp_mss", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); cJSON_AddNumberToObject(test->json_start, "tcp_mss_default", opt); } } } else if (test->verbose) { iprintf(test, report_cookie, test->cookie); if (test->protocol->id == SOCK_STREAM) { if (test->settings->mss) iprintf(test, " TCP MSS: %d\n", test->settings->mss); else { len = sizeof(opt); getsockopt(test->ctrl_sck, IPPROTO_TCP, TCP_MAXSEG, &opt, &len); iprintf(test, " TCP MSS: %d (default)\n", opt); } } } }
167,315
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 MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1602 CWE ID: CWE-190
static MagickOffsetType TIFFSeekCustomStream(const MagickOffsetType offset, const int whence,void *user_data) { PhotoshopProfile *profile; profile=(PhotoshopProfile *) user_data; switch (whence) { case SEEK_SET: default: { if (offset < 0) return(-1); profile->offset=offset; break; } case SEEK_CUR: { if (((offset > 0) && (profile->offset > (SSIZE_MAX-offset))) || ((offset < 0) && (profile->offset < (-SSIZE_MAX-offset)))) { errno=EOVERFLOW; return(-1); } if ((profile->offset+offset) < 0) return(-1); profile->offset+=offset; break; } case SEEK_END: { if (((MagickOffsetType) profile->length+offset) < 0) return(-1); profile->offset=profile->length+offset; break; } } return(profile->offset); }
169,620
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 InspectorNetworkAgent::DidBlockRequest( ExecutionContext* execution_context, const ResourceRequest& request, DocumentLoader* loader, const FetchInitiatorInfo& initiator_info, ResourceRequestBlockedReason reason) { unsigned long identifier = CreateUniqueIdentifier(); WillSendRequestInternal(execution_context, identifier, loader, request, ResourceResponse(), initiator_info); String request_id = IdentifiersFactory::RequestId(identifier); String protocol_reason = BuildBlockedReason(reason); GetFrontend()->loadingFailed( request_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson( resources_data_->GetResourceType(request_id)), String(), false, protocol_reason); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void InspectorNetworkAgent::DidBlockRequest( ExecutionContext* execution_context, const ResourceRequest& request, DocumentLoader* loader, const FetchInitiatorInfo& initiator_info, ResourceRequestBlockedReason reason, Resource::Type resource_type) { unsigned long identifier = CreateUniqueIdentifier(); InspectorPageAgent::ResourceType type = InspectorPageAgent::ToResourceType(resource_type); WillSendRequestInternal(execution_context, identifier, loader, request, ResourceResponse(), initiator_info, type); String request_id = IdentifiersFactory::RequestId(identifier); String protocol_reason = BuildBlockedReason(reason); GetFrontend()->loadingFailed( request_id, MonotonicallyIncreasingTime(), InspectorPageAgent::ResourceTypeJson( resources_data_->GetResourceType(request_id)), String(), false, protocol_reason); }
172,465
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: PHP_FUNCTION(mcrypt_module_get_algo_block_size) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir)); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_get_algo_block_size) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir)); }
167,099
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 CrosLibrary::TestApi::SetBrightnessLibrary( BrightnessLibrary* library, bool own) { library_->brightness_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetBrightnessLibrary(
170,635
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: WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
WtsSessionProcessDelegate::Core::Core( scoped_refptr<base::SingleThreadTaskRunner> main_task_runner, scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, const FilePath& binary_path, bool launch_elevated, const std::string& channel_security) : main_task_runner_(main_task_runner), io_task_runner_(io_task_runner), binary_path_(binary_path), channel_security_(channel_security), get_named_pipe_client_pid_(NULL), launch_elevated_(launch_elevated), stopping_(false) { DCHECK(main_task_runner_->BelongsToCurrentThread()); }
171,555
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 ahci_uninit(AHCIState *s) { g_free(s->dev); } Commit Message: CWE ID: CWE-772
void ahci_uninit(AHCIState *s) { int i, j; for (i = 0; i < s->ports; i++) { AHCIDevice *ad = &s->dev[i]; for (j = 0; j < 2; j++) { IDEState *s = &ad->port.ifs[j]; ide_exit(s); } } g_free(s->dev); }
164,797
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: aspath_put (struct stream *s, struct aspath *as, int use32bit ) { struct assegment *seg = as->segments; size_t bytes = 0; if (!seg || seg->length == 0) return 0; if (seg) { /* * Hey, what do we do when we have > STREAM_WRITABLE(s) here? * At the moment, we would write out a partial aspath, and our peer * will complain and drop the session :-/ * * The general assumption here is that many things tested will * never happen. And, in real live, up to now, they have not. */ while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s))) { struct assegment *next = seg->next; int written = 0; int asns_packed = 0; size_t lenp; /* Overlength segments have to be split up */ while ( (seg->length - written) > AS_SEGMENT_MAX) { assegment_header_put (s, seg->type, AS_SEGMENT_MAX); assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit); written += AS_SEGMENT_MAX; bytes += ASSEGMENT_SIZE (written, use32bit); } /* write the final segment, probably is also the first */ lenp = assegment_header_put (s, seg->type, seg->length - written); assegment_data_put (s, (seg->as + written), seg->length - written, use32bit); /* Sequence-type segments can be 'packed' together * Case of a segment which was overlength and split up * will be missed here, but that doesn't matter. */ while (next && ASSEGMENTS_PACKABLE (seg, next)) { /* NB: We should never normally get here given we * normalise aspath data when parse them. However, better * safe than sorry. We potentially could call * assegment_normalise here instead, but it's cheaper and * easier to do it on the fly here rather than go through * the segment list twice every time we write out * aspath's. */ /* Next segment's data can fit in this one */ assegment_data_put (s, next->as, next->length, use32bit); /* update the length of the segment header */ stream_putc_at (s, lenp, seg->length - written + next->length); asns_packed += next->length; next = next->next; } bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, use32bit); seg = next; } } return bytes; } Commit Message: CWE ID: CWE-20
aspath_put (struct stream *s, struct aspath *as, int use32bit ) { struct assegment *seg = as->segments; size_t bytes = 0; if (!seg || seg->length == 0) return 0; if (seg) { /* * Hey, what do we do when we have > STREAM_WRITABLE(s) here? * At the moment, we would write out a partial aspath, and our peer * will complain and drop the session :-/ * * The general assumption here is that many things tested will * never happen. And, in real live, up to now, they have not. */ while (seg && (ASSEGMENT_LEN(seg, use32bit) <= STREAM_WRITEABLE(s))) { struct assegment *next = seg->next; int written = 0; int asns_packed = 0; size_t lenp; /* Overlength segments have to be split up */ while ( (seg->length - written) > AS_SEGMENT_MAX) { assegment_header_put (s, seg->type, AS_SEGMENT_MAX); assegment_data_put (s, seg->as, AS_SEGMENT_MAX, use32bit); written += AS_SEGMENT_MAX; bytes += ASSEGMENT_SIZE (AS_SEGMENT_MAX, use32bit); } /* write the final segment, probably is also the first */ lenp = assegment_header_put (s, seg->type, seg->length - written); assegment_data_put (s, (seg->as + written), seg->length - written, use32bit); /* Sequence-type segments can be 'packed' together * Case of a segment which was overlength and split up * will be missed here, but that doesn't matter. */ while (next && ASSEGMENTS_PACKABLE (seg, next)) { /* NB: We should never normally get here given we * normalise aspath data when parse them. However, better * safe than sorry. We potentially could call * assegment_normalise here instead, but it's cheaper and * easier to do it on the fly here rather than go through * the segment list twice every time we write out * aspath's. */ /* Next segment's data can fit in this one */ assegment_data_put (s, next->as, next->length, use32bit); /* update the length of the segment header */ stream_putc_at (s, lenp, seg->length - written + next->length); asns_packed += next->length; next = next->next; } bytes += ASSEGMENT_SIZE (seg->length - written + asns_packed, use32bit); seg = next; } } return bytes; }
164,639
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( Segment* pSegment, long long start, long long size_, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(start), m_size(size_), m_element_start(element_start), m_element_size(element_size), m_pMuxingAppAsUTF8(NULL), m_pWritingAppAsUTF8(NULL), 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,439
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 ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { u16 offset = sizeof(struct ipv6hdr); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset <= packet_len) { struct ipv6_opt_hdr *exthdr; switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } if (offset + sizeof(struct ipv6_opt_hdr) > packet_len) return -EINVAL; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); offset += ipv6_optlen(exthdr); *nexthdr = &exthdr->nexthdr; } return -EINVAL; } Commit Message: ipv6: avoid overflow of offset in ip6_find_1stfragopt In some cases, offset can overflow and can cause an infinite loop in ip6_find_1stfragopt(). Make it unsigned int to prevent the overflow, and cap it at IPV6_MAXPLEN, since packets larger than that should be invalid. This problem has been here since before the beginning of git history. Signed-off-by: Sabrina Dubroca <sd@queasysnail.net> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-190
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { unsigned int offset = sizeof(struct ipv6hdr); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset <= packet_len) { struct ipv6_opt_hdr *exthdr; unsigned int len; switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } if (offset + sizeof(struct ipv6_opt_hdr) > packet_len) return -EINVAL; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); len = ipv6_optlen(exthdr); if (len + offset >= IPV6_MAXPLEN) return -EINVAL; offset += len; *nexthdr = &exthdr->nexthdr; } return -EINVAL; }
168,260
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 net_get(int s, void *arg, int *len) { struct net_hdr nh; int plen; if (net_read_exact(s, &nh, sizeof(nh)) == -1) { return -1; } plen = ntohl(nh.nh_len); if (!(plen <= *len)) printf("PLEN %d type %d len %d\n", plen, nh.nh_type, *len); assert(plen <= *len); /* XXX */ *len = plen; if ((*len) && (net_read_exact(s, arg, *len) == -1)) { return -1; } return nh.nh_type; } Commit Message: OSdep: Fixed segmentation fault that happens with a malicious server sending a negative length (Closes #16 on GitHub). git-svn-id: http://svn.aircrack-ng.org/trunk@2419 28c6078b-6c39-48e3-add9-af49d547ecab CWE ID: CWE-20
int net_get(int s, void *arg, int *len) { struct net_hdr nh; int plen; if (net_read_exact(s, &nh, sizeof(nh)) == -1) { return -1; } plen = ntohl(nh.nh_len); if (!(plen <= *len)) printf("PLEN %d type %d len %d\n", plen, nh.nh_type, *len); assert(plen <= *len && plen > 0); /* XXX */ *len = plen; if ((*len) && (net_read_exact(s, arg, *len) == -1)) { return -1; } return nh.nh_type; }
168,912
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 ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case V_ASN1_OBJECT: result = OBJ_cmp(a->value.object, b->value.object); break; case V_ASN1_BOOLEAN: result = a->value.boolean - b->value.boolean; break; case V_ASN1_NULL: result = 0; /* They do not have content. */ break; case V_ASN1_INTEGER: case V_ASN1_NEG_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_NEG_ENUMERATED: case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr, (ASN1_STRING *)b->value.ptr); break; } return result; } Commit Message: CWE ID: CWE-119
int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) { int result = -1; if (!a || !b || a->type != b->type) return -1; switch (a->type) { case V_ASN1_OBJECT: result = OBJ_cmp(a->value.object, b->value.object); break; case V_ASN1_BOOLEAN: result = a->value.boolean - b->value.boolean; break; case V_ASN1_NULL: result = 0; /* They do not have content. */ break; case V_ASN1_INTEGER: case V_ASN1_ENUMERATED: case V_ASN1_BIT_STRING: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_OCTET_STRING: case V_ASN1_SEQUENCE: case V_ASN1_SET: case V_ASN1_NUMERICSTRING: case V_ASN1_PRINTABLESTRING: case V_ASN1_T61STRING: case V_ASN1_VIDEOTEXSTRING: case V_ASN1_IA5STRING: case V_ASN1_UTCTIME: case V_ASN1_GENERALIZEDTIME: case V_ASN1_GRAPHICSTRING: case V_ASN1_VISIBLESTRING: case V_ASN1_GENERALSTRING: case V_ASN1_UNIVERSALSTRING: case V_ASN1_BMPSTRING: case V_ASN1_UTF8STRING: case V_ASN1_OTHER: default: result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr, (ASN1_STRING *)b->value.ptr); break; } return result; }
165,211
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 peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, "Invalid state %d\n", rdp->state); return -1; } return 0; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
static int peer_recv_callback(rdpTransport* transport, wStream* s, void* extra) { freerdp_peer* client = (freerdp_peer*) extra; rdpRdp* rdp = client->context->rdp; switch (rdp->state) { case CONNECTION_STATE_INITIAL: if (!rdp_server_accept_nego(rdp, s)) return -1; if (rdp->nego->selected_protocol & PROTOCOL_NLA) { sspi_CopyAuthIdentity(&client->identity, &(rdp->nego->transport->credssp->identity)); IFCALLRET(client->Logon, client->authenticated, client, &client->identity, TRUE); credssp_free(rdp->nego->transport->credssp); rdp->nego->transport->credssp = NULL; } else { IFCALLRET(client->Logon, client->authenticated, client, &client->identity, FALSE); } break; case CONNECTION_STATE_NEGO: if (!rdp_server_accept_mcs_connect_initial(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CONNECT: if (!rdp_server_accept_mcs_erect_domain_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ERECT_DOMAIN: if (!rdp_server_accept_mcs_attach_user_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_ATTACH_USER: if (!rdp_server_accept_mcs_channel_join_request(rdp, s)) return -1; break; case CONNECTION_STATE_MCS_CHANNEL_JOIN: if (rdp->settings->DisableEncryption) { if (!rdp_server_accept_client_keys(rdp, s)) return -1; break; } rdp->state = CONNECTION_STATE_ESTABLISH_KEYS; /* FALLTHROUGH */ case CONNECTION_STATE_ESTABLISH_KEYS: if (!rdp_server_accept_client_info(rdp, s)) return -1; IFCALL(client->Capabilities, client); if (!rdp_send_demand_active(rdp)) return -1; break; case CONNECTION_STATE_LICENSE: if (!rdp_server_accept_confirm_active(rdp, s)) { /** * During reactivation sequence the client might sent some input or channel data * before receiving the Deactivate All PDU. We need to process them as usual. */ Stream_SetPosition(s, 0); return peer_recv_pdu(client, s); } break; case CONNECTION_STATE_ACTIVE: if (peer_recv_pdu(client, s) < 0) return -1; break; default: fprintf(stderr, "Invalid state %d\n", rdp->state); return -1; } return 0; }
167,600
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(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); }
167,034
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 kvm_ioctl_create_device(struct kvm *kvm, struct kvm_create_device *cd) { struct kvm_device_ops *ops = NULL; struct kvm_device *dev; bool test = cd->flags & KVM_CREATE_DEVICE_TEST; int ret; if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) return -ENODEV; ops = kvm_device_ops_table[cd->type]; if (ops == NULL) return -ENODEV; if (test) return 0; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ops = ops; dev->kvm = kvm; mutex_lock(&kvm->lock); ret = ops->create(dev, cd->type); if (ret < 0) { mutex_unlock(&kvm->lock); kfree(dev); return ret; } list_add(&dev->vm_node, &kvm->devices); mutex_unlock(&kvm->lock); if (ops->init) ops->init(dev); ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); if (ret < 0) { ops->destroy(dev); mutex_lock(&kvm->lock); list_del(&dev->vm_node); mutex_unlock(&kvm->lock); return ret; } kvm_get_kvm(kvm); cd->fd = ret; return 0; } Commit Message: KVM: use after free in kvm_ioctl_create_device() We should move the ops->destroy(dev) after the list_del(&dev->vm_node) so that we don't use "dev" after freeing it. Fixes: a28ebea2adc4 ("KVM: Protect device ops->create and list_add with kvm->lock") Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Reviewed-by: David Hildenbrand <david@redhat.com> Signed-off-by: Radim Krčmář <rkrcmar@redhat.com> CWE ID: CWE-416
static int kvm_ioctl_create_device(struct kvm *kvm, struct kvm_create_device *cd) { struct kvm_device_ops *ops = NULL; struct kvm_device *dev; bool test = cd->flags & KVM_CREATE_DEVICE_TEST; int ret; if (cd->type >= ARRAY_SIZE(kvm_device_ops_table)) return -ENODEV; ops = kvm_device_ops_table[cd->type]; if (ops == NULL) return -ENODEV; if (test) return 0; dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) return -ENOMEM; dev->ops = ops; dev->kvm = kvm; mutex_lock(&kvm->lock); ret = ops->create(dev, cd->type); if (ret < 0) { mutex_unlock(&kvm->lock); kfree(dev); return ret; } list_add(&dev->vm_node, &kvm->devices); mutex_unlock(&kvm->lock); if (ops->init) ops->init(dev); ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC); if (ret < 0) { mutex_lock(&kvm->lock); list_del(&dev->vm_node); mutex_unlock(&kvm->lock); ops->destroy(dev); return ret; } kvm_get_kvm(kvm); cd->fd = ret; return 0; }
168,519
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 ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData()) return; dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } } Commit Message: [Fix] STP: Possible out-of-bounds memory read with malformed STP files (caught with afl-fuzz). git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@9567 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-125
static void ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData() || start >= src.nLength || src.nLength - start < len) { return; } dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } }
169,338
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: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; } Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team) git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-120
LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; char buf[32]; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); memset(buf,0,32); if(str){ strncpy(buf,str,31); openmpt_free_string(str); } if(buff){ strncpy(buff,buf,32); } return (unsigned int)strlen(buf); }
169,500
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::suspend(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, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true); return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::suspend(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, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_SUSPEND_JOBS,true); return true; }
164,836
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: media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() { if (!media_service_factory_) { mojo::InterfacePtr<mojo::Shell> shell_ptr; GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr)); mojo::ServiceProviderPtr service_provider; mojo::URLRequestPtr request(mojo::URLRequest::New()); request->url = mojo::String::From("mojo:media"); shell_ptr->ConnectToApplication(request.Pass(), GetProxy(&service_provider), nullptr, nullptr); mojo::ConnectToService(service_provider.get(), &media_service_factory_); media_service_factory_.set_connection_error_handler( base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError, base::Unretained(this))); } return media_service_factory_.get(); } Commit Message: Connect WebUSB client interface to the devices app This provides a basic WebUSB client interface in content/renderer. Most of the interface is unimplemented, but this CL hooks up navigator.usb.getDevices() to the browser's Mojo devices app to enumerate available USB devices. BUG=492204 Review URL: https://codereview.chromium.org/1293253002 Cr-Commit-Position: refs/heads/master@{#344881} CWE ID: CWE-399
media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() { if (!media_service_factory_) { mojo::ServiceProviderPtr service_provider = ConnectToApplication(GURL("mojo:media")); mojo::ConnectToService(service_provider.get(), &media_service_factory_); media_service_factory_.set_connection_error_handler( base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError, base::Unretained(this))); } return media_service_factory_.get(); }
171,696
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 DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { if (!g_teredo_enabled) return TM_ECODE_FAILED; uint8_t *start = pkt; /* Is this packet to short to contain an IPv6 packet ? */ if (len < IPV6_HEADER_LEN) return TM_ECODE_FAILED; /* Teredo encapsulate IPv6 in UDP and can add some custom message * part before the IPv6 packet. In our case, we just want to get * over an ORIGIN indication. So we just make one offset if needed. */ if (start[0] == 0x0) { switch (start[1]) { /* origin indication: compatible with tunnel */ case 0x0: /* offset is coherent with len and presence of an IPv6 header */ if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN) start += TEREDO_ORIG_INDICATION_LENGTH; else return TM_ECODE_FAILED; break; /* authentication: negotiation not real tunnel */ case 0x1: return TM_ECODE_FAILED; /* this case is not possible in Teredo: not that protocol */ default: return TM_ECODE_FAILED; } } /* There is no specific field that we can check to prove that the packet * is a Teredo packet. We've zapped here all the possible Teredo header * and we should have an IPv6 packet at the start pointer. * We then can only do two checks before sending the encapsulated packets * to decoding: * - The packet has a protocol version which is IPv6. * - The IPv6 length of the packet matches what remains in buffer. */ if (IP_GET_RAW_VER(start) == 6) { IPV6Hdr *thdr = (IPV6Hdr *)start; if (len == IPV6_HEADER_LEN + IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) { if (pq != NULL) { int blen = len - (start - pkt); /* spawn off tunnel packet */ Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen, DECODE_TUNNEL_IPV6, pq); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO); /* add the tp to the packet queue. */ PacketEnqueue(pq,tp); StatsIncr(tv, dtv->counter_teredo); return TM_ECODE_OK; } } } return TM_ECODE_FAILED; } return TM_ECODE_FAILED; } Commit Message: teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736. CWE ID: CWE-20
int DecodeTeredo(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, uint8_t *pkt, uint16_t len, PacketQueue *pq) { if (!g_teredo_enabled) return TM_ECODE_FAILED; uint8_t *start = pkt; /* Is this packet to short to contain an IPv6 packet ? */ if (len < IPV6_HEADER_LEN) return TM_ECODE_FAILED; /* Teredo encapsulate IPv6 in UDP and can add some custom message * part before the IPv6 packet. In our case, we just want to get * over an ORIGIN indication. So we just make one offset if needed. */ if (start[0] == 0x0) { switch (start[1]) { /* origin indication: compatible with tunnel */ case 0x0: /* offset is coherent with len and presence of an IPv6 header */ if (len >= TEREDO_ORIG_INDICATION_LENGTH + IPV6_HEADER_LEN) start += TEREDO_ORIG_INDICATION_LENGTH; else return TM_ECODE_FAILED; break; /* authentication: negotiation not real tunnel */ case 0x1: return TM_ECODE_FAILED; /* this case is not possible in Teredo: not that protocol */ default: return TM_ECODE_FAILED; } } /* There is no specific field that we can check to prove that the packet * is a Teredo packet. We've zapped here all the possible Teredo header * and we should have an IPv6 packet at the start pointer. * We then can only do a few checks before sending the encapsulated packets * to decoding: * - The packet has a protocol version which is IPv6. * - The IPv6 length of the packet matches what remains in buffer. * - HLIM is 0. This would technically be valid, but still weird. * - NH 0 (HOP) and not enough data. * * If all these conditions are met, the tunnel decoder will be called. * If the packet gets an invalid event set, it will still be rejected. */ if (IP_GET_RAW_VER(start) == 6) { IPV6Hdr *thdr = (IPV6Hdr *)start; /* ignore hoplimit 0 packets, most likely an artifact of bad detection */ if (IPV6_GET_RAW_HLIM(thdr) == 0) return TM_ECODE_FAILED; /* if nh is 0 (HOP) with little data we have a bogus packet */ if (IPV6_GET_RAW_NH(thdr) == 0 && IPV6_GET_RAW_PLEN(thdr) < 8) return TM_ECODE_FAILED; if (len == IPV6_HEADER_LEN + IPV6_GET_RAW_PLEN(thdr) + (start - pkt)) { if (pq != NULL) { int blen = len - (start - pkt); /* spawn off tunnel packet */ Packet *tp = PacketTunnelPktSetup(tv, dtv, p, start, blen, DECODE_TUNNEL_IPV6_TEREDO, pq); if (tp != NULL) { PKT_SET_SRC(tp, PKT_SRC_DECODER_TEREDO); /* add the tp to the packet queue. */ PacketEnqueue(pq,tp); StatsIncr(tv, dtv->counter_teredo); return TM_ECODE_OK; } } } return TM_ECODE_FAILED; } return TM_ECODE_FAILED; }
169,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: my_object_stringify (MyObject *obj, GValue *value, char **ret, GError **error) { GValue valstr = {0, }; g_value_init (&valstr, G_TYPE_STRING); if (!g_value_transform (value, &valstr)) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "couldn't transform value"); return FALSE; } *ret = g_value_dup_string (&valstr); g_value_unset (&valstr); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_stringify (MyObject *obj, GValue *value, char **ret, GError **error)
165,122
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 klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc < 0) dev_err(&port->dev, "Reading line status failed (error = %d)\n", rc); else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; } Commit Message: USB: serial: kl5kusb105: fix line-state error handling The current implementation failed to detect short transfers when attempting to read the line state, and also, to make things worse, logged the content of the uninitialised heap transfer buffer. Fixes: abf492e7b3ae ("USB: kl5kusb105: fix DMA buffers on stack") Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <stable@vger.kernel.org> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Signed-off-by: Johan Hovold <johan@kernel.org> CWE ID: CWE-532
static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc != KLSI_STATUSBUF_LEN) { dev_err(&port->dev, "reading line status failed: %d\n", rc); if (rc >= 0) rc = -EIO; } else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; }
168,389
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 preproc_mount_mnt_dir(void) { if (!tmpfs_mounted) { if (arg_debug) printf("Mounting tmpfs on %s directory\n", RUN_MNT_DIR); if (mount("tmpfs", RUN_MNT_DIR, "tmpfs", MS_NOSUID | MS_STRICTATIME, "mode=755,gid=0") < 0) errExit("mounting /run/firejail/mnt"); tmpfs_mounted = 1; fs_logger2("tmpfs", RUN_MNT_DIR); #ifdef HAVE_SECCOMP if (arg_seccomp_block_secondary) copy_file(PATH_SECCOMP_BLOCK_SECONDARY, RUN_SECCOMP_BLOCK_SECONDARY, getuid(), getgid(), 0644); // root needed else { copy_file(PATH_SECCOMP_32, RUN_SECCOMP_32, getuid(), getgid(), 0644); // root needed } if (arg_allow_debuggers) copy_file(PATH_SECCOMP_DEFAULT_DEBUG, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed else copy_file(PATH_SECCOMP_DEFAULT, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed if (arg_memory_deny_write_execute) copy_file(PATH_SECCOMP_MDWX, RUN_SECCOMP_MDWX, getuid(), getgid(), 0644); // root needed create_empty_file_as_root(RUN_SECCOMP_PROTOCOL, 0644); if (set_perms(RUN_SECCOMP_PROTOCOL, getuid(), getgid(), 0644)) errExit("set_perms"); create_empty_file_as_root(RUN_SECCOMP_POSTEXEC, 0644); if (set_perms(RUN_SECCOMP_POSTEXEC, getuid(), getgid(), 0644)) errExit("set_perms"); #endif } } Commit Message: mount runtime seccomp files read-only (#2602) avoid creating locations in the file system that are both writable and executable (in this case for processes with euid of the user). for the same reason also remove user owned libfiles when it is not needed any more CWE ID: CWE-284
void preproc_mount_mnt_dir(void) { if (!tmpfs_mounted) { if (arg_debug) printf("Mounting tmpfs on %s directory\n", RUN_MNT_DIR); if (mount("tmpfs", RUN_MNT_DIR, "tmpfs", MS_NOSUID | MS_STRICTATIME, "mode=755,gid=0") < 0) errExit("mounting /run/firejail/mnt"); tmpfs_mounted = 1; fs_logger2("tmpfs", RUN_MNT_DIR); #ifdef HAVE_SECCOMP create_empty_dir_as_root(RUN_SECCOMP_DIR, 0755); if (arg_seccomp_block_secondary) copy_file(PATH_SECCOMP_BLOCK_SECONDARY, RUN_SECCOMP_BLOCK_SECONDARY, getuid(), getgid(), 0644); // root needed else { copy_file(PATH_SECCOMP_32, RUN_SECCOMP_32, getuid(), getgid(), 0644); // root needed } if (arg_allow_debuggers) copy_file(PATH_SECCOMP_DEFAULT_DEBUG, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed else copy_file(PATH_SECCOMP_DEFAULT, RUN_SECCOMP_CFG, getuid(), getgid(), 0644); // root needed if (arg_memory_deny_write_execute) copy_file(PATH_SECCOMP_MDWX, RUN_SECCOMP_MDWX, getuid(), getgid(), 0644); // root needed create_empty_file_as_root(RUN_SECCOMP_PROTOCOL, 0644); if (set_perms(RUN_SECCOMP_PROTOCOL, getuid(), getgid(), 0644)) errExit("set_perms"); create_empty_file_as_root(RUN_SECCOMP_POSTEXEC, 0644); if (set_perms(RUN_SECCOMP_POSTEXEC, getuid(), getgid(), 0644)) errExit("set_perms"); #endif } }
169,658
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 RenderFrameHostImpl::OnDidAddMessageToConsole( int32_t level, const base::string16& message, int32_t line_no, const base::string16& source_id) { if (level < logging::LOG_VERBOSE || level > logging::LOG_FATAL) { bad_message::ReceivedBadMessage( GetProcess(), bad_message::RFH_DID_ADD_CONSOLE_MESSAGE_BAD_SEVERITY); return; } if (delegate_->DidAddMessageToConsole(level, message, line_no, source_id)) return; const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(level, message, line_no, is_builtin_component, is_off_the_record, source_id); } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <lowell@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
void RenderFrameHostImpl::OnDidAddMessageToConsole( void RenderFrameHostImpl::DidAddMessageToConsole( blink::mojom::ConsoleMessageLevel log_level, const base::string16& message, int32_t line_no, const base::string16& source_id) { // TODO(https://crbug.com/786836): Update downstream code to use // ConsoleMessageLevel everywhere to avoid this conversion. logging::LogSeverity log_severity = logging::LOG_VERBOSE; switch (log_level) { case blink::mojom::ConsoleMessageLevel::kVerbose: log_severity = logging::LOG_VERBOSE; break; case blink::mojom::ConsoleMessageLevel::kInfo: log_severity = logging::LOG_INFO; break; case blink::mojom::ConsoleMessageLevel::kWarning: log_severity = logging::LOG_WARNING; break; case blink::mojom::ConsoleMessageLevel::kError: log_severity = logging::LOG_ERROR; break; } if (delegate_->DidAddMessageToConsole(log_severity, message, line_no, source_id)) { return; } // Pass through log severity only on builtin components pages to limit console const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(log_severity, message, line_no, is_builtin_component, is_off_the_record, source_id); }
172,485
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 find_low_bit(unsigned int x) { int i; for(i=0;i<=31;i++) { if(x&(1<<i)) return i; } return 0; } Commit Message: Trying to fix some invalid left shift operations Fixes issue #16 CWE ID: CWE-682
static int find_low_bit(unsigned int x) { int i; for(i=0;i<=31;i++) { if(x&(1U<<(unsigned int)i)) return i; } return 0; }
168,195
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: IceGenerateMagicCookie ( int len ) { char *auth; #ifndef HAVE_ARC4RANDOM_BUF long ldata[2]; int seed; int value; int i; #endif if ((auth = malloc (len + 1)) == NULL) return (NULL); #ifdef HAVE_ARC4RANDOM_BUF arc4random_buf(auth, len); #else #ifdef ITIMER_REAL { struct timeval now; int i; ldata[0] = now.tv_sec; ldata[1] = now.tv_usec; } #else { long time (); ldata[0] = time ((long *) 0); ldata[1] = getpid (); } #endif seed = (ldata[0]) + (ldata[1] << 16); srand (seed); for (i = 0; i < len; i++) ldata[1] = now.tv_usec; value = rand (); auth[i] = value & 0xff; } Commit Message: CWE ID: CWE-331
IceGenerateMagicCookie ( static void emulate_getrandom_buf ( char *auth, int len ) { long ldata[2]; int seed; int value; int i; #ifdef ITIMER_REAL { struct timeval now; int i; ldata[0] = now.tv_sec; ldata[1] = now.tv_usec; } #else /* ITIMER_REAL */ { long time (); ldata[0] = time ((long *) 0); ldata[1] = getpid (); } #endif /* ITIMER_REAL */ seed = (ldata[0]) + (ldata[1] << 16); srand (seed); for (i = 0; i < len; i++) ldata[1] = now.tv_usec; value = rand (); auth[i] = value & 0xff; }
165,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: void PepperRendererConnection::OnMsgDidCreateInProcessInstance( PP_Instance instance, const PepperRendererInstanceData& instance_data) { PepperRendererInstanceData data = instance_data; data.render_process_id = render_process_id_; in_process_host_->AddInstance(instance, data); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <bbudge@chromium.org> Reviewed-by: Raymes Khoury <raymes@chromium.org> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void PepperRendererConnection::OnMsgDidCreateInProcessInstance( PP_Instance instance, const PepperRendererInstanceData& instance_data) { PepperRendererInstanceData data = instance_data; // It's important that we supply the render process ID ourselves since the // message may be coming from a compromised renderer. data.render_process_id = render_process_id_; // 'instance' is possibly invalid. The host must be careful not to trust it. in_process_host_->AddInstance(instance, data); }
172,311
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 yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = yr_max(64, (index + 1) * 2); array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; } Commit Message: Fix heap overflow (reported by Jurriaan Bremer) When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. CWE ID: CWE-119
int yr_object_array_set_item( YR_OBJECT* object, YR_OBJECT* item, int index) { YR_OBJECT_ARRAY* array; int i; int count; assert(index >= 0); assert(object->type == OBJECT_TYPE_ARRAY); array = object_as_array(object); if (array->items == NULL) { count = 64; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_malloc( sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; memset(array->items->objects, 0, count * sizeof(YR_OBJECT*)); array->items->count = count; } else if (index >= array->items->count) { count = array->items->count * 2; while (count <= index) count *= 2; array->items = (YR_ARRAY_ITEMS*) yr_realloc( array->items, sizeof(YR_ARRAY_ITEMS) + count * sizeof(YR_OBJECT*)); if (array->items == NULL) return ERROR_INSUFFICIENT_MEMORY; for (i = array->items->count; i < count; i++) array->items->objects[i] = NULL; array->items->count = count; } item->parent = object; array->items->objects[index] = item; return ERROR_SUCCESS; }
168,045
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 vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data, unsigned int data_sz, vpx_codec_stream_info_t *si, int *is_intra_only, vpx_decrypt_cb decrypt_cb, void *decrypt_state) { int intra_only_flag = 0; uint8_t clear_buffer[9]; if (data + data_sz <= data) return VPX_CODEC_INVALID_PARAM; si->is_kf = 0; si->w = si->h = 0; if (decrypt_cb) { data_sz = VPXMIN(sizeof(clear_buffer), data_sz); decrypt_cb(decrypt_state, data, clear_buffer, data_sz); data = clear_buffer; } { int show_frame; int error_resilient; struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL }; const int frame_marker = vpx_rb_read_literal(&rb, 2); const BITSTREAM_PROFILE profile = vp9_read_profile(&rb); if (frame_marker != VP9_FRAME_MARKER) return VPX_CODEC_UNSUP_BITSTREAM; if (profile >= MAX_PROFILES) return VPX_CODEC_UNSUP_BITSTREAM; if ((profile >= 2 && data_sz <= 1) || data_sz < 1) return VPX_CODEC_UNSUP_BITSTREAM; if (vpx_rb_read_bit(&rb)) { // show an existing frame vpx_rb_read_literal(&rb, 3); // Frame buffer to show. return VPX_CODEC_OK; } if (data_sz <= 8) return VPX_CODEC_UNSUP_BITSTREAM; si->is_kf = !vpx_rb_read_bit(&rb); show_frame = vpx_rb_read_bit(&rb); error_resilient = vpx_rb_read_bit(&rb); if (si->is_kf) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } else { intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb); rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context if (intra_only_flag) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (profile > PROFILE_0) { if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; } rb.bit_offset += REF_FRAMES; // refresh_frame_flags vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } } } if (is_intra_only != NULL) *is_intra_only = intra_only_flag; return VPX_CODEC_OK; } Commit Message: DO NOT MERGE | libvpx: cherry-pick aa1c813 from upstream Description from upstream: vp9: Fix potential SEGV in decoder_peek_si_internal decoder_peek_si_internal could potentially read more bytes than what actually exists in the input buffer. We check for the buffer size to be at least 8, but we try to read up to 10 bytes in the worst case. A well crafted file could thus cause a segfault. Likely change that introduced this bug was: https://chromium-review.googlesource.com/#/c/70439 (git hash: 7c43fb6) Bug: 30013856 Change-Id: If556414cb5b82472d5673e045bc185cc57bb9af3 (cherry picked from commit bd57d587c2eb743c61b049add18f9fd72bf78c33) CWE ID: CWE-119
static vpx_codec_err_t decoder_peek_si_internal(const uint8_t *data, unsigned int data_sz, vpx_codec_stream_info_t *si, int *is_intra_only, vpx_decrypt_cb decrypt_cb, void *decrypt_state) { int intra_only_flag = 0; uint8_t clear_buffer[10]; if (data + data_sz <= data) return VPX_CODEC_INVALID_PARAM; si->is_kf = 0; si->w = si->h = 0; if (decrypt_cb) { data_sz = VPXMIN(sizeof(clear_buffer), data_sz); decrypt_cb(decrypt_state, data, clear_buffer, data_sz); data = clear_buffer; } // A maximum of 6 bits are needed to read the frame marker, profile and // show_existing_frame. if (data_sz < 1) return VPX_CODEC_UNSUP_BITSTREAM; { int show_frame; int error_resilient; struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL }; const int frame_marker = vpx_rb_read_literal(&rb, 2); const BITSTREAM_PROFILE profile = vp9_read_profile(&rb); if (frame_marker != VP9_FRAME_MARKER) return VPX_CODEC_UNSUP_BITSTREAM; if (profile >= MAX_PROFILES) return VPX_CODEC_UNSUP_BITSTREAM; if (vpx_rb_read_bit(&rb)) { // show an existing frame // If profile is > 2 and show_existing_frame is true, then at least 1 more // byte (6+3=9 bits) is needed. if (profile > 2 && data_sz < 2) return VPX_CODEC_UNSUP_BITSTREAM; vpx_rb_read_literal(&rb, 3); // Frame buffer to show. return VPX_CODEC_OK; } // For the rest of the function, a maximum of 9 more bytes are needed // (computed by taking the maximum possible bits needed in each case). Note // that this has to be updated if we read any more bits in this function. if (data_sz < 10) return VPX_CODEC_UNSUP_BITSTREAM; si->is_kf = !vpx_rb_read_bit(&rb); show_frame = vpx_rb_read_bit(&rb); error_resilient = vpx_rb_read_bit(&rb); if (si->is_kf) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } else { intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb); rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context if (intra_only_flag) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (profile > PROFILE_0) { if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; } rb.bit_offset += REF_FRAMES; // refresh_frame_flags vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } } } if (is_intra_only != NULL) *is_intra_only = intra_only_flag; return VPX_CODEC_OK; }
173,409
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 CrosLibrary::TestApi::SetMountLibrary( MountLibrary* library, bool own) { library_->mount_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetMountLibrary(
170,641
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 f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range) { __u64 start = F2FS_BYTES_TO_BLK(range->start); __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1; unsigned int start_segno, end_segno; struct cp_control cpc; int err = 0; if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize) return -EINVAL; cpc.trimmed = 0; if (end <= MAIN_BLKADDR(sbi)) goto out; if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) { f2fs_msg(sbi->sb, KERN_WARNING, "Found FS corruption, run fsck to fix."); goto out; } /* start/end segment number in main_area */ start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start); end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 : GET_SEGNO(sbi, end); cpc.reason = CP_DISCARD; cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen)); /* do checkpoint to issue discard commands safely */ for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) { cpc.trim_start = start_segno; if (sbi->discard_blks == 0) break; else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi)) cpc.trim_end = end_segno; else cpc.trim_end = min_t(unsigned int, rounddown(start_segno + BATCHED_TRIM_SEGMENTS(sbi), sbi->segs_per_sec) - 1, end_segno); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); if (err) break; schedule(); } /* It's time to issue all the filed discards */ mark_discard_range_all(sbi); f2fs_wait_discard_bios(sbi); out: range->len = F2FS_BLK_TO_BYTES(cpc.trimmed); return err; } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <qkrwngud825@gmail.com> Signed-off-by: Chao Yu <yuchao0@huawei.com> Signed-off-by: Jaegeuk Kim <jaegeuk@kernel.org> CWE ID: CWE-20
int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range) { __u64 start = F2FS_BYTES_TO_BLK(range->start); __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1; unsigned int start_segno, end_segno; struct cp_control cpc; int err = 0; if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize) return -EINVAL; cpc.trimmed = 0; if (end <= MAIN_BLKADDR(sbi)) goto out; if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) { f2fs_msg(sbi->sb, KERN_WARNING, "Found FS corruption, run fsck to fix."); goto out; } /* start/end segment number in main_area */ start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start); end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 : GET_SEGNO(sbi, end); cpc.reason = CP_DISCARD; cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen)); /* do checkpoint to issue discard commands safely */ for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) { cpc.trim_start = start_segno; if (sbi->discard_blks == 0) break; else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi)) cpc.trim_end = end_segno; else cpc.trim_end = min_t(unsigned int, rounddown(start_segno + BATCHED_TRIM_SEGMENTS(sbi), sbi->segs_per_sec) - 1, end_segno); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); if (err) break; schedule(); } /* It's time to issue all the filed discards */ mark_discard_range_all(sbi); f2fs_wait_discard_bios(sbi, false); out: range->len = F2FS_BLK_TO_BYTES(cpc.trimmed); return err; }
169,413
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 FlushImeConfig() { if (!initialized_successfully_) return; bool active_input_methods_are_changed = false; InputMethodConfigRequests::iterator iter = pending_config_requests_.begin(); while (iter != pending_config_requests_.end()) { const std::string& section = iter->first.first; const std::string& config_name = iter->first.second; ImeConfigValue& value = iter->second; if (config_name == language_prefs::kPreloadEnginesConfigName && !tentative_current_input_method_id_.empty()) { std::vector<std::string>::iterator engine_iter = std::find( value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_); if (engine_iter != value.string_list_value.end()) { std::rotate(value.string_list_value.begin(), engine_iter, // this becomes the new first element value.string_list_value.end()); } else { LOG(WARNING) << tentative_current_input_method_id_ << " is not in preload_engines: " << value.ToString(); } tentative_current_input_method_id_.erase(); } if (chromeos::SetImeConfig(input_method_status_connection_, section.c_str(), config_name.c_str(), value)) { if (config_name == language_prefs::kPreloadEnginesConfigName) { active_input_methods_are_changed = true; VLOG(1) << "Updated preload_engines: " << value.ToString(); } pending_config_requests_.erase(iter++); } else { break; } } if (active_input_methods_are_changed) { const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(Observer, observers_, ActiveInputMethodsChanged(this, current_input_method_, num_active_input_methods)); } } 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 FlushImeConfig() { if (!initialized_successfully_) return; bool active_input_methods_are_changed = false; InputMethodConfigRequests::iterator iter = pending_config_requests_.begin(); while (iter != pending_config_requests_.end()) { const std::string& section = iter->first.first; const std::string& config_name = iter->first.second; input_method::ImeConfigValue& value = iter->second; if (config_name == language_prefs::kPreloadEnginesConfigName && !tentative_current_input_method_id_.empty()) { std::vector<std::string>::iterator engine_iter = std::find( value.string_list_value.begin(), value.string_list_value.end(), tentative_current_input_method_id_); if (engine_iter != value.string_list_value.end()) { std::rotate(value.string_list_value.begin(), engine_iter, // this becomes the new first element value.string_list_value.end()); } else { LOG(WARNING) << tentative_current_input_method_id_ << " is not in preload_engines: " << value.ToString(); } tentative_current_input_method_id_.erase(); } if (ibus_controller_->SetImeConfig(section, config_name, value)) { if (config_name == language_prefs::kPreloadEnginesConfigName) { active_input_methods_are_changed = true; VLOG(1) << "Updated preload_engines: " << value.ToString(); } pending_config_requests_.erase(iter++); } else { break; } } if (active_input_methods_are_changed) { const size_t num_active_input_methods = GetNumActiveInputMethods(); FOR_EACH_OBSERVER(InputMethodLibrary::Observer, observers_, ActiveInputMethodsChanged(this, current_input_method_, num_active_input_methods)); } }
170,485
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 bool Speak( const std::string& utterance, const std::string& language, const std::string& gender, double rate, double pitch, double volume) { error_ = kNotSupportedError; return false; } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
virtual bool Speak( int utterance_id, const std::string& utterance, const std::string& lang, const UtteranceContinuousParameters& params) { error_ = kNotSupportedError; return false; }
170,400
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 a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length) { int ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL); if (ret < 0) { ERROR("ack failed (%s)", strerror(errno)); if (errno == EINTR) { /* retry again */ ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL); if (ret < 0) { ERROR("ack failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } } else { skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } } return ret; } 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 int a2dp_ctrl_receive(struct a2dp_stream_common *common, void* buffer, int length) { int ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL)); if (ret < 0) { ERROR("ack failed (%s)", strerror(errno)); if (errno == EINTR) { /* retry again */ ret = TEMP_FAILURE_RETRY(recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL)); if (ret < 0) { ERROR("ack failed (%s)", strerror(errno)); skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } } else { skt_disconnect(common->ctrl_fd); common->ctrl_fd = AUDIO_SKT_DISCONNECTED; return -1; } } return ret; }
173,423
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 ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr, pmd_t *pmd, unsigned int flags) { int result; handle_t *handle = NULL; struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; bool write = flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, ext4_chunk_trans_blocks(inode, PMD_SIZE / PAGE_SIZE)); } if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_pmd_fault(vma, addr, pmd, flags, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); sb_end_pagefault(sb); } return result; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-362
static int ext4_dax_pmd_fault(struct vm_area_struct *vma, unsigned long addr, pmd_t *pmd, unsigned int flags) { int result; handle_t *handle = NULL; struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; bool write = flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, ext4_chunk_trans_blocks(inode, PMD_SIZE / PAGE_SIZE)); } else down_read(&EXT4_I(inode)->i_mmap_sem); if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_pmd_fault(vma, addr, pmd, flags, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(sb); } else up_read(&EXT4_I(inode)->i_mmap_sem); return result; }
167,488
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 iov_fault_in_pages_read(struct iovec *iov, unsigned long len) { while (!iov->iov_len) iov++; while (len > 0) { unsigned long this_len; this_len = min_t(unsigned long, len, iov->iov_len); fault_in_pages_readable(iov->iov_base, this_len); len -= this_len; iov++; } } Commit Message: new helper: copy_page_from_iter() parallel to copy_page_to_iter(). pipe_write() switched to it (and became ->write_iter()). Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-17
static void iov_fault_in_pages_read(struct iovec *iov, unsigned long len)
166,685
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 r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) { int i; ut8 *directory_base; struct minidump_directory *entry; directory_base = obj->b->buf + obj->hdr->stream_directory_rva; sdb_num_set (obj->kv, "mdmp_directory.offset", obj->hdr->stream_directory_rva, 0); sdb_set (obj->kv, "mdmp_directory.format", "[4]E? " "(mdmp_stream_type)StreamType " "(mdmp_location_descriptor)Location", 0); /* Parse each entry in the directory */ for (i = 0; i < (int)obj->hdr->number_of_streams; i++) { entry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory))); r_bin_mdmp_init_directory_entry (obj, entry); } return true; } Commit Message: Fix #10464 - oobread crash in mdmp CWE ID: CWE-125
static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) { int i; struct minidump_directory entry; sdb_num_set (obj->kv, "mdmp_directory.offset", obj->hdr->stream_directory_rva, 0); sdb_set (obj->kv, "mdmp_directory.format", "[4]E? " "(mdmp_stream_type)StreamType " "(mdmp_location_descriptor)Location", 0); /* Parse each entry in the directory */ ut64 rvadir = obj->hdr->stream_directory_rva; for (i = 0; i < (int)obj->hdr->number_of_streams; i++) { ut32 delta = i * sizeof (struct minidump_directory); int r = r_buf_read_at (obj->b, rvadir + delta, (ut8*) &entry, sizeof (struct minidump_directory)); if (r) { r_bin_mdmp_init_directory_entry (obj, &entry); } } return true; }
169,148
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 config_save(const config_t *config, const char *filename) { assert(config != NULL); assert(filename != NULL); assert(*filename != '\0'); char *temp_filename = osi_calloc(strlen(filename) + 5); if (!temp_filename) { LOG_ERROR("%s unable to allocate memory for filename.", __func__); return false; } strcpy(temp_filename, filename); strcat(temp_filename, ".new"); FILE *fp = fopen(temp_filename, "wt"); if (!fp) { LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno)); goto error; } for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) { const section_t *section = (const section_t *)list_node(node); fprintf(fp, "[%s]\n", section->name); for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) { const entry_t *entry = (const entry_t *)list_node(enode); fprintf(fp, "%s = %s\n", entry->key, entry->value); } if (list_next(node) != list_end(config->sections)) fputc('\n', fp); } fflush(fp); fclose(fp); if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) { LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno)); goto error; } if (rename(temp_filename, filename) == -1) { LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno)); goto error; } osi_free(temp_filename); return true; error:; unlink(temp_filename); osi_free(temp_filename); return false; } 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
bool config_save(const config_t *config, const char *filename) { assert(config != NULL); assert(filename != NULL); assert(*filename != '\0'); // Steps to ensure content of config file gets to disk: // // 1) Open and write to temp file (e.g. bt_config.conf.new). // 2) Sync the temp file to disk with fsync(). // 3) Rename temp file to actual config file (e.g. bt_config.conf). // This ensures atomic update. // 4) Sync directory that has the conf file with fsync(). // This ensures directory entries are up-to-date. int dir_fd = -1; FILE *fp = NULL; // Build temp config file based on config file (e.g. bt_config.conf.new). static const char *temp_file_ext = ".new"; const int filename_len = strlen(filename); const int temp_filename_len = filename_len + strlen(temp_file_ext) + 1; char *temp_filename = osi_calloc(temp_filename_len); snprintf(temp_filename, temp_filename_len, "%s%s", filename, temp_file_ext); // Extract directory from file path (e.g. /data/misc/bluedroid). char *temp_dirname = osi_strdup(filename); const char *directoryname = dirname(temp_dirname); if (!directoryname) { LOG_ERROR("%s error extracting directory from '%s': %s", __func__, filename, strerror(errno)); goto error; } dir_fd = TEMP_FAILURE_RETRY(open(directoryname, O_RDONLY)); if (dir_fd < 0) { LOG_ERROR("%s unable to open dir '%s': %s", __func__, directoryname, strerror(errno)); goto error; } fp = fopen(temp_filename, "wt"); if (!fp) { LOG_ERROR("%s unable to write file '%s': %s", __func__, temp_filename, strerror(errno)); goto error; } for (const list_node_t *node = list_begin(config->sections); node != list_end(config->sections); node = list_next(node)) { const section_t *section = (const section_t *)list_node(node); if (fprintf(fp, "[%s]\n", section->name) < 0) { LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno)); goto error; } for (const list_node_t *enode = list_begin(section->entries); enode != list_end(section->entries); enode = list_next(enode)) { const entry_t *entry = (const entry_t *)list_node(enode); if (fprintf(fp, "%s = %s\n", entry->key, entry->value) < 0) { LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno)); goto error; } } if (list_next(node) != list_end(config->sections)) { if (fputc('\n', fp) == EOF) { LOG_ERROR("%s unable to write to file '%s': %s", __func__, temp_filename, strerror(errno)); goto error; } } } // Sync written temp file out to disk. fsync() is blocking until data makes it to disk. if (fsync(fileno(fp)) < 0) { LOG_WARN("%s unable to fsync file '%s': %s", __func__, temp_filename, strerror(errno)); } if (fclose(fp) == EOF) { LOG_ERROR("%s unable to close file '%s': %s", __func__, temp_filename, strerror(errno)); goto error; } fp = NULL; if (chmod(temp_filename, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) == -1) { LOG_ERROR("%s unable to change file permissions '%s': %s", __func__, filename, strerror(errno)); goto error; } // Rename written temp file to the actual config file. if (rename(temp_filename, filename) == -1) { LOG_ERROR("%s unable to commit file '%s': %s", __func__, filename, strerror(errno)); goto error; } // This should ensure the directory is updated as well. if (fsync(dir_fd) < 0) { LOG_WARN("%s unable to fsync dir '%s': %s", __func__, directoryname, strerror(errno)); } if (close(dir_fd) < 0) { LOG_ERROR("%s unable to close dir '%s': %s", __func__, directoryname, strerror(errno)); goto error; } osi_free(temp_filename); osi_free(temp_dirname); return true; error: // This indicates there is a write issue. Unlink as partial data is not acceptable. unlink(temp_filename); if (fp) fclose(fp); if (dir_fd != -1) close(dir_fd); osi_free(temp_filename); osi_free(temp_dirname); return false; }
173,479
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: cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() { return delegated_frame_host_ ? delegated_frame_host_->GetFrameSinkId() : cc::FrameSinkId(); } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 TBR=jam@chromium.org Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} CWE ID: CWE-254
cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() { return frame_sink_id_; }
172,234
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 ChromeBrowserMainPartsChromeos::PreEarlyInitialization() { base::CommandLine* singleton_command_line = base::CommandLine::ForCurrentProcess(); if (parsed_command_line().HasSwitch(switches::kGuestSession)) { singleton_command_line->AppendSwitch(::switches::kDisableSync); singleton_command_line->AppendSwitch(::switches::kDisableExtensions); browser_defaults::bookmarks_enabled = false; } if (!base::SysInfo::IsRunningOnChromeOS() && !parsed_command_line().HasSwitch(switches::kLoginManager) && !parsed_command_line().HasSwitch(switches::kLoginUser) && !parsed_command_line().HasSwitch(switches::kGuestSession)) { singleton_command_line->AppendSwitchASCII( switches::kLoginUser, cryptohome::Identification(user_manager::StubAccountId()).id()); if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) { singleton_command_line->AppendSwitchASCII(switches::kLoginProfile, chrome::kTestUserProfileDir); } LOG(WARNING) << "Running as stub user with profile dir: " << singleton_command_line ->GetSwitchValuePath(switches::kLoginProfile) .value(); } RegisterStubPathOverridesIfNecessary(); #if defined(GOOGLE_CHROME_BUILD) const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK"; std::string channel; if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel)) chrome::SetChannel(channel); #endif dbus_pre_early_init_ = std::make_unique<internal::DBusPreEarlyInit>(); return ChromeBrowserMainPartsLinux::PreEarlyInitialization(); } Commit Message: Add a fake DriveFS launcher client. Using DriveFS requires building and deploying ChromeOS. Add a client for the fake DriveFS launcher to allow the use of a real DriveFS from a ChromeOS chroot to be used with a target_os="chromeos" build of chrome. This connects to the fake DriveFS launcher using mojo over a unix domain socket named by a command-line flag, using the launcher to create DriveFS instances. Bug: 848126 Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1 Reviewed-on: https://chromium-review.googlesource.com/1098434 Reviewed-by: Xiyuan Xia <xiyuan@chromium.org> Commit-Queue: Sam McNally <sammc@chromium.org> Cr-Commit-Position: refs/heads/master@{#567513} CWE ID:
int ChromeBrowserMainPartsChromeos::PreEarlyInitialization() { base::CommandLine* singleton_command_line = base::CommandLine::ForCurrentProcess(); if (parsed_command_line().HasSwitch(switches::kGuestSession)) { singleton_command_line->AppendSwitch(::switches::kDisableSync); singleton_command_line->AppendSwitch(::switches::kDisableExtensions); browser_defaults::bookmarks_enabled = false; } if (!base::SysInfo::IsRunningOnChromeOS() && !parsed_command_line().HasSwitch(switches::kLoginManager) && !parsed_command_line().HasSwitch(switches::kLoginUser) && !parsed_command_line().HasSwitch(switches::kGuestSession)) { singleton_command_line->AppendSwitchASCII( switches::kLoginUser, cryptohome::Identification(user_manager::StubAccountId()).id()); if (!parsed_command_line().HasSwitch(switches::kLoginProfile)) { singleton_command_line->AppendSwitchASCII(switches::kLoginProfile, chrome::kTestUserProfileDir); } LOG(WARNING) << "Running as stub user with profile dir: " << singleton_command_line ->GetSwitchValuePath(switches::kLoginProfile) .value(); } RegisterStubPathOverridesIfNecessary(); #if defined(GOOGLE_CHROME_BUILD) const char kChromeOSReleaseTrack[] = "CHROMEOS_RELEASE_TRACK"; std::string channel; if (base::SysInfo::GetLsbReleaseValue(kChromeOSReleaseTrack, &channel)) chrome::SetChannel(channel); #endif dbus_pre_early_init_ = std::make_unique<internal::DBusPreEarlyInit>(); if (!base::SysInfo::IsRunningOnChromeOS() && parsed_command_line().HasSwitch( switches::kFakeDriveFsLauncherChrootPath) && parsed_command_line().HasSwitch( switches::kFakeDriveFsLauncherSocketPath)) { drivefs::FakeDriveFsLauncherClient::Init( parsed_command_line().GetSwitchValuePath( switches::kFakeDriveFsLauncherChrootPath), parsed_command_line().GetSwitchValuePath( switches::kFakeDriveFsLauncherSocketPath)); } return ChromeBrowserMainPartsLinux::PreEarlyInitialization(); }
171,728
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 ShellBrowserMain(const content::MainFunctionParams& parameters) { bool layout_test_mode = CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree); base::ScopedTempDir browser_context_path_for_layout_tests; if (layout_test_mode) { CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir()); CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kContentShellDataPath, browser_context_path_for_layout_tests.path().MaybeAsASCII()); } scoped_ptr<content::BrowserMainRunner> main_runner_( content::BrowserMainRunner::Create()); int exit_code = main_runner_->Initialize(parameters); if (exit_code >= 0) return exit_code; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kCheckLayoutTestSysDeps)) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); main_runner_->Shutdown(); return 0; } if (layout_test_mode) { content::WebKitTestController test_controller; std::string test_string; CommandLine::StringVector args = CommandLine::ForCurrentProcess()->GetArgs(); size_t command_line_position = 0; bool ran_at_least_once = false; #if defined(OS_ANDROID) std::cout << "#READY\n"; std::cout.flush(); #endif while (GetNextTest(args, &command_line_position, &test_string)) { if (test_string.empty()) continue; if (test_string == "QUIT") break; bool enable_pixel_dumps; std::string pixel_hash; FilePath cwd; GURL test_url = GetURLForLayoutTest( test_string, &cwd, &enable_pixel_dumps, &pixel_hash); if (!content::WebKitTestController::Get()->PrepareForLayoutTest( test_url, cwd, enable_pixel_dumps, pixel_hash)) { break; } ran_at_least_once = true; main_runner_->Run(); if (!content::WebKitTestController::Get()->ResetAfterLayoutTest()) break; } if (!ran_at_least_once) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); } exit_code = 0; } else { exit_code = main_runner_->Run(); } main_runner_->Shutdown(); return exit_code; } Commit Message: [content shell] reset the CWD after each layout test BUG=111316 R=marja@chromium.org Review URL: https://codereview.chromium.org/11633017 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173906 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int ShellBrowserMain(const content::MainFunctionParams& parameters) { bool layout_test_mode = CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree); base::ScopedTempDir browser_context_path_for_layout_tests; if (layout_test_mode) { CHECK(browser_context_path_for_layout_tests.CreateUniqueTempDir()); CHECK(!browser_context_path_for_layout_tests.path().MaybeAsASCII().empty()); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kContentShellDataPath, browser_context_path_for_layout_tests.path().MaybeAsASCII()); } scoped_ptr<content::BrowserMainRunner> main_runner_( content::BrowserMainRunner::Create()); int exit_code = main_runner_->Initialize(parameters); if (exit_code >= 0) return exit_code; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kCheckLayoutTestSysDeps)) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); main_runner_->Shutdown(); return 0; } if (layout_test_mode) { content::WebKitTestController test_controller; std::string test_string; CommandLine::StringVector args = CommandLine::ForCurrentProcess()->GetArgs(); size_t command_line_position = 0; bool ran_at_least_once = false; #if defined(OS_ANDROID) std::cout << "#READY\n"; std::cout.flush(); #endif FilePath original_cwd; { // We're outside of the message loop here, and this is a test. base::ThreadRestrictions::ScopedAllowIO allow_io; file_util::GetCurrentDirectory(&original_cwd); } while (GetNextTest(args, &command_line_position, &test_string)) { if (test_string.empty()) continue; if (test_string == "QUIT") break; bool enable_pixel_dumps; std::string pixel_hash; FilePath cwd; GURL test_url = GetURLForLayoutTest( test_string, &cwd, &enable_pixel_dumps, &pixel_hash); if (!content::WebKitTestController::Get()->PrepareForLayoutTest( test_url, cwd, enable_pixel_dumps, pixel_hash)) { break; } ran_at_least_once = true; main_runner_->Run(); { // We're outside of the message loop here, and this is a test. base::ThreadRestrictions::ScopedAllowIO allow_io; file_util::SetCurrentDirectory(original_cwd); } if (!content::WebKitTestController::Get()->ResetAfterLayoutTest()) break; } if (!ran_at_least_once) { MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure()); main_runner_->Run(); } exit_code = 0; } else { exit_code = main_runner_->Run(); } main_runner_->Shutdown(); return exit_code; }
171,469
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 udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to) { struct pathComponent *pc; int elen = 0; unsigned char *p = to; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: p = to; *p++ = '/'; break; case 3: memcpy(p, "../", 3); p += 3; break; case 4: memcpy(p, "./", 2); p += 2; /* that would be . - just ignore */ break; case 5: p += udf_get_filename(sb, pc->componentIdent, p, pc->lengthComponentIdent); *p++ = '/'; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: stable@vger.kernel.org Reported-by: Carl Henrik Lunde <chlunde@ping.uio.no> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-17
static void udf_pc_to_char(struct super_block *sb, unsigned char *from, static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; }
166,757
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 fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction) { FDrive *cur_drv = get_cur_drv(fdctrl); if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x80) { /* Command parameters done */ if (fdctrl->fifo[fdctrl->data_pos - 1] & 0x40) { fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl->fifo[2] = 0; fdctrl->fifo[3] = 0; } } else if (fdctrl->data_len > 7) { /* ERROR */ fdctrl->fifo[0] = 0x80 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl); fdctrl_set_fifo(fdctrl, 1); } } Commit Message: CWE ID: CWE-119
static void fdctrl_handle_drive_specification_command(FDCtrl *fdctrl, int direction) { FDrive *cur_drv = get_cur_drv(fdctrl); uint32_t pos; pos = fdctrl->data_pos - 1; pos %= FD_SECTOR_LEN; if (fdctrl->fifo[pos] & 0x80) { /* Command parameters done */ if (fdctrl->fifo[pos] & 0x40) { fdctrl->fifo[0] = fdctrl->fifo[1]; fdctrl->fifo[2] = 0; fdctrl->fifo[3] = 0; } } else if (fdctrl->data_len > 7) { /* ERROR */ fdctrl->fifo[0] = 0x80 | (cur_drv->head << 2) | GET_CUR_DRV(fdctrl); fdctrl_set_fifo(fdctrl, 1); } }
164,706
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 PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame, WebKit::WebNode* node, bool is_preview) { DCHECK(frame); PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(), &settings.params)); bool result = true; if (PrintMsg_Print_Params_IsEmpty(settings.params)) { if (!is_preview) { render_view()->runModalAlertDialog( frame, l10n_util::GetStringUTF16( IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS)); } result = false; } if (result && (settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) { NOTREACHED(); result = false; } settings.pages.clear(); print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); return result; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame, bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame) { DCHECK(frame); PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(), &settings.params)); bool result = true; if (PrintMsg_Print_Params_IsEmpty(settings.params)) { render_view()->runModalAlertDialog( frame, l10n_util::GetStringUTF16( IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS)); result = false; } if (result && (settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) { NOTREACHED(); result = false; } settings.pages.clear(); print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); return result; }
170,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: void *gdImageJpegPtr (gdImagePtr im, int *size, int quality) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); gdImageJpegCtx (im, out, quality); rv = gdDPExtractData (out, size); out->gd_free (out); return rv; } Commit Message: Sync with upstream Even though libgd/libgd#492 is not a relevant bug fix for PHP, since the binding doesn't use the `gdImage*Ptr()` functions at all, we're porting the fix to stay in sync here. CWE ID: CWE-415
void *gdImageJpegPtr (gdImagePtr im, int *size, int quality) { void *rv; gdIOCtx *out = gdNewDynamicCtx (2048, NULL); if (!_gdImageJpegCtx(im, out, quality)) { rv = gdDPExtractData(out, size); } else { rv = NULL; } out->gd_free (out); return rv; }
169,736
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: DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), reloading_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); frontend_host_.reset(content::DevToolsFrontendHost::Create( web_contents_->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(this)))); } 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
DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), reloading_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); UpdateFrontendHost(); }
172,452
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: xcalloc (size_t num, size_t size) { void *ptr = malloc(num * size); if (ptr) { memset (ptr, '\0', (num * size)); } return ptr; } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
xcalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); void *ptr; ptr = malloc(res); if (ptr) { memset (ptr, '\0', (res)); } return ptr; }
168,358
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 FocusInCallback(IBusPanelService* panel, const gchar* path, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->FocusIn(path); } 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
static void FocusInCallback(IBusPanelService* panel, void FocusIn(IBusPanelService* panel, const gchar* input_context_path) { if (!input_context_path) { LOG(ERROR) << "NULL context passed"; } else { VLOG(1) << "FocusIn: " << input_context_path; } // Remember the current ic path. input_context_path_ = Or(input_context_path, ""); }
170,533
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 SoftVPXEncoder::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR param) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitrate = (OMX_VIDEO_PARAM_BITRATETYPE *)param; if (bitrate->nPortIndex != kOutputPortIndex) { return OMX_ErrorUnsupportedIndex; } bitrate->nTargetBitrate = mBitrate; if (mBitrateControlMode == VPX_VBR) { bitrate->eControlRate = OMX_Video_ControlRateVariable; } else if (mBitrateControlMode == VPX_CBR) { bitrate->eControlRate = OMX_Video_ControlRateConstant; } else { return OMX_ErrorUnsupportedSetting; } return OMX_ErrorNone; } case OMX_IndexParamVideoVp8: { OMX_VIDEO_PARAM_VP8TYPE *vp8Params = (OMX_VIDEO_PARAM_VP8TYPE *)param; if (vp8Params->nPortIndex != kOutputPortIndex) { return OMX_ErrorUnsupportedIndex; } vp8Params->eProfile = OMX_VIDEO_VP8ProfileMain; vp8Params->eLevel = mLevel; vp8Params->nDCTPartitions = mDCTPartitions; vp8Params->bErrorResilientMode = mErrorResilience; return OMX_ErrorNone; } case OMX_IndexParamVideoAndroidVp8Encoder: { OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *vp8AndroidParams = (OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param; if (vp8AndroidParams->nPortIndex != kOutputPortIndex) { return OMX_ErrorUnsupportedIndex; } vp8AndroidParams->nKeyFrameInterval = mKeyFrameInterval; vp8AndroidParams->eTemporalPattern = mTemporalPatternType; vp8AndroidParams->nTemporalLayerCount = mTemporalLayers; vp8AndroidParams->nMinQuantizer = mMinQuantizer; vp8AndroidParams->nMaxQuantizer = mMaxQuantizer; memcpy(vp8AndroidParams->nTemporalLayerBitrateRatio, mTemporalLayerBitrateRatio, sizeof(mTemporalLayerBitrateRatio)); return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalGetParameter(index, param); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVPXEncoder::internalGetParameter(OMX_INDEXTYPE index, OMX_PTR param) { const int32_t indexFull = index; switch (indexFull) { case OMX_IndexParamVideoBitrate: { OMX_VIDEO_PARAM_BITRATETYPE *bitrate = (OMX_VIDEO_PARAM_BITRATETYPE *)param; if (!isValidOMXParam(bitrate)) { return OMX_ErrorBadParameter; } if (bitrate->nPortIndex != kOutputPortIndex) { return OMX_ErrorUnsupportedIndex; } bitrate->nTargetBitrate = mBitrate; if (mBitrateControlMode == VPX_VBR) { bitrate->eControlRate = OMX_Video_ControlRateVariable; } else if (mBitrateControlMode == VPX_CBR) { bitrate->eControlRate = OMX_Video_ControlRateConstant; } else { return OMX_ErrorUnsupportedSetting; } return OMX_ErrorNone; } case OMX_IndexParamVideoVp8: { OMX_VIDEO_PARAM_VP8TYPE *vp8Params = (OMX_VIDEO_PARAM_VP8TYPE *)param; if (!isValidOMXParam(vp8Params)) { return OMX_ErrorBadParameter; } if (vp8Params->nPortIndex != kOutputPortIndex) { return OMX_ErrorUnsupportedIndex; } vp8Params->eProfile = OMX_VIDEO_VP8ProfileMain; vp8Params->eLevel = mLevel; vp8Params->nDCTPartitions = mDCTPartitions; vp8Params->bErrorResilientMode = mErrorResilience; return OMX_ErrorNone; } case OMX_IndexParamVideoAndroidVp8Encoder: { OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *vp8AndroidParams = (OMX_VIDEO_PARAM_ANDROID_VP8ENCODERTYPE *)param; if (!isValidOMXParam(vp8AndroidParams)) { return OMX_ErrorBadParameter; } if (vp8AndroidParams->nPortIndex != kOutputPortIndex) { return OMX_ErrorUnsupportedIndex; } vp8AndroidParams->nKeyFrameInterval = mKeyFrameInterval; vp8AndroidParams->eTemporalPattern = mTemporalPatternType; vp8AndroidParams->nTemporalLayerCount = mTemporalLayers; vp8AndroidParams->nMinQuantizer = mMinQuantizer; vp8AndroidParams->nMaxQuantizer = mMaxQuantizer; memcpy(vp8AndroidParams->nTemporalLayerBitrateRatio, mTemporalLayerBitrateRatio, sizeof(mTemporalLayerBitrateRatio)); return OMX_ErrorNone; } default: return SoftVideoEncoderOMXComponent::internalGetParameter(index, param); } }
174,213
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 UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics( const page_load_metrics::PageLoadExtraInfo& info, base::TimeTicks app_background_time) { ukm::builders::PageLoad builder(info.source_id); base::Optional<base::TimeDelta> foreground_duration = page_load_metrics::GetInitialForegroundDuration(info, app_background_time); if (foreground_duration) { builder.SetPageTiming_ForegroundDuration( foreground_duration.value().InMilliseconds()); } metrics::SystemProfileProto::Network::EffectiveConnectionType proto_effective_connection_type = metrics::ConvertEffectiveConnectionType(effective_connection_type_); if (proto_effective_connection_type != metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { builder.SetNet_EffectiveConnectionType2_OnNavigationStart( static_cast<int64_t>(proto_effective_connection_type)); } if (http_response_code_) { builder.SetNet_HttpResponseCode( static_cast<int64_t>(http_response_code_.value())); } if (http_rtt_estimate_) { builder.SetNet_HttpRttEstimate_OnNavigationStart( static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds())); } if (transport_rtt_estimate_) { builder.SetNet_TransportRttEstimate_OnNavigationStart( static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds())); } if (downstream_kbps_estimate_) { builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart( static_cast<int64_t>(downstream_kbps_estimate_.value())); } builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_)); builder.SetNavigation_PageEndReason( static_cast<int64_t>(info.page_end_reason)); if (info.did_commit && was_cached_) { builder.SetWasCached(1); } builder.Record(ukm::UkmRecorder::Get()); } Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation. Also refactor UkmPageLoadMetricsObserver to use this new boolean to report the user initiated metric in RecordPageLoadExtraInfoMetrics, so that it works correctly in the case when the page load failed. Bug: 925104 Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff Reviewed-on: https://chromium-review.googlesource.com/c/1450460 Commit-Queue: Annie Sullivan <sullivan@chromium.org> Reviewed-by: Bryan McQuade <bmcquade@chromium.org> Cr-Commit-Position: refs/heads/master@{#630870} CWE ID: CWE-79
void UkmPageLoadMetricsObserver::RecordPageLoadExtraInfoMetrics( const page_load_metrics::PageLoadExtraInfo& info, base::TimeTicks app_background_time) { ukm::builders::PageLoad builder(info.source_id); base::Optional<base::TimeDelta> foreground_duration = page_load_metrics::GetInitialForegroundDuration(info, app_background_time); if (foreground_duration) { builder.SetPageTiming_ForegroundDuration( foreground_duration.value().InMilliseconds()); } bool is_user_initiated_navigation = // All browser initiated page loads are user-initiated. info.user_initiated_info.browser_initiated || // Renderer-initiated navigations are user-initiated if there is an // associated input event. info.user_initiated_info.user_input_event; builder.SetExperimental_Navigation_UserInitiated( is_user_initiated_navigation); metrics::SystemProfileProto::Network::EffectiveConnectionType proto_effective_connection_type = metrics::ConvertEffectiveConnectionType(effective_connection_type_); if (proto_effective_connection_type != metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { builder.SetNet_EffectiveConnectionType2_OnNavigationStart( static_cast<int64_t>(proto_effective_connection_type)); } if (http_response_code_) { builder.SetNet_HttpResponseCode( static_cast<int64_t>(http_response_code_.value())); } if (http_rtt_estimate_) { builder.SetNet_HttpRttEstimate_OnNavigationStart( static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds())); } if (transport_rtt_estimate_) { builder.SetNet_TransportRttEstimate_OnNavigationStart( static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds())); } if (downstream_kbps_estimate_) { builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart( static_cast<int64_t>(downstream_kbps_estimate_.value())); } builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_)); builder.SetNavigation_PageEndReason( static_cast<int64_t>(info.page_end_reason)); if (info.did_commit && was_cached_) { builder.SetWasCached(1); } builder.Record(ukm::UkmRecorder::Get()); }
172,496
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 vrend_renderer_context_destroy(uint32_t handle) { struct vrend_decode_ctx *ctx; bool ret; if (handle >= VREND_MAX_CTX) return; ctx = dec_ctx[handle]; if (!ctx) return; vrend_hw_switch_context(dec_ctx[0]->grctx, true); } Commit Message: CWE ID: CWE-476
void vrend_renderer_context_destroy(uint32_t handle) { struct vrend_decode_ctx *ctx; bool ret; if (handle >= VREND_MAX_CTX) return; /* never destroy context 0 here, it will be destroyed in vrend_decode_reset()*/ if (handle == 0) { return; } ctx = dec_ctx[handle]; if (!ctx) return; vrend_hw_switch_context(dec_ctx[0]->grctx, true); }
164,949
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: WebContents* DevToolsWindow::OpenURLFromTab( WebContents* source, const content::OpenURLParams& params) { DCHECK(source == main_web_contents_); if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) { WebContents* inspected_web_contents = GetInspectedWebContents(); return inspected_web_contents ? inspected_web_contents->OpenURL(params) : NULL; } bindings_->Reload(); return main_web_contents_; } Commit Message: [DevTools] Use no-referrer for DevTools links Bug: 732751 Change-Id: I77753120e2424203dedcc7bc0847fb67f87fe2b2 Reviewed-on: https://chromium-review.googlesource.com/615021 Reviewed-by: Andrey Kosyakov <caseq@chromium.org> Commit-Queue: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#494413} CWE ID: CWE-668
WebContents* DevToolsWindow::OpenURLFromTab( WebContents* source, const content::OpenURLParams& params) { DCHECK(source == main_web_contents_); if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) { WebContents* inspected_web_contents = GetInspectedWebContents(); if (!inspected_web_contents) return nullptr; content::OpenURLParams modified = params; modified.referrer = content::Referrer(); return inspected_web_contents->OpenURL(modified); } bindings_->Reload(); return main_web_contents_; }
172,960