instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int gdTransformAffineCopy(gdImagePtr dst, int dst_x, int dst_y, const gdImagePtr src, gdRectPtr src_region, const double affine[6]) { int c1x,c1y,c2x,c2y; int backclip = 0; int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2; register int x, y, src_offset_x, src_offset_y; double inv[6]; int *dst_p; gdPointF pt, src_pt; gdRect bbox; int end_x, end_y; gdInterpolationMethod interpolation_id_bak = GD_DEFAULT; interpolation_method interpolation_bak; /* These methods use special implementations */ if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) { interpolation_id_bak = src->interpolation_id; interpolation_bak = src->interpolation; gdImageSetInterpolationMethod(src, GD_BICUBIC); } gdImageClipRectangle(src, src_region); if (src_region->x > 0 || src_region->y > 0 || src_region->width < gdImageSX(src) || src_region->height < gdImageSY(src)) { backclip = 1; gdImageGetClip(src, &backup_clipx1, &backup_clipy1, &backup_clipx2, &backup_clipy2); gdImageSetClip(src, src_region->x, src_region->y, src_region->x + src_region->width - 1, src_region->y + src_region->height - 1); } if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) { if (backclip) { gdImageSetClip(src, backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2); } gdImageSetInterpolationMethod(src, interpolation_id_bak); return GD_FALSE; } gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y); end_x = bbox.width + (int) fabs(bbox.x); end_y = bbox.height + (int) fabs(bbox.y); /* Get inverse affine to let us work with destination -> source */ gdAffineInvert(inv, affine); src_offset_x = src_region->x; src_offset_y = src_region->y; if (dst->alphaBlendingFlag) { for (y = bbox.y; y <= end_y; y++) { pt.y = y + 0.5; for (x = 0; x <= end_x; x++) { pt.x = x + 0.5; gdAffineApplyToPointF(&src_pt, &pt, inv); gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0)); } } } else { for (y = 0; y <= end_y; y++) { pt.y = y + 0.5 + bbox.y; if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) { continue; } dst_p = dst->tpixels[dst_y + y] + dst_x; for (x = 0; x <= end_x; x++) { pt.x = x + 0.5 + bbox.x; gdAffineApplyToPointF(&src_pt, &pt, inv); if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) { break; } *(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1); } } } /* Restore clip if required */ if (backclip) { gdImageSetClip(src, backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2); } gdImageSetInterpolationMethod(src, interpolation_id_bak); return GD_TRUE; } Commit Message: Fixed bug #72227: imagescale out-of-bounds read Ported from https://github.com/libgd/libgd/commit/4f65a3e4eedaffa1efcf9ee1eb08f0b504fbc31a CWE ID: CWE-125
int gdTransformAffineCopy(gdImagePtr dst, int dst_x, int dst_y, const gdImagePtr src, gdRectPtr src_region, const double affine[6]) { int c1x,c1y,c2x,c2y; int backclip = 0; int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2; register int x, y, src_offset_x, src_offset_y; double inv[6]; int *dst_p; gdPointF pt, src_pt; gdRect bbox; int end_x, end_y; gdInterpolationMethod interpolation_id_bak = GD_DEFAULT; interpolation_method interpolation_bak; /* These methods use special implementations */ if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) { interpolation_id_bak = src->interpolation_id; interpolation_bak = src->interpolation; gdImageSetInterpolationMethod(src, GD_BICUBIC); } gdImageClipRectangle(src, src_region); if (src_region->x > 0 || src_region->y > 0 || src_region->width < gdImageSX(src) || src_region->height < gdImageSY(src)) { backclip = 1; gdImageGetClip(src, &backup_clipx1, &backup_clipy1, &backup_clipx2, &backup_clipy2); gdImageSetClip(src, src_region->x, src_region->y, src_region->x + src_region->width - 1, src_region->y + src_region->height - 1); } if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) { if (backclip) { gdImageSetClip(src, backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2); } gdImageSetInterpolationMethod(src, interpolation_id_bak); return GD_FALSE; } gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y); end_x = bbox.width + (int) fabs(bbox.x); end_y = bbox.height + (int) fabs(bbox.y); /* Get inverse affine to let us work with destination -> source */ gdAffineInvert(inv, affine); src_offset_x = src_region->x; src_offset_y = src_region->y; if (dst->alphaBlendingFlag) { for (y = bbox.y; y <= end_y; y++) { pt.y = y + 0.5; for (x = 0; x <= end_x; x++) { pt.x = x + 0.5; gdAffineApplyToPointF(&src_pt, &pt, inv); gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0)); } } } else { for (y = 0; y <= end_y; y++) { pt.y = y + 0.5 + bbox.y; if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) { continue; } dst_p = dst->tpixels[dst_y + y] + dst_x; for (x = 0; x <= end_x; x++) { pt.x = x + 0.5 + bbox.x; gdAffineApplyToPointF(&src_pt, &pt, inv); if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) { break; } *(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1); } } } /* Restore clip if required */ if (backclip) { gdImageSetClip(src, backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2); } gdImageSetInterpolationMethod(src, interpolation_id_bak); return GD_TRUE; }
170,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } Commit Message: Fix OOB reads of the TGA decompression buffer It is possible to craft TGA files which will overflow the decompression buffer, but not the image's bitmap. Therefore we augment the check for the bitmap's overflow with a check for the buffer's overflow. This issue had been reported by Ibrahim El-Sayed to [email protected]. CVE-2016-6906 CWE ID: CWE-125
int read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; }
168,823
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserContextDestroyer::DestroyContext(BrowserContext* context) { CHECK(context->IsOffTheRecord() || !context->HasOffTheRecordContext()); content::BrowserContext::NotifyWillBeDestroyed(context); std::set<content::RenderProcessHost*> hosts; for (content::RenderProcessHost::iterator it = content::RenderProcessHost::AllHostsIterator(); !it.IsAtEnd(); it.Advance()) { content::RenderProcessHost* host = it.GetCurrentValue(); if (host->GetBrowserContext() != context) { continue; } hosts.insert(host); //// static } if (hosts.empty()) { delete context; } else { new BrowserContextDestroyer(context, hosts); } } Commit Message: CWE ID: CWE-20
void BrowserContextDestroyer::DestroyContext(BrowserContext* context) { void BrowserContextDestroyer::Shutdown() { auto destroy_all_unused_contexts = []() { auto it = g_contexts_pending_deletion.Get().begin(); while (it != g_contexts_pending_deletion.Get().end()) { BrowserContextDestroyer* destroyer = *it; ++it; if (!destroyer->finish_destroy_scheduled_) { continue; } destroyer->FinishDestroyContext(); // |destroyer| is invalid now } }; // We make 2 passes over the list because the first pass can destroy an // incognito BrowserContext that subsequently schedules its owner context for // deletion destroy_all_unused_contexts(); destroy_all_unused_contexts(); } //// static void BrowserContextDestroyer::RenderProcessHostAssignedToSiteInstance( content::RenderProcessHost* host) { BrowserContextDestroyer* destroyer = GetForContext(host->GetBrowserContext()); if (!destroyer) { return; } CHECK(!destroyer->finish_destroy_scheduled_); if (destroyer->pending_host_ids_.find(host->GetID()) != destroyer->pending_host_ids_.end()) { return; } destroyer->ObserveHost(host); }
165,419
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_event_interrupt(struct pt_regs *regs) { int i; struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events); struct perf_event *event; unsigned long val; int found = 0; int nmi; if (cpuhw->n_limited) freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5), mfspr(SPRN_PMC6)); perf_read_regs(regs); nmi = perf_intr_is_nmi(regs); if (nmi) nmi_enter(); else irq_enter(); for (i = 0; i < cpuhw->n_events; ++i) { event = cpuhw->event[i]; if (!event->hw.idx || is_limited_pmc(event->hw.idx)) continue; val = read_pmc(event->hw.idx); if ((int)val < 0) { /* event has overflowed */ found = 1; record_and_restart(event, val, regs, nmi); } } /* * In case we didn't find and reset the event that caused * the interrupt, scan all events and reset any that are * negative, to avoid getting continual interrupts. * Any that we processed in the previous loop will not be negative. */ if (!found) { for (i = 0; i < ppmu->n_counter; ++i) { if (is_limited_pmc(i + 1)) continue; val = read_pmc(i + 1); if (pmc_overflow(val)) write_pmc(i + 1, 0); } } /* * Reset MMCR0 to its normal value. This will set PMXE and * clear FC (freeze counters) and PMAO (perf mon alert occurred) * and thus allow interrupts to occur again. * XXX might want to use MSR.PM to keep the events frozen until * we get back out of this interrupt. */ write_mmcr0(cpuhw, cpuhw->mmcr[0]); if (nmi) nmi_exit(); else irq_exit(); } Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface The nmi parameter indicated if we could do wakeups from the current context, if not, we would set some state and self-IPI and let the resulting interrupt do the wakeup. For the various event classes: - hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from the PMI-tail (ARM etc.) - tracepoint: nmi=0; since tracepoint could be from NMI context. - software: nmi=[0,1]; some, like the schedule thing cannot perform wakeups, and hence need 0. As one can see, there is very little nmi=1 usage, and the down-side of not using it is that on some platforms some software events can have a jiffy delay in wakeup (when arch_irq_work_raise isn't implemented). The up-side however is that we can remove the nmi parameter and save a bunch of conditionals in fast paths. Signed-off-by: Peter Zijlstra <[email protected]> Cc: Michael Cree <[email protected]> Cc: Will Deacon <[email protected]> Cc: Deng-Cheng Zhu <[email protected]> Cc: Anton Blanchard <[email protected]> Cc: Eric B Munson <[email protected]> Cc: Heiko Carstens <[email protected]> Cc: Paul Mundt <[email protected]> Cc: David S. Miller <[email protected]> Cc: Frederic Weisbecker <[email protected]> Cc: Jason Wessel <[email protected]> Cc: Don Zickus <[email protected]> Link: http://lkml.kernel.org/n/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-399
static void perf_event_interrupt(struct pt_regs *regs) { int i; struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events); struct perf_event *event; unsigned long val; int found = 0; int nmi; if (cpuhw->n_limited) freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5), mfspr(SPRN_PMC6)); perf_read_regs(regs); nmi = perf_intr_is_nmi(regs); if (nmi) nmi_enter(); else irq_enter(); for (i = 0; i < cpuhw->n_events; ++i) { event = cpuhw->event[i]; if (!event->hw.idx || is_limited_pmc(event->hw.idx)) continue; val = read_pmc(event->hw.idx); if ((int)val < 0) { /* event has overflowed */ found = 1; record_and_restart(event, val, regs); } } /* * In case we didn't find and reset the event that caused * the interrupt, scan all events and reset any that are * negative, to avoid getting continual interrupts. * Any that we processed in the previous loop will not be negative. */ if (!found) { for (i = 0; i < ppmu->n_counter; ++i) { if (is_limited_pmc(i + 1)) continue; val = read_pmc(i + 1); if (pmc_overflow(val)) write_pmc(i + 1, 0); } } /* * Reset MMCR0 to its normal value. This will set PMXE and * clear FC (freeze counters) and PMAO (perf mon alert occurred) * and thus allow interrupts to occur again. * XXX might want to use MSR.PM to keep the events frozen until * we get back out of this interrupt. */ write_mmcr0(cpuhw, cpuhw->mmcr[0]); if (nmi) nmi_exit(); else irq_exit(); }
165,788
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; if (data_size <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Integer overflow in data size"); RETURN_FALSE; } data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); }
167,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_ANY); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; } Commit Message: common: [security fix] Make sure sockets only listen locally CWE ID: CWE-284
int socket_create(uint16_t port) { int sfd = -1; int yes = 1; #ifdef WIN32 WSADATA wsa_data; if (!wsa_init) { if (WSAStartup(MAKEWORD(2,2), &wsa_data) != ERROR_SUCCESS) { fprintf(stderr, "WSAStartup failed!\n"); ExitProcess(-1); } wsa_init = 1; } #endif struct sockaddr_in saddr; if (0 > (sfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))) { perror("socket()"); return -1; } if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void*)&yes, sizeof(int)) == -1) { perror("setsockopt()"); socket_close(sfd); return -1; } memset((void *) &saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); saddr.sin_port = htons(port); if (0 > bind(sfd, (struct sockaddr *) &saddr, sizeof(saddr))) { perror("bind()"); socket_close(sfd); return -1; } if (listen(sfd, 1) == -1) { perror("listen()"); socket_close(sfd); return -1; } return sfd; }
167,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id) { struct snd_msnd *chip = dev_id; void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF; /* Send ack to DSP */ /* inb(chip->io + HP_RXL); */ /* Evaluate queued DSP messages */ while (readw(chip->DSPQ + JQS_wTail) != readw(chip->DSPQ + JQS_wHead)) { u16 wTmp; snd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * readw(chip->DSPQ + JQS_wHead))); wTmp = readw(chip->DSPQ + JQS_wHead) + 1; if (wTmp > readw(chip->DSPQ + JQS_wSize)) writew(0, chip->DSPQ + JQS_wHead); else writew(wTmp, chip->DSPQ + JQS_wHead); } /* Send ack to DSP */ inb(chip->io + HP_RXL); return IRQ_HANDLED; } Commit Message: ALSA: msnd: Optimize / harden DSP and MIDI loops The ISA msnd drivers have loops fetching the ring-buffer head, tail and size values inside the loops. Such codes are inefficient and fragile. This patch optimizes it, and also adds the sanity check to avoid the endless loops. Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196131 Bugzilla: https://bugzilla.kernel.org/show_bug.cgi?id=196133 Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-125
static irqreturn_t snd_msnd_interrupt(int irq, void *dev_id) { struct snd_msnd *chip = dev_id; void *pwDSPQData = chip->mappedbase + DSPQ_DATA_BUFF; u16 head, tail, size; /* Send ack to DSP */ /* inb(chip->io + HP_RXL); */ /* Evaluate queued DSP messages */ head = readw(chip->DSPQ + JQS_wHead); tail = readw(chip->DSPQ + JQS_wTail); size = readw(chip->DSPQ + JQS_wSize); if (head > size || tail > size) goto out; while (head != tail) { snd_msnd_eval_dsp_msg(chip, readw(pwDSPQData + 2 * head)); if (++head > size) head = 0; writew(head, chip->DSPQ + JQS_wHead); } out: /* Send ack to DSP */ inb(chip->io + HP_RXL); return IRQ_HANDLED; }
168,080
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHPAPI char *php_escape_shell_arg(char *str) { int x, y = 0, l = strlen(str); char *cmd; size_t estimate = (4 * l) + 3; TSRMLS_FETCH(); cmd = safe_emalloc(4, l, 3); /* worst case */ #ifdef PHP_WIN32 cmd[y++] = '"'; #else cmd[y++] = '\''; #endif for (x = 0; x < l; x++) { int mb_len = php_mblen(str + x, (l - x)); /* skip non-valid multibyte characters */ if (mb_len < 0) { continue; } else if (mb_len > 1) { memcpy(cmd + y, str + x, mb_len); y += mb_len; x += mb_len - 1; continue; } switch (str[x]) { #ifdef PHP_WIN32 case '"': case '%': cmd[y++] = ' '; break; #else case '\'': cmd[y++] = '\''; cmd[y++] = '\\'; cmd[y++] = '\''; #endif /* fall-through */ default: cmd[y++] = str[x]; } } #ifdef PHP_WIN32 cmd[y++] = '"'; #else cmd[y++] = '\''; return cmd; } Commit Message: CWE ID: CWE-78
PHPAPI char *php_escape_shell_arg(char *str) { int x, y = 0, l = strlen(str); char *cmd; size_t estimate = (4 * l) + 3; TSRMLS_FETCH(); cmd = safe_emalloc(4, l, 3); /* worst case */ #ifdef PHP_WIN32 cmd[y++] = '"'; #else cmd[y++] = '\''; #endif for (x = 0; x < l; x++) { int mb_len = php_mblen(str + x, (l - x)); /* skip non-valid multibyte characters */ if (mb_len < 0) { continue; } else if (mb_len > 1) { memcpy(cmd + y, str + x, mb_len); y += mb_len; x += mb_len - 1; continue; } switch (str[x]) { #ifdef PHP_WIN32 case '"': case '%': cmd[y++] = ' '; break; #else case '\'': cmd[y++] = '\''; cmd[y++] = '\\'; cmd[y++] = '\''; #endif /* fall-through */ default: cmd[y++] = str[x]; } } #ifdef PHP_WIN32 if (y > 0 && '\\' == cmd[y - 1]) { int k = 0, n = y - 1; for (; n >= 0 && '\\' == cmd[n]; n--, k++); if (k % 2) { cmd[y++] = '\\'; } } cmd[y++] = '"'; #else cmd[y++] = '\''; return cmd; }
165,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const BlockEntry* Cues::GetBlock(const CuePoint* pCP, const CuePoint::TrackPosition* pTP) const { if (pCP == NULL) return NULL; if (pTP == NULL) return NULL; return m_pSegment->GetBlock(*pCP, *pTP); } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
const BlockEntry* Cues::GetBlock(const CuePoint* pCP, const CuePoint::TrackPosition* pTP) const { if (pCP == NULL || pTP == NULL) return NULL; return m_pSegment->GetBlock(*pCP, *pTP); }
173,813
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AXNodeObject::isChecked() const { Node* node = this->getNode(); if (!node) return false; if (isHTMLInputElement(*node)) return toHTMLInputElement(*node).shouldAppearChecked(); switch (ariaRoleAttribute()) { case CheckBoxRole: case MenuItemCheckBoxRole: case MenuItemRadioRole: case RadioButtonRole: case SwitchRole: if (equalIgnoringCase( getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked), "true")) return true; return false; default: break; } return false; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXNodeObject::isChecked() const { Node* node = this->getNode(); if (!node) return false; if (isHTMLInputElement(*node)) return toHTMLInputElement(*node).shouldAppearChecked(); switch (ariaRoleAttribute()) { case CheckBoxRole: case MenuItemCheckBoxRole: case MenuItemRadioRole: case RadioButtonRole: case SwitchRole: if (equalIgnoringASCIICase( getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked), "true")) return true; return false; default: break; } return false; }
171,914
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltProcessUserParamInternal(xsltTransformContextPtr ctxt, const xmlChar * name, const xmlChar * value, int eval) { xsltStylesheetPtr style; const xmlChar *prefix; const xmlChar *href; xmlXPathCompExprPtr xpExpr; xmlXPathObjectPtr result; xsltStackElemPtr elem; int res; void *res_ptr; if (ctxt == NULL) return(-1); if (name == NULL) return(0); if (value == NULL) return(0); style = ctxt->style; #ifdef WITH_XSLT_DEBUG_VARIABLE XSLT_TRACE(ctxt,XSLT_TRACE_VARIABLES,xsltGenericDebug(xsltGenericDebugContext, "Evaluating user parameter %s=%s\n", name, value)); #endif /* * Name lookup */ name = xsltSplitQName(ctxt->dict, name, &prefix); href = NULL; if (prefix != NULL) { xmlNsPtr ns; ns = xmlSearchNs(style->doc, xmlDocGetRootElement(style->doc), prefix); if (ns == NULL) { xsltTransformError(ctxt, style, NULL, "user param : no namespace bound to prefix %s\n", prefix); href = NULL; } else { href = ns->href; } } if (name == NULL) return (-1); res_ptr = xmlHashLookup2(ctxt->globalVars, name, href); if (res_ptr != 0) { xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } if (ctxt->globalVars == NULL) ctxt->globalVars = xmlHashCreate(20); /* * do not overwrite variables with parameters from the command line */ while (style != NULL) { elem = ctxt->style->variables; while (elem != NULL) { if ((elem->comp != NULL) && (elem->comp->type == XSLT_FUNC_VARIABLE) && (xmlStrEqual(elem->name, name)) && (xmlStrEqual(elem->nameURI, href))) { return(0); } elem = elem->next; } style = xsltNextImport(style); } style = ctxt->style; elem = NULL; /* * Do the evaluation if @eval is non-zero. */ result = NULL; if (eval != 0) { xpExpr = xmlXPathCompile(value); if (xpExpr != NULL) { xmlDocPtr oldXPDoc; xmlNodePtr oldXPContextNode; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; xmlNsPtr *oldXPNamespaces; xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; /* * Save context states. */ oldXPDoc = xpctxt->doc; oldXPContextNode = xpctxt->node; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; oldXPNamespaces = xpctxt->namespaces; oldXPNsNr = xpctxt->nsNr; /* * SPEC XSLT 1.0: * "At top-level, the expression or template specifying the * variable value is evaluated with the same context as that used * to process the root node of the source document: the current * node is the root node of the source document and the current * node list is a list containing just the root node of the source * document." */ xpctxt->doc = ctxt->initialContextDoc; xpctxt->node = ctxt->initialContextNode; xpctxt->contextSize = 1; xpctxt->proximityPosition = 1; /* * There is really no in scope namespace for parameters on the * command line. */ xpctxt->namespaces = NULL; xpctxt->nsNr = 0; result = xmlXPathCompiledEval(xpExpr, xpctxt); /* * Restore Context states. */ xpctxt->doc = oldXPDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->namespaces = oldXPNamespaces; xpctxt->nsNr = oldXPNsNr; xmlXPathFreeCompExpr(xpExpr); } if (result == NULL) { xsltTransformError(ctxt, style, NULL, "Evaluating user parameter %s failed\n", name); ctxt->state = XSLT_STATE_STOPPED; return(-1); } } /* * If @eval is 0 then @value is to be taken literally and result is NULL * * If @eval is not 0, then @value is an XPath expression and has been * successfully evaluated and result contains the resulting value and * is not NULL. * * Now create an xsltStackElemPtr for insertion into the context's * global variable/parameter hash table. */ #ifdef WITH_XSLT_DEBUG_VARIABLE #ifdef LIBXML_DEBUG_ENABLED if ((xsltGenericDebugContext == stdout) || (xsltGenericDebugContext == stderr)) xmlXPathDebugDumpObject((FILE *)xsltGenericDebugContext, result, 0); #endif #endif elem = xsltNewStackElem(NULL); if (elem != NULL) { elem->name = name; elem->select = xmlDictLookup(ctxt->dict, value, -1); if (href != NULL) elem->nameURI = xmlDictLookup(ctxt->dict, href, -1); elem->tree = NULL; elem->computed = 1; if (eval == 0) { elem->value = xmlXPathNewString(value); } else { elem->value = result; } } /* * Global parameters are stored in the XPath context variables pool. */ res = xmlHashAddEntry2(ctxt->globalVars, name, href, elem); if (res != 0) { xsltFreeStackElem(elem); xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } 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
xsltProcessUserParamInternal(xsltTransformContextPtr ctxt, const xmlChar * name, const xmlChar * value, int eval) { xsltStylesheetPtr style; const xmlChar *prefix; const xmlChar *href; xmlXPathCompExprPtr xpExpr; xmlXPathObjectPtr result; xsltStackElemPtr elem; int res; void *res_ptr; if (ctxt == NULL) return(-1); if (name == NULL) return(0); if (value == NULL) return(0); style = ctxt->style; #ifdef WITH_XSLT_DEBUG_VARIABLE XSLT_TRACE(ctxt,XSLT_TRACE_VARIABLES,xsltGenericDebug(xsltGenericDebugContext, "Evaluating user parameter %s=%s\n", name, value)); #endif /* * Name lookup */ href = NULL; if (name[0] == '{') { int len = 0; while ((name[len] != 0) && (name[len] != '}')) len++; if (name[len] == 0) { xsltTransformError(ctxt, style, NULL, "user param : malformed parameter name : %s\n", name); } else { href = xmlDictLookup(ctxt->dict, &name[1], len-1); name = xmlDictLookup(ctxt->dict, &name[len + 1], -1); } } else { name = xsltSplitQName(ctxt->dict, name, &prefix); if (prefix != NULL) { xmlNsPtr ns; ns = xmlSearchNs(style->doc, xmlDocGetRootElement(style->doc), prefix); if (ns == NULL) { xsltTransformError(ctxt, style, NULL, "user param : no namespace bound to prefix %s\n", prefix); href = NULL; } else { href = ns->href; } } } if (name == NULL) return (-1); res_ptr = xmlHashLookup2(ctxt->globalVars, name, href); if (res_ptr != 0) { xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } if (ctxt->globalVars == NULL) ctxt->globalVars = xmlHashCreate(20); /* * do not overwrite variables with parameters from the command line */ while (style != NULL) { elem = ctxt->style->variables; while (elem != NULL) { if ((elem->comp != NULL) && (elem->comp->type == XSLT_FUNC_VARIABLE) && (xmlStrEqual(elem->name, name)) && (xmlStrEqual(elem->nameURI, href))) { return(0); } elem = elem->next; } style = xsltNextImport(style); } style = ctxt->style; elem = NULL; /* * Do the evaluation if @eval is non-zero. */ result = NULL; if (eval != 0) { xpExpr = xmlXPathCompile(value); if (xpExpr != NULL) { xmlDocPtr oldXPDoc; xmlNodePtr oldXPContextNode; int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; xmlNsPtr *oldXPNamespaces; xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; /* * Save context states. */ oldXPDoc = xpctxt->doc; oldXPContextNode = xpctxt->node; oldXPProximityPosition = xpctxt->proximityPosition; oldXPContextSize = xpctxt->contextSize; oldXPNamespaces = xpctxt->namespaces; oldXPNsNr = xpctxt->nsNr; /* * SPEC XSLT 1.0: * "At top-level, the expression or template specifying the * variable value is evaluated with the same context as that used * to process the root node of the source document: the current * node is the root node of the source document and the current * node list is a list containing just the root node of the source * document." */ xpctxt->doc = ctxt->initialContextDoc; xpctxt->node = ctxt->initialContextNode; xpctxt->contextSize = 1; xpctxt->proximityPosition = 1; /* * There is really no in scope namespace for parameters on the * command line. */ xpctxt->namespaces = NULL; xpctxt->nsNr = 0; result = xmlXPathCompiledEval(xpExpr, xpctxt); /* * Restore Context states. */ xpctxt->doc = oldXPDoc; xpctxt->node = oldXPContextNode; xpctxt->contextSize = oldXPContextSize; xpctxt->proximityPosition = oldXPProximityPosition; xpctxt->namespaces = oldXPNamespaces; xpctxt->nsNr = oldXPNsNr; xmlXPathFreeCompExpr(xpExpr); } if (result == NULL) { xsltTransformError(ctxt, style, NULL, "Evaluating user parameter %s failed\n", name); ctxt->state = XSLT_STATE_STOPPED; return(-1); } } /* * If @eval is 0 then @value is to be taken literally and result is NULL * * If @eval is not 0, then @value is an XPath expression and has been * successfully evaluated and result contains the resulting value and * is not NULL. * * Now create an xsltStackElemPtr for insertion into the context's * global variable/parameter hash table. */ #ifdef WITH_XSLT_DEBUG_VARIABLE #ifdef LIBXML_DEBUG_ENABLED if ((xsltGenericDebugContext == stdout) || (xsltGenericDebugContext == stderr)) xmlXPathDebugDumpObject((FILE *)xsltGenericDebugContext, result, 0); #endif #endif elem = xsltNewStackElem(NULL); if (elem != NULL) { elem->name = name; elem->select = xmlDictLookup(ctxt->dict, value, -1); if (href != NULL) elem->nameURI = xmlDictLookup(ctxt->dict, href, -1); elem->tree = NULL; elem->computed = 1; if (eval == 0) { elem->value = xmlXPathNewString(value); } else { elem->value = result; } } /* * Global parameters are stored in the XPath context variables pool. */ res = xmlHashAddEntry2(ctxt->globalVars, name, href, elem); if (res != 0) { xsltFreeStackElem(elem); xsltTransformError(ctxt, style, NULL, "Global parameter %s already defined\n", name); } return(0); }
173,332
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Bool FFD_CanHandleURL(GF_InputService *plug, const char *url) { Bool has_audio, has_video; s32 i; AVFormatContext *ctx; AVOutputFormat *fmt_out; Bool ret = GF_FALSE; char *ext, szName[1000], szExt[20]; const char *szExtList; FFDemux *ffd; if (!plug || !url) return GF_FALSE; /*disable RTP/RTSP from ffmpeg*/ if (!strnicmp(url, "rtsp://", 7)) return GF_FALSE; if (!strnicmp(url, "rtspu://", 8)) return GF_FALSE; if (!strnicmp(url, "rtp://", 6)) return GF_FALSE; if (!strnicmp(url, "plato://", 8)) return GF_FALSE; if (!strnicmp(url, "udp://", 6)) return GF_FALSE; if (!strnicmp(url, "tcp://", 6)) return GF_FALSE; if (!strnicmp(url, "data:", 5)) return GF_FALSE; ffd = (FFDemux*)plug->priv; strcpy(szName, url); ext = strrchr(szName, '#'); if (ext) ext[0] = 0; ext = strrchr(szName, '?'); if (ext) ext[0] = 0; ext = strrchr(szName, '.'); if (ext && strlen(ext) > 19) ext = NULL; if (ext && strlen(ext) > 1) { strcpy(szExt, &ext[1]); strlwr(szExt); #ifndef FFMPEG_DEMUX_ENABLE_MPEG2TS if (strstr("ts m2t mts dmb trp", szExt) ) return GF_FALSE; #endif /*note we forbid ffmpeg to handle files we support*/ if (!strcmp(szExt, "mp4") || !strcmp(szExt, "mpg4") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m21") || !strcmp(szExt, "m4v") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m4s") || !strcmp(szExt, "3gs") || !strcmp(szExt, "3gp") || !strcmp(szExt, "3gpp") || !strcmp(szExt, "3gp2") || !strcmp(szExt, "3g2") || !strcmp(szExt, "mp3") || !strcmp(szExt, "ac3") || !strcmp(szExt, "amr") || !strcmp(szExt, "bt") || !strcmp(szExt, "wrl") || !strcmp(szExt, "x3dv") || !strcmp(szExt, "xmt") || !strcmp(szExt, "xmta") || !strcmp(szExt, "x3d") || !strcmp(szExt, "jpg") || !strcmp(szExt, "jpeg") || !strcmp(szExt, "png") ) return GF_FALSE; /*check any default stuff that should work with ffmpeg*/ { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) { if (gf_service_check_mime_register(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2], ext)) return GF_TRUE; } } } ffd_parse_options(ffd, url); ctx = NULL; if (open_file(&ctx, szName, NULL, ffd->options ? &ffd->options : NULL)<0) { AVInputFormat *av_in = NULL; /*some extensions not supported by ffmpeg*/ if (ext && !strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v"); if (open_file(&ctx, szName, av_in, ffd->options ? &ffd->options : NULL)<0) { return GF_FALSE; } } if (!ctx) goto exit; if (av_find_stream_info(ctx) <0) goto exit; /*figure out if we can use codecs or not*/ has_video = has_audio = GF_FALSE; for(i = 0; i < (s32)ctx->nb_streams; i++) { AVCodecContext *enc = ctx->streams[i]->codec; switch(enc->codec_type) { case AVMEDIA_TYPE_AUDIO: if (!has_audio) has_audio = GF_TRUE; break; case AVMEDIA_TYPE_VIDEO: if (!has_video) has_video= GF_TRUE; break; default: break; } } if (!has_audio && !has_video) goto exit; ret = GF_TRUE; #if ((LIBAVFORMAT_VERSION_MAJOR == 52) && (LIBAVFORMAT_VERSION_MINOR <= 47)) || (LIBAVFORMAT_VERSION_MAJOR < 52) fmt_out = guess_stream_format(NULL, url, NULL); #else fmt_out = av_guess_format(NULL, url, NULL); #endif if (fmt_out) gf_service_register_mime(plug, fmt_out->mime_type, fmt_out->extensions, fmt_out->name); else { ext = strrchr(szName, '.'); if (ext) { strcpy(szExt, &ext[1]); strlwr(szExt); szExtList = gf_modules_get_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg"); if (!szExtList) { gf_service_register_mime(plug, "application/x-ffmpeg", szExt, "Other Movies (FFMPEG)"); } else if (!strstr(szExtList, szExt)) { u32 len; char *buf; len = (u32) (strlen(szExtList) + strlen(szExt) + 10); buf = (char*)gf_malloc(sizeof(char)*len); sprintf(buf, "\"%s ", szExt); strcat(buf, &szExtList[1]); gf_modules_set_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg", buf); gf_free(buf); } } } exit: #if FF_API_CLOSE_INPUT_FILE if (ctx) av_close_input_file(ctx); #else if (ctx) avformat_close_input(&ctx); #endif return ret; } Commit Message: fix some overflows due to strcpy fixes #1184, #1186, #1187 among other things CWE ID: CWE-119
static Bool FFD_CanHandleURL(GF_InputService *plug, const char *url) { Bool has_audio, has_video; s32 i; AVFormatContext *ctx; AVOutputFormat *fmt_out; Bool ret = GF_FALSE; char *ext, szName[1024], szExt[20]; const char *szExtList; FFDemux *ffd; if (!plug || !url) return GF_FALSE; /*disable RTP/RTSP from ffmpeg*/ if (!strnicmp(url, "rtsp://", 7)) return GF_FALSE; if (!strnicmp(url, "rtspu://", 8)) return GF_FALSE; if (!strnicmp(url, "rtp://", 6)) return GF_FALSE; if (!strnicmp(url, "plato://", 8)) return GF_FALSE; if (!strnicmp(url, "udp://", 6)) return GF_FALSE; if (!strnicmp(url, "tcp://", 6)) return GF_FALSE; if (!strnicmp(url, "data:", 5)) return GF_FALSE; ffd = (FFDemux*)plug->priv; if (strlen(url) >= sizeof(szName)) return GF_FALSE; strcpy(szName, url); ext = strrchr(szName, '#'); if (ext) ext[0] = 0; ext = strrchr(szName, '?'); if (ext) ext[0] = 0; ext = strrchr(szName, '.'); if (ext && strlen(ext) > 19) ext = NULL; if (ext && strlen(ext) > 1 && strlen(ext) <= sizeof(szExt)) { strcpy(szExt, &ext[1]); strlwr(szExt); #ifndef FFMPEG_DEMUX_ENABLE_MPEG2TS if (strstr("ts m2t mts dmb trp", szExt) ) return GF_FALSE; #endif /*note we forbid ffmpeg to handle files we support*/ if (!strcmp(szExt, "mp4") || !strcmp(szExt, "mpg4") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m21") || !strcmp(szExt, "m4v") || !strcmp(szExt, "m4a") || !strcmp(szExt, "m4s") || !strcmp(szExt, "3gs") || !strcmp(szExt, "3gp") || !strcmp(szExt, "3gpp") || !strcmp(szExt, "3gp2") || !strcmp(szExt, "3g2") || !strcmp(szExt, "mp3") || !strcmp(szExt, "ac3") || !strcmp(szExt, "amr") || !strcmp(szExt, "bt") || !strcmp(szExt, "wrl") || !strcmp(szExt, "x3dv") || !strcmp(szExt, "xmt") || !strcmp(szExt, "xmta") || !strcmp(szExt, "x3d") || !strcmp(szExt, "jpg") || !strcmp(szExt, "jpeg") || !strcmp(szExt, "png") ) return GF_FALSE; /*check any default stuff that should work with ffmpeg*/ { u32 i; for (i = 0 ; FFD_MIME_TYPES[i]; i+=3) { if (gf_service_check_mime_register(plug, FFD_MIME_TYPES[i], FFD_MIME_TYPES[i+1], FFD_MIME_TYPES[i+2], ext)) return GF_TRUE; } } } ffd_parse_options(ffd, url); ctx = NULL; if (open_file(&ctx, szName, NULL, ffd->options ? &ffd->options : NULL)<0) { AVInputFormat *av_in = NULL; /*some extensions not supported by ffmpeg*/ if (ext && !strcmp(szExt, "cmp")) av_in = av_find_input_format("m4v"); if (open_file(&ctx, szName, av_in, ffd->options ? &ffd->options : NULL)<0) { return GF_FALSE; } } if (!ctx) goto exit; if (av_find_stream_info(ctx) <0) goto exit; /*figure out if we can use codecs or not*/ has_video = has_audio = GF_FALSE; for(i = 0; i < (s32)ctx->nb_streams; i++) { AVCodecContext *enc = ctx->streams[i]->codec; switch(enc->codec_type) { case AVMEDIA_TYPE_AUDIO: if (!has_audio) has_audio = GF_TRUE; break; case AVMEDIA_TYPE_VIDEO: if (!has_video) has_video= GF_TRUE; break; default: break; } } if (!has_audio && !has_video) goto exit; ret = GF_TRUE; #if ((LIBAVFORMAT_VERSION_MAJOR == 52) && (LIBAVFORMAT_VERSION_MINOR <= 47)) || (LIBAVFORMAT_VERSION_MAJOR < 52) fmt_out = guess_stream_format(NULL, url, NULL); #else fmt_out = av_guess_format(NULL, url, NULL); #endif if (fmt_out) gf_service_register_mime(plug, fmt_out->mime_type, fmt_out->extensions, fmt_out->name); else { ext = strrchr(szName, '.'); if (ext) { strcpy(szExt, &ext[1]); strlwr(szExt); szExtList = gf_modules_get_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg"); if (!szExtList) { gf_service_register_mime(plug, "application/x-ffmpeg", szExt, "Other Movies (FFMPEG)"); } else if (!strstr(szExtList, szExt)) { u32 len; char *buf; len = (u32) (strlen(szExtList) + strlen(szExt) + 10); buf = (char*)gf_malloc(sizeof(char)*len); sprintf(buf, "\"%s ", szExt); strcat(buf, &szExtList[1]); gf_modules_set_option((GF_BaseInterface *)plug, "MimeTypes", "application/x-ffmpeg", buf); gf_free(buf); } } } exit: #if FF_API_CLOSE_INPUT_FILE if (ctx) av_close_input_file(ctx); #else if (ctx) avformat_close_input(&ctx); #endif return ret; }
169,792
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDAT_list_extend(struct IDAT_list *tail) { /* Use the previous cached value if available. */ struct IDAT_list *next = tail->next; if (next == NULL) { /* Insert a new, malloc'ed, block of IDAT information buffers, this * one twice as large as the previous one: */ unsigned int length = 2 * tail->length; if (length < tail->length) /* arithmetic overflow */ length = tail->length; next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length))); CLEAR(*next); /* The caller must handle this: */ if (next == NULL) return NULL; next->next = NULL; next->length = length; tail->next = next; } return next; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
IDAT_list_extend(struct IDAT_list *tail) { /* Use the previous cached value if available. */ struct IDAT_list *next = tail->next; if (next == NULL) { /* Insert a new, malloc'ed, block of IDAT information buffers, this * one twice as large as the previous one: */ unsigned int length = 2 * tail->length; if (length < tail->length) /* arithmetic overflow */ length = tail->length; next = voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length))); CLEAR(*next); /* The caller must handle this: */ if (next == NULL) return NULL; next->next = NULL; next->length = length; tail->next = next; } return next; }
173,728
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: resetLppTransposer (HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer */ UCHAR highBandStartSb, /*!< High band area: start subband */ UCHAR *v_k_master, /*!< Master table */ UCHAR numMaster, /*!< Valid entries in master table */ UCHAR *noiseBandTable, /*!< Mapping of SBR noise bands to QMF bands */ UCHAR noNoiseBands, /*!< Number of noise bands */ UCHAR usb, /*!< High band area: stop subband */ UINT fs /*!< SBR output sampling frequency */ ) { TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings; PATCH_PARAM *patchParam = pSettings->patchParam; int i, patch; int targetStopBand; int sourceStartBand; int patchDistance; int numBandsInPatch; int lsb = v_k_master[0]; /* Start subband expressed in "non-critical" sampling terms*/ int xoverOffset = highBandStartSb - lsb; /* Calculate distance in QMF bands between k0 and kx */ int startFreqHz; int desiredBorder; usb = fixMin(usb, v_k_master[numMaster]); /* Avoid endless loops (compare with float code). */ /* * Plausibility check */ if ( lsb - SHIFT_START_SB < 4 ) { return SBRDEC_UNSUPPORTED_CONFIG; } /* * Initialize the patching parameter */ /* ISO/IEC 14496-3 (Figure 4.48): goalSb = round( 2.048e6 / fs ) */ desiredBorder = (((2048000*2) / fs) + 1) >> 1; desiredBorder = findClosestEntry(desiredBorder, v_k_master, numMaster, 1); /* Adapt region to master-table */ /* First patch */ sourceStartBand = SHIFT_START_SB + xoverOffset; targetStopBand = lsb + xoverOffset; /* upperBand */ /* Even (odd) numbered channel must be patched to even (odd) numbered channel */ patch = 0; while(targetStopBand < usb) { /* Too many patches? Allow MAX_NUM_PATCHES+1 patches here. we need to check later again, since patch might be the highest patch AND contain less than 3 bands => actual number of patches will be reduced by 1. */ if (patch > MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } patchParam[patch].guardStartBand = targetStopBand; patchParam[patch].targetStartBand = targetStopBand; numBandsInPatch = desiredBorder - targetStopBand; /* Get the desired range of the patch */ if ( numBandsInPatch >= lsb - sourceStartBand ) { /* Desired number bands are not available -> patch whole source range */ patchDistance = targetStopBand - sourceStartBand; /* Get the targetOffset */ patchDistance = patchDistance & ~1; /* Rounding off odd numbers and make all even */ numBandsInPatch = lsb - (targetStopBand - patchDistance); /* Update number of bands to be patched */ numBandsInPatch = findClosestEntry(targetStopBand + numBandsInPatch, v_k_master, numMaster, 0) - targetStopBand; /* Adapt region to master-table */ } /* Desired number bands are available -> get the minimal even patching distance */ patchDistance = numBandsInPatch + targetStopBand - lsb; /* Get minimal distance */ patchDistance = (patchDistance + 1) & ~1; /* Rounding up odd numbers and make all even */ if (numBandsInPatch > 0) { patchParam[patch].sourceStartBand = targetStopBand - patchDistance; patchParam[patch].targetBandOffs = patchDistance; patchParam[patch].numBandsInPatch = numBandsInPatch; patchParam[patch].sourceStopBand = patchParam[patch].sourceStartBand + numBandsInPatch; targetStopBand += patchParam[patch].numBandsInPatch; patch++; } /* All patches but first */ sourceStartBand = SHIFT_START_SB; /* Check if we are close to desiredBorder */ if( desiredBorder - targetStopBand < 3) /* MPEG doc */ { desiredBorder = usb; } } patch--; /* If highest patch contains less than three subband: skip it */ if ( (patch>0) && (patchParam[patch].numBandsInPatch < 3) ) { patch--; targetStopBand = patchParam[patch].targetStartBand + patchParam[patch].numBandsInPatch; } /* now check if we don't have one too many */ if (patch >= MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } pSettings->noOfPatches = patch + 1; /* Check lowest and highest source subband */ pSettings->lbStartPatching = targetStopBand; pSettings->lbStopPatching = 0; for ( patch = 0; patch < pSettings->noOfPatches; patch++ ) { pSettings->lbStartPatching = fixMin( pSettings->lbStartPatching, patchParam[patch].sourceStartBand ); pSettings->lbStopPatching = fixMax( pSettings->lbStopPatching, patchParam[patch].sourceStopBand ); } for(i = 0 ; i < noNoiseBands; i++){ pSettings->bwBorders[i] = noiseBandTable[i+1]; } /* * Choose whitening factors */ startFreqHz = ( (lsb + xoverOffset)*fs ) >> 7; /* Shift does a division by 2*(64) */ for( i = 1; i < NUM_WHFACTOR_TABLE_ENTRIES; i++ ) { if( startFreqHz < FDK_sbrDecoder_sbr_whFactorsIndex[i]) break; } i--; pSettings->whFactors.off = FDK_sbrDecoder_sbr_whFactorsTable[i][0]; pSettings->whFactors.transitionLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][1]; pSettings->whFactors.lowLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][2]; pSettings->whFactors.midLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][3]; pSettings->whFactors.highLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][4]; return SBRDEC_OK; } Commit Message: Fix out of bound memory access in lppTransposer In TRANSPOSER_SETTINGS, initialize the whole bwBorders array to a reasonable value to guarantee correct termination in while loop in lppTransposer function. This fixes the reported bug. For completeness: - clear the whole bwIndex array instead of noOfPatches entries only. - abort criterion in while loop to prevent potential infinite loop, and limit bwIndex[patch] to a valid range. Test: see bug for malicious content, decoded with "stagefright -s -a" Bug: 65280786 Change-Id: I16ed2e1c0f1601926239a652ca20a91284151843 (cherry picked from commit 6d3dd40e204bf550abcfa589bd9615df8778e118) CWE ID: CWE-200
resetLppTransposer (HANDLE_SBR_LPP_TRANS hLppTrans, /*!< Handle of lpp transposer */ UCHAR highBandStartSb, /*!< High band area: start subband */ UCHAR *v_k_master, /*!< Master table */ UCHAR numMaster, /*!< Valid entries in master table */ UCHAR *noiseBandTable, /*!< Mapping of SBR noise bands to QMF bands */ UCHAR noNoiseBands, /*!< Number of noise bands */ UCHAR usb, /*!< High band area: stop subband */ UINT fs /*!< SBR output sampling frequency */ ) { TRANSPOSER_SETTINGS *pSettings = hLppTrans->pSettings; PATCH_PARAM *patchParam = pSettings->patchParam; int i, patch; int targetStopBand; int sourceStartBand; int patchDistance; int numBandsInPatch; int lsb = v_k_master[0]; /* Start subband expressed in "non-critical" sampling terms*/ int xoverOffset = highBandStartSb - lsb; /* Calculate distance in QMF bands between k0 and kx */ int startFreqHz; int desiredBorder; usb = fixMin(usb, v_k_master[numMaster]); /* Avoid endless loops (compare with float code). */ /* * Plausibility check */ if ( lsb - SHIFT_START_SB < 4 ) { return SBRDEC_UNSUPPORTED_CONFIG; } /* * Initialize the patching parameter */ /* ISO/IEC 14496-3 (Figure 4.48): goalSb = round( 2.048e6 / fs ) */ desiredBorder = (((2048000*2) / fs) + 1) >> 1; desiredBorder = findClosestEntry(desiredBorder, v_k_master, numMaster, 1); /* Adapt region to master-table */ /* First patch */ sourceStartBand = SHIFT_START_SB + xoverOffset; targetStopBand = lsb + xoverOffset; /* upperBand */ /* Even (odd) numbered channel must be patched to even (odd) numbered channel */ patch = 0; while(targetStopBand < usb) { /* Too many patches? Allow MAX_NUM_PATCHES+1 patches here. we need to check later again, since patch might be the highest patch AND contain less than 3 bands => actual number of patches will be reduced by 1. */ if (patch > MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } patchParam[patch].guardStartBand = targetStopBand; patchParam[patch].targetStartBand = targetStopBand; numBandsInPatch = desiredBorder - targetStopBand; /* Get the desired range of the patch */ if ( numBandsInPatch >= lsb - sourceStartBand ) { /* Desired number bands are not available -> patch whole source range */ patchDistance = targetStopBand - sourceStartBand; /* Get the targetOffset */ patchDistance = patchDistance & ~1; /* Rounding off odd numbers and make all even */ numBandsInPatch = lsb - (targetStopBand - patchDistance); /* Update number of bands to be patched */ numBandsInPatch = findClosestEntry(targetStopBand + numBandsInPatch, v_k_master, numMaster, 0) - targetStopBand; /* Adapt region to master-table */ } /* Desired number bands are available -> get the minimal even patching distance */ patchDistance = numBandsInPatch + targetStopBand - lsb; /* Get minimal distance */ patchDistance = (patchDistance + 1) & ~1; /* Rounding up odd numbers and make all even */ if (numBandsInPatch > 0) { patchParam[patch].sourceStartBand = targetStopBand - patchDistance; patchParam[patch].targetBandOffs = patchDistance; patchParam[patch].numBandsInPatch = numBandsInPatch; patchParam[patch].sourceStopBand = patchParam[patch].sourceStartBand + numBandsInPatch; targetStopBand += patchParam[patch].numBandsInPatch; patch++; } /* All patches but first */ sourceStartBand = SHIFT_START_SB; /* Check if we are close to desiredBorder */ if( desiredBorder - targetStopBand < 3) /* MPEG doc */ { desiredBorder = usb; } } patch--; /* If highest patch contains less than three subband: skip it */ if ( (patch>0) && (patchParam[patch].numBandsInPatch < 3) ) { patch--; targetStopBand = patchParam[patch].targetStartBand + patchParam[patch].numBandsInPatch; } /* now check if we don't have one too many */ if (patch >= MAX_NUM_PATCHES) { return SBRDEC_UNSUPPORTED_CONFIG; } pSettings->noOfPatches = patch + 1; /* Check lowest and highest source subband */ pSettings->lbStartPatching = targetStopBand; pSettings->lbStopPatching = 0; for ( patch = 0; patch < pSettings->noOfPatches; patch++ ) { pSettings->lbStartPatching = fixMin( pSettings->lbStartPatching, patchParam[patch].sourceStartBand ); pSettings->lbStopPatching = fixMax( pSettings->lbStopPatching, patchParam[patch].sourceStopBand ); } for(i = 0 ; i < noNoiseBands; i++){ pSettings->bwBorders[i] = noiseBandTable[i+1]; } for (;i < MAX_NUM_NOISE_VALUES; i++) { pSettings->bwBorders[i] = 255; } /* * Choose whitening factors */ startFreqHz = ( (lsb + xoverOffset)*fs ) >> 7; /* Shift does a division by 2*(64) */ for( i = 1; i < NUM_WHFACTOR_TABLE_ENTRIES; i++ ) { if( startFreqHz < FDK_sbrDecoder_sbr_whFactorsIndex[i]) break; } i--; pSettings->whFactors.off = FDK_sbrDecoder_sbr_whFactorsTable[i][0]; pSettings->whFactors.transitionLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][1]; pSettings->whFactors.lowLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][2]; pSettings->whFactors.midLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][3]; pSettings->whFactors.highLevel = FDK_sbrDecoder_sbr_whFactorsTable[i][4]; return SBRDEC_OK; }
174,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void queue_delete(struct snd_seq_queue *q) { /* stop and release the timer */ snd_seq_timer_stop(q->timer); snd_seq_timer_close(q); /* wait until access free */ snd_use_lock_sync(&q->use_lock); /* release resources... */ snd_seq_prioq_delete(&q->tickq); snd_seq_prioq_delete(&q->timeq); snd_seq_timer_delete(&q->timer); kfree(q); } Commit Message: ALSA: seq: Fix race at timer setup and close ALSA sequencer code has an open race between the timer setup ioctl and the close of the client. This was triggered by syzkaller fuzzer, and a use-after-free was caught there as a result. This patch papers over it by adding a proper queue->timer_mutex lock around the timer-related calls in the relevant code path. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362
static void queue_delete(struct snd_seq_queue *q) { /* stop and release the timer */ mutex_lock(&q->timer_mutex); snd_seq_timer_stop(q->timer); snd_seq_timer_close(q); mutex_unlock(&q->timer_mutex); /* wait until access free */ snd_use_lock_sync(&q->use_lock); /* release resources... */ snd_seq_prioq_delete(&q->tickq); snd_seq_prioq_delete(&q->timeq); snd_seq_timer_delete(&q->timer); kfree(q); }
167,409
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_accept_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret, tmpmin, negState; send_token_flag return_token; gss_buffer_t mechtok_in, mic_in, mic_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_ctx_id_t sc = NULL; spnego_gss_cred_id_t spcred = NULL; int sendTokenInit = 0, tmpret; mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated mech's gss_accept_sec_context function * and examine the results. * 3. Process or generate MICs if necessary. * * Step one determines whether the negotiation requires a MIC exchange, * while steps two and three share responsibility for determining when * the exchange is complete. If the selected mech completes in this * call and no MIC exchange is expected, then step 2 will decide. If a * MIC exchange is expected, then step 3 will decide. If an error * occurs in any step, the exchange will be aborted, possibly with an * error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * return_token is used to indicate what type of token, if any, should * be generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (input_token == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ; /* Step 1: Perform mechanism negotiation. */ sc = (spnego_gss_ctx_id_t)*context_handle; spcred = (spnego_gss_cred_id_t)verifier_cred_handle; if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) { /* Process an initial token or request for NegHints. */ if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (time_rec != NULL) *time_rec = 0; if (ret_flags != NULL) *ret_flags = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (input_token->length == 0) { ret = acc_ctx_hints(minor_status, context_handle, spcred, &mic_out, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; sendTokenInit = 1; ret = GSS_S_CONTINUE_NEEDED; } else { /* Can set negState to REQUEST_MIC */ ret = acc_ctx_new(minor_status, input_token, context_handle, spcred, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } } else { /* Process a response token. Can set negState to * ACCEPT_INCOMPLETE. */ ret = acc_ctx_cont(minor_status, input_token, context_handle, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } /* Step 2: invoke the negotiated mechanism's gss_accept_sec_context * function. */ sc = (spnego_gss_ctx_id_t)*context_handle; /* * Handle mechtok_in and mic_in only if they are * present in input_token. If neither is present, whether * this is an error depends on whether this is the first * round-trip. RET is set to a default value according to * whether it is the first round-trip. */ if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) { ret = acc_ctx_call_acc(minor_status, sc, spcred, mechtok_in, mech_type, &mechtok_out, ret_flags, time_rec, delegated_cred_handle, &negState, &return_token); } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && sc->mech_complete && (sc->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mic_in, (mechtok_out.length != 0), sc, &mic_out, &negState, &return_token); } cleanup: if (return_token == INIT_TOKEN_SEND && sendTokenInit) { assert(sc != NULL); tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0, GSS_C_NO_BUFFER, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } else if (return_token != NO_TOKEN_SEND && return_token != CHECK_MIC) { tmpret = make_spnego_tokenTarg_msg(negState, sc ? sc->internal_mech : GSS_C_NO_OID, &mechtok_out, mic_out, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } if (ret == GSS_S_COMPLETE) { *context_handle = (gss_ctx_id_t)sc->ctx_handle; if (sc->internal_name != GSS_C_NO_NAME && src_name != NULL) { *src_name = sc->internal_name; sc->internal_name = GSS_C_NO_NAME; } release_spnego_ctx(&sc); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (sc != NULL) { gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&sc); } *context_handle = GSS_C_NO_CONTEXT; } gss_release_buffer(&tmpmin, &mechtok_out); if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mic_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_in); free(mic_in); } if (mic_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_out); free(mic_out); } return ret; } Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695] The SPNEGO mechanism currently replaces its context handle with the mechanism context handle upon establishment, under the assumption that most GSS functions are only called after context establishment. This assumption is incorrect, and can lead to aliasing violations for some programs. Maintain the SPNEGO context structure after context establishment and refer to it in all GSS methods. Add initiate and opened flags to the SPNEGO context structure for use in gss_inquire_context() prior to context establishment. CVE-2015-2695: In MIT krb5 1.5 and later, applications which call gss_inquire_context() on a partially-established SPNEGO context can cause the GSS-API library to read from a pointer using the wrong type, generally causing a process crash. This bug may go unnoticed, because the most common SPNEGO authentication scenario establishes the context after just one call to gss_accept_sec_context(). Java server applications using the native JGSS provider are vulnerable to this bug. A carefully crafted SPNEGO packet might allow the gss_inquire_context() call to succeed with attacker-determined results, but applications should not make access control decisions based on gss_inquire_context() results prior to context establishment. CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C [[email protected]: several bugfixes, style changes, and edge-case behavior changes; commit message and CVE description] ticket: 8244 target_version: 1.14 tags: pullup CWE ID: CWE-18
spnego_gss_accept_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret, tmpmin, negState; send_token_flag return_token; gss_buffer_t mechtok_in, mic_in, mic_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_ctx_id_t sc = NULL; spnego_gss_cred_id_t spcred = NULL; int sendTokenInit = 0, tmpret; mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated mech's gss_accept_sec_context function * and examine the results. * 3. Process or generate MICs if necessary. * * Step one determines whether the negotiation requires a MIC exchange, * while steps two and three share responsibility for determining when * the exchange is complete. If the selected mech completes in this * call and no MIC exchange is expected, then step 2 will decide. If a * MIC exchange is expected, then step 3 will decide. If an error * occurs in any step, the exchange will be aborted, possibly with an * error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * return_token is used to indicate what type of token, if any, should * be generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (input_token == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ; /* Step 1: Perform mechanism negotiation. */ sc = (spnego_gss_ctx_id_t)*context_handle; spcred = (spnego_gss_cred_id_t)verifier_cred_handle; if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) { /* Process an initial token or request for NegHints. */ if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (time_rec != NULL) *time_rec = 0; if (ret_flags != NULL) *ret_flags = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (input_token->length == 0) { ret = acc_ctx_hints(minor_status, context_handle, spcred, &mic_out, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; sendTokenInit = 1; ret = GSS_S_CONTINUE_NEEDED; } else { /* Can set negState to REQUEST_MIC */ ret = acc_ctx_new(minor_status, input_token, context_handle, spcred, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } } else { /* Process a response token. Can set negState to * ACCEPT_INCOMPLETE. */ ret = acc_ctx_cont(minor_status, input_token, context_handle, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } /* Step 2: invoke the negotiated mechanism's gss_accept_sec_context * function. */ sc = (spnego_gss_ctx_id_t)*context_handle; /* * Handle mechtok_in and mic_in only if they are * present in input_token. If neither is present, whether * this is an error depends on whether this is the first * round-trip. RET is set to a default value according to * whether it is the first round-trip. */ if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) { ret = acc_ctx_call_acc(minor_status, sc, spcred, mechtok_in, mech_type, &mechtok_out, ret_flags, time_rec, delegated_cred_handle, &negState, &return_token); } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && sc->mech_complete && (sc->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mic_in, (mechtok_out.length != 0), sc, &mic_out, &negState, &return_token); } cleanup: if (return_token == INIT_TOKEN_SEND && sendTokenInit) { assert(sc != NULL); tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0, GSS_C_NO_BUFFER, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } else if (return_token != NO_TOKEN_SEND && return_token != CHECK_MIC) { tmpret = make_spnego_tokenTarg_msg(negState, sc ? sc->internal_mech : GSS_C_NO_OID, &mechtok_out, mic_out, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } if (ret == GSS_S_COMPLETE) { sc->opened = 1; if (sc->internal_name != GSS_C_NO_NAME && src_name != NULL) { *src_name = sc->internal_name; sc->internal_name = GSS_C_NO_NAME; } } else if (ret != GSS_S_CONTINUE_NEEDED) { if (sc != NULL) { gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&sc); } *context_handle = GSS_C_NO_CONTEXT; } gss_release_buffer(&tmpmin, &mechtok_out); if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mic_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_in); free(mic_in); } if (mic_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_out); free(mic_out); } return ret; }
166,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebContentsImpl::CreateNewWindow( RenderFrameHost* opener, int32_t render_view_route_id, int32_t main_frame_route_id, int32_t main_frame_widget_route_id, const mojom::CreateNewWindowParams& params, SessionStorageNamespace* session_storage_namespace) { DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_route_id == MSG_ROUTING_NONE)); DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_widget_route_id == MSG_ROUTING_NONE)); DCHECK(opener); int render_process_id = opener->GetProcess()->GetID(); SiteInstance* source_site_instance = opener->GetSiteInstance(); DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id)); bool is_guest = BrowserPluginGuest::IsGuest(this); DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE); scoped_refptr<SiteInstance> site_instance = params.opener_suppressed && !is_guest ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) : source_site_instance; const std::string& partition_id = GetContentClient()->browser()-> GetStoragePartitionIdForSite(GetBrowserContext(), site_instance->GetSiteURL()); StoragePartition* partition = BrowserContext::GetStoragePartition( GetBrowserContext(), site_instance.get()); DOMStorageContextWrapper* dom_storage_context = static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext()); SessionStorageNamespaceImpl* session_storage_namespace_impl = static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace); CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context)); if (delegate_ && !delegate_->ShouldCreateWebContents( this, opener, source_site_instance, render_view_route_id, main_frame_route_id, main_frame_widget_route_id, params.window_container_type, opener->GetLastCommittedURL(), params.frame_name, params.target_url, partition_id, session_storage_namespace)) { RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id); if (rfh) { DCHECK(rfh->IsRenderFrameLive()); rfh->Init(); } return; } CreateParams create_params(GetBrowserContext(), site_instance.get()); create_params.routing_id = render_view_route_id; create_params.main_frame_routing_id = main_frame_route_id; create_params.main_frame_widget_routing_id = main_frame_widget_route_id; create_params.main_frame_name = params.frame_name; create_params.opener_render_process_id = render_process_id; create_params.opener_render_frame_id = opener->GetRoutingID(); create_params.opener_suppressed = params.opener_suppressed; if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) create_params.initially_hidden = true; create_params.renderer_initiated_creation = main_frame_route_id != MSG_ROUTING_NONE; WebContentsImpl* new_contents = NULL; if (!is_guest) { create_params.context = view_->GetNativeView(); create_params.initial_size = GetContainerBounds().size(); new_contents = static_cast<WebContentsImpl*>( WebContents::Create(create_params)); } else { new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params); } new_contents->GetController().SetSessionStorageNamespace( partition_id, session_storage_namespace); if (!params.frame_name.empty()) new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame(); if (!params.opener_suppressed) { if (!is_guest) { WebContentsView* new_view = new_contents->view_.get(); new_view->CreateViewForWidget( new_contents->GetRenderViewHost()->GetWidget(), false); } DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id); pending_contents_[std::make_pair( render_process_id, main_frame_widget_route_id)] = new_contents; AddDestructionObserver(new_contents); } if (delegate_) { delegate_->WebContentsCreated(this, render_process_id, opener->GetRoutingID(), params.frame_name, params.target_url, new_contents); } if (opener) { for (auto& observer : observers_) { observer.DidOpenRequestedURL(new_contents, opener, params.target_url, params.referrer, params.disposition, ui::PAGE_TRANSITION_LINK, false, // started_from_context_menu true); // renderer_initiated } } if (params.opener_suppressed) { bool was_blocked = false; if (delegate_) { gfx::Rect initial_rect; base::WeakPtr<WebContentsImpl> weak_new_contents = new_contents->weak_factory_.GetWeakPtr(); delegate_->AddNewContents( this, new_contents, params.disposition, initial_rect, params.user_gesture, &was_blocked); if (!weak_new_contents) return; // The delegate deleted |new_contents| during AddNewContents(). } if (!was_blocked) { OpenURLParams open_params(params.target_url, params.referrer, WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */); open_params.user_gesture = params.user_gesture; if (delegate_ && !is_guest && !delegate_->ShouldResumeRequestsForCreatedWindow()) { new_contents->delayed_open_url_params_.reset( new OpenURLParams(open_params)); } else { new_contents->OpenURL(open_params); } } } } Commit Message: If a page shows a popup, end fullscreen. This was implemented in Blink r159834, but it is susceptible to a popup/fullscreen race. This CL reverts that implementation and re-implements it in WebContents. BUG=752003 TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f Reviewed-on: https://chromium-review.googlesource.com/606987 Commit-Queue: Avi Drissman <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Cr-Commit-Position: refs/heads/master@{#498171} CWE ID: CWE-20
void WebContentsImpl::CreateNewWindow( RenderFrameHost* opener, int32_t render_view_route_id, int32_t main_frame_route_id, int32_t main_frame_widget_route_id, const mojom::CreateNewWindowParams& params, SessionStorageNamespace* session_storage_namespace) { DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_route_id == MSG_ROUTING_NONE)); DCHECK_EQ((render_view_route_id == MSG_ROUTING_NONE), (main_frame_widget_route_id == MSG_ROUTING_NONE)); DCHECK(opener); int render_process_id = opener->GetProcess()->GetID(); SiteInstance* source_site_instance = opener->GetSiteInstance(); DCHECK(!RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id)); bool is_guest = BrowserPluginGuest::IsGuest(this); DCHECK(!params.opener_suppressed || render_view_route_id == MSG_ROUTING_NONE); scoped_refptr<SiteInstance> site_instance = params.opener_suppressed && !is_guest ? SiteInstance::CreateForURL(GetBrowserContext(), params.target_url) : source_site_instance; const std::string& partition_id = GetContentClient()->browser()-> GetStoragePartitionIdForSite(GetBrowserContext(), site_instance->GetSiteURL()); StoragePartition* partition = BrowserContext::GetStoragePartition( GetBrowserContext(), site_instance.get()); DOMStorageContextWrapper* dom_storage_context = static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext()); SessionStorageNamespaceImpl* session_storage_namespace_impl = static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace); CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context)); if (delegate_ && !delegate_->ShouldCreateWebContents( this, opener, source_site_instance, render_view_route_id, main_frame_route_id, main_frame_widget_route_id, params.window_container_type, opener->GetLastCommittedURL(), params.frame_name, params.target_url, partition_id, session_storage_namespace)) { RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id, main_frame_route_id); if (rfh) { DCHECK(rfh->IsRenderFrameLive()); rfh->Init(); } return; } CreateParams create_params(GetBrowserContext(), site_instance.get()); create_params.routing_id = render_view_route_id; create_params.main_frame_routing_id = main_frame_route_id; create_params.main_frame_widget_routing_id = main_frame_widget_route_id; create_params.main_frame_name = params.frame_name; create_params.opener_render_process_id = render_process_id; create_params.opener_render_frame_id = opener->GetRoutingID(); create_params.opener_suppressed = params.opener_suppressed; if (params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB) create_params.initially_hidden = true; create_params.renderer_initiated_creation = main_frame_route_id != MSG_ROUTING_NONE; WebContentsImpl* new_contents = NULL; if (!is_guest) { create_params.context = view_->GetNativeView(); create_params.initial_size = GetContainerBounds().size(); new_contents = static_cast<WebContentsImpl*>( WebContents::Create(create_params)); } else { new_contents = GetBrowserPluginGuest()->CreateNewGuestWindow(create_params); } new_contents->GetController().SetSessionStorageNamespace( partition_id, session_storage_namespace); if (!params.frame_name.empty()) new_contents->GetRenderManager()->CreateProxiesForNewNamedFrame(); if (!params.opener_suppressed) { if (!is_guest) { WebContentsView* new_view = new_contents->view_.get(); new_view->CreateViewForWidget( new_contents->GetRenderViewHost()->GetWidget(), false); } DCHECK_NE(MSG_ROUTING_NONE, main_frame_widget_route_id); pending_contents_[std::make_pair( render_process_id, main_frame_widget_route_id)] = new_contents; AddDestructionObserver(new_contents); } if (delegate_) { delegate_->WebContentsCreated(this, render_process_id, opener->GetRoutingID(), params.frame_name, params.target_url, new_contents); } if (opener) { for (auto& observer : observers_) { observer.DidOpenRequestedURL(new_contents, opener, params.target_url, params.referrer, params.disposition, ui::PAGE_TRANSITION_LINK, false, // started_from_context_menu true); // renderer_initiated } } // Any new WebContents opened while this WebContents is in fullscreen can be // used to confuse the user, so drop fullscreen. if (IsFullscreenForCurrentTab()) ExitFullscreen(true); if (params.opener_suppressed) { bool was_blocked = false; if (delegate_) { gfx::Rect initial_rect; base::WeakPtr<WebContentsImpl> weak_new_contents = new_contents->weak_factory_.GetWeakPtr(); delegate_->AddNewContents( this, new_contents, params.disposition, initial_rect, params.user_gesture, &was_blocked); if (!weak_new_contents) return; // The delegate deleted |new_contents| during AddNewContents(). } if (!was_blocked) { OpenURLParams open_params(params.target_url, params.referrer, WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_LINK, true /* is_renderer_initiated */); open_params.user_gesture = params.user_gesture; if (delegate_ && !is_guest && !delegate_->ShouldResumeRequestsForCreatedWindow()) { new_contents->delayed_open_url_params_.reset( new OpenURLParams(open_params)); } else { new_contents->OpenURL(open_params); } } } }
172,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; int64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == -1 && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119
static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect) { HTTPContext *s = h->priv_data; URLContext *old_hd = s->hd; uint64_t old_off = s->off; uint8_t old_buf[BUFFER_SIZE]; int old_buf_size, ret; AVDictionary *options = NULL; if (whence == AVSEEK_SIZE) return s->filesize; else if (!force_reconnect && ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))) return s->off; else if ((s->filesize == UINT64_MAX && whence == SEEK_END)) return AVERROR(ENOSYS); if (whence == SEEK_CUR) off += s->off; else if (whence == SEEK_END) off += s->filesize; else if (whence != SEEK_SET) return AVERROR(EINVAL); if (off < 0) return AVERROR(EINVAL); s->off = off; if (s->off && h->is_streamed) return AVERROR(ENOSYS); /* we save the old context in case the seek fails */ old_buf_size = s->buf_end - s->buf_ptr; memcpy(old_buf, s->buf_ptr, old_buf_size); s->hd = NULL; /* if it fails, continue on old connection */ if ((ret = http_open_cnx(h, &options)) < 0) { av_dict_free(&options); memcpy(s->buffer, old_buf, old_buf_size); s->buf_ptr = s->buffer; s->buf_end = s->buffer + old_buf_size; s->hd = old_hd; s->off = old_off; return ret; } av_dict_free(&options); ffurl_close(old_hd); return off; }
168,502
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) { if (HasTextBeingDragged()) return ui::DragDropTypes::DRAG_NONE; if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) { GURL url; base::string16 title; if (data.GetURLAndTitle( ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) { base::string16 text( StripJavascriptSchemas(base::UTF8ToUTF16(url.spec()))); if (model()->CanPasteAndGo(text)) { model()->PasteAndGo(text); return ui::DragDropTypes::DRAG_COPY; } } } else if (data.HasString()) { base::string16 text; if (data.GetString(&text)) { base::string16 collapsed_text(base::CollapseWhitespace(text, true)); if (model()->CanPasteAndGo(collapsed_text)) model()->PasteAndGo(collapsed_text); return ui::DragDropTypes::DRAG_COPY; } } return ui::DragDropTypes::DRAG_NONE; } Commit Message: Strip JavaScript schemas on Linux text drop When dropping text onto the Omnibox, any leading JavaScript schemes should be stripped to avoid a "self-XSS" attack. This stripping already occurs in all cases except when plaintext is dropped on Linux. This CL corrects that oversight. Bug: 768910 Change-Id: I43af24ace4a13cf61d15a32eb9382dcdd498a062 Reviewed-on: https://chromium-review.googlesource.com/685638 Reviewed-by: Justin Donnelly <[email protected]> Commit-Queue: Eric Lawrence <[email protected]> Cr-Commit-Position: refs/heads/master@{#504695} CWE ID: CWE-79
int OmniboxViewViews::OnDrop(const ui::OSExchangeData& data) { if (HasTextBeingDragged()) return ui::DragDropTypes::DRAG_NONE; if (data.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)) { GURL url; base::string16 title; if (data.GetURLAndTitle( ui::OSExchangeData::CONVERT_FILENAMES, &url, &title)) { base::string16 text( StripJavascriptSchemas(base::UTF8ToUTF16(url.spec()))); if (model()->CanPasteAndGo(text)) { model()->PasteAndGo(text); return ui::DragDropTypes::DRAG_COPY; } } } else if (data.HasString()) { base::string16 text; if (data.GetString(&text)) { base::string16 collapsed_text( StripJavascriptSchemas(base::CollapseWhitespace(text, true))); if (model()->CanPasteAndGo(collapsed_text)) model()->PasteAndGo(collapsed_text); return ui::DragDropTypes::DRAG_COPY; } } return ui::DragDropTypes::DRAG_NONE; }
172,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AudioRendererAlgorithm::OutputFasterPlayback(uint8* dest) { DCHECK_LT(index_into_window_, window_size_); DCHECK_GT(playback_rate_, 1.0); if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; int input_step = window_size_; int output_step = ceil(window_size_ / playback_rate_); AlignToFrameBoundary(&output_step); DCHECK_GT(input_step, output_step); int bytes_to_crossfade = bytes_in_crossfade_; if (muted_ || bytes_to_crossfade > output_step) bytes_to_crossfade = 0; int outtro_crossfade_begin = output_step - bytes_to_crossfade; int outtro_crossfade_end = output_step; int intro_crossfade_begin = input_step - bytes_to_crossfade; if (index_into_window_ < outtro_crossfade_begin) { CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } while (index_into_window_ < outtro_crossfade_end) { if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; DCHECK_GT(bytes_to_crossfade, 0); uint8* place_to_copy = crossfade_buffer_.get() + (index_into_window_ - outtro_crossfade_begin); CopyWithAdvance(place_to_copy); index_into_window_ += bytes_per_frame_; } while (index_into_window_ < intro_crossfade_begin) { if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; DropFrame(); index_into_window_ += bytes_per_frame_; } if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; if (bytes_to_crossfade == 0) { DCHECK_EQ(index_into_window_, window_size_); return false; } DCHECK_LT(index_into_window_, window_size_); int offset_into_buffer = index_into_window_ - intro_crossfade_begin; memcpy(dest, crossfade_buffer_.get() + offset_into_buffer, bytes_per_frame_); scoped_array<uint8> intro_frame_ptr(new uint8[bytes_per_frame_]); audio_buffer_.Read(intro_frame_ptr.get(), bytes_per_frame_); OutputCrossfadedFrame(dest, intro_frame_ptr.get()); index_into_window_ += bytes_per_frame_; return true; } Commit Message: Protect AudioRendererAlgorithm from invalid step sizes. BUG=165430 TEST=unittests and asan pass. Review URL: https://codereview.chromium.org/11573023 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173249 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool AudioRendererAlgorithm::OutputFasterPlayback(uint8* dest) { bool AudioRendererAlgorithm::OutputFasterPlayback(uint8* dest, int input_step, int output_step) { // Ensure we don't run into OOB read/write situation. CHECK_GT(input_step, output_step); DCHECK_LT(index_into_window_, window_size_); DCHECK_GT(playback_rate_, 1.0); if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; int bytes_to_crossfade = bytes_in_crossfade_; if (muted_ || bytes_to_crossfade > output_step) bytes_to_crossfade = 0; int outtro_crossfade_begin = output_step - bytes_to_crossfade; int outtro_crossfade_end = output_step; int intro_crossfade_begin = input_step - bytes_to_crossfade; if (index_into_window_ < outtro_crossfade_begin) { CopyWithAdvance(dest); index_into_window_ += bytes_per_frame_; return true; } while (index_into_window_ < outtro_crossfade_end) { if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; DCHECK_GT(bytes_to_crossfade, 0); uint8* place_to_copy = crossfade_buffer_.get() + (index_into_window_ - outtro_crossfade_begin); CopyWithAdvance(place_to_copy); index_into_window_ += bytes_per_frame_; } while (index_into_window_ < intro_crossfade_begin) { if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; DropFrame(); index_into_window_ += bytes_per_frame_; } if (audio_buffer_.forward_bytes() < bytes_per_frame_) return false; if (bytes_to_crossfade == 0) { DCHECK_EQ(index_into_window_, window_size_); return false; } DCHECK_LT(index_into_window_, window_size_); int offset_into_buffer = index_into_window_ - intro_crossfade_begin; memcpy(dest, crossfade_buffer_.get() + offset_into_buffer, bytes_per_frame_); scoped_array<uint8> intro_frame_ptr(new uint8[bytes_per_frame_]); audio_buffer_.Read(intro_frame_ptr.get(), bytes_per_frame_); OutputCrossfadedFrame(dest, intro_frame_ptr.get()); index_into_window_ += bytes_per_frame_; return true; }
171,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int efx_probe_all(struct efx_nic *efx) { int rc; rc = efx_probe_nic(efx); if (rc) { netif_err(efx, probe, efx->net_dev, "failed to create NIC\n"); goto fail1; } rc = efx_probe_port(efx); if (rc) { netif_err(efx, probe, efx->net_dev, "failed to create port\n"); goto fail2; } efx->rxq_entries = efx->txq_entries = EFX_DEFAULT_DMAQ_SIZE; rc = efx_probe_channels(efx); if (rc) goto fail3; rc = efx_probe_filters(efx); if (rc) { netif_err(efx, probe, efx->net_dev, "failed to create filter tables\n"); goto fail4; } return 0; fail4: efx_remove_channels(efx); fail3: efx_remove_port(efx); fail2: efx_remove_nic(efx); fail1: return rc; } Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size [ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ] Currently an skb requiring TSO may not fit within a minimum-size TX queue. The TX queue selected for the skb may stall and trigger the TX watchdog repeatedly (since the problem skb will be retried after the TX reset). This issue is designated as CVE-2012-3412. Set the maximum number of TSO segments for our devices to 100. This should make no difference to behaviour unless the actual MSS is less than about 700. Increase the minimum TX queue size accordingly to allow for 2 worst-case skbs, so that there will definitely be space to add an skb after we wake a queue. To avoid invalidating existing configurations, change efx_ethtool_set_ringparam() to fix up values that are too small rather than returning -EINVAL. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> CWE ID: CWE-189
static int efx_probe_all(struct efx_nic *efx) { int rc; rc = efx_probe_nic(efx); if (rc) { netif_err(efx, probe, efx->net_dev, "failed to create NIC\n"); goto fail1; } rc = efx_probe_port(efx); if (rc) { netif_err(efx, probe, efx->net_dev, "failed to create port\n"); goto fail2; } BUILD_BUG_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_RXQ_MIN_ENT); if (WARN_ON(EFX_DEFAULT_DMAQ_SIZE < EFX_TXQ_MIN_ENT(efx))) { rc = -EINVAL; goto fail3; } efx->rxq_entries = efx->txq_entries = EFX_DEFAULT_DMAQ_SIZE; rc = efx_probe_channels(efx); if (rc) goto fail3; rc = efx_probe_filters(efx); if (rc) { netif_err(efx, probe, efx->net_dev, "failed to create filter tables\n"); goto fail4; } return 0; fail4: efx_remove_channels(efx); fail3: efx_remove_port(efx); fail2: efx_remove_nic(efx); fail1: return rc; }
165,584
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; } Commit Message: [MJ2] Avoid index out of bounds access to pi->include[] Signed-off-by: Young_X <[email protected]> CWE ID: CWE-20
static opj_bool pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { int resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { int dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : int_min(pi->dx, dx); pi->dy = !pi->dy ? dy : int_min(pi->dy, dy); } if (!pi->tp_on) { pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += pi->dy - (pi->y % pi->dy)) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += pi->dx - (pi->x % pi->dx)) { for (pi->resno = pi->poc.resno0; pi->resno < int_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { int levelno; int trx0, try0; int trx1, try1; int rpx, rpy; int prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = int_ceildiv(pi->tx0, comp->dx << levelno); try0 = int_ceildiv(pi->ty0, comp->dy << levelno); trx1 = int_ceildiv(pi->tx1, comp->dx << levelno); try1 = int_ceildiv(pi->ty1, comp->dy << levelno); rpx = res->pdx + levelno; rpy = res->pdy + levelno; /* To avoid divisions by zero / undefined behaviour on shift */ if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx || rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) { continue; } if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))) { continue; } if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))) { continue; } if ((res->pw == 0) || (res->ph == 0)) { continue; } if ((trx0 == trx1) || (try0 == try1)) { continue; } prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx) - int_floordivpow2(trx0, res->pdx); prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy) - int_floordivpow2(try0, res->pdy); pi->precno = prci + prcj * res->pw; for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; /* Avoids index out of bounds access with include*/ if (index >= pi->include_size) { opj_pi_emit_error(pi, "Invalid access to pi->include"); return OPJ_FALSE; } if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } } return OPJ_FALSE; }
169,767
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data) { int ret; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0, indx, data, size, 100); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); return ret; } Commit Message: pegasus: Use heap buffers for all register access Allocating USB buffers on the stack is not portable, and no longer works on x86_64 (with VMAP_STACK enabled as per default). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") References: https://bugs.debian.org/852556 Reported-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]> Tested-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data) static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, const void *data) { u8 *buf; int ret; buf = kmemdup(data, size, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0, indx, buf, size, 100); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); kfree(buf); return ret; }
168,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; } Commit Message: ipv6/dccp: do not inherit ipv6_mc_list from parent Like commit 657831ffc38e ("dccp/tcp: do not inherit mc_list from parent") we should clear ipv6_mc_list etc. for IPv6 sockets too. Cc: Eric Dumazet <[email protected]> Signed-off-by: Cong Wang <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static struct sock *dccp_v6_request_recv_sock(const struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst, struct request_sock *req_unhash, bool *own_req) { struct inet_request_sock *ireq = inet_rsk(req); struct ipv6_pinfo *newnp; const struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt; struct inet_sock *newinet; struct dccp6_sock *newdp6; struct sock *newsk; if (skb->protocol == htons(ETH_P_IP)) { /* * v6 mapped */ newsk = dccp_v4_request_recv_sock(sk, skb, req, dst, req_unhash, own_req); if (newsk == NULL) return NULL; newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newnp->saddr = newsk->sk_v6_rcv_saddr; inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped; newsk->sk_backlog_rcv = dccp_v4_do_rcv; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks count * here, dccp_create_openreq_child now does this for us, see the comment in * that function for the gory details. -acme */ /* It is tricky place. Until this moment IPv4 tcp worked with IPv6 icsk.icsk_af_ops. Sync it now. */ dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie); return newsk; } if (sk_acceptq_is_full(sk)) goto out_overflow; if (!dst) { struct flowi6 fl6; dst = inet6_csk_route_req(sk, &fl6, req, IPPROTO_DCCP); if (!dst) goto out; } newsk = dccp_create_openreq_child(sk, req, skb); if (newsk == NULL) goto out_nonewsk; /* * No need to charge this sock to the relevant IPv6 refcnt debug socks * count here, dccp_create_openreq_child now does this for us, see the * comment in that function for the gory details. -acme */ ip6_dst_store(newsk, dst, NULL, NULL); newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM | NETIF_F_TSO); newdp6 = (struct dccp6_sock *)newsk; newinet = inet_sk(newsk); newinet->pinet6 = &newdp6->inet6; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); newsk->sk_v6_daddr = ireq->ir_v6_rmt_addr; newnp->saddr = ireq->ir_v6_loc_addr; newsk->sk_v6_rcv_saddr = ireq->ir_v6_loc_addr; newsk->sk_bound_dev_if = ireq->ir_iif; /* Now IPv6 options... First: no IPv4 options. */ newinet->inet_opt = NULL; /* Clone RX bits */ newnp->rxopt.all = np->rxopt.all; newnp->ipv6_mc_list = NULL; newnp->ipv6_ac_list = NULL; newnp->ipv6_fl_list = NULL; newnp->pktoptions = NULL; newnp->opt = NULL; newnp->mcast_oif = inet6_iif(skb); newnp->mcast_hops = ipv6_hdr(skb)->hop_limit; /* * Clone native IPv6 options from listening socket (if any) * * Yes, keeping reference count would be much more clever, but we make * one more one thing there: reattach optmem to newsk. */ opt = ireq->ipv6_opt; if (!opt) opt = rcu_dereference(np->opt); if (opt) { opt = ipv6_dup_options(newsk, opt); RCU_INIT_POINTER(newnp->opt, opt); } inet_csk(newsk)->icsk_ext_hdr_len = 0; if (opt) inet_csk(newsk)->icsk_ext_hdr_len = opt->opt_nflen + opt->opt_flen; dccp_sync_mss(newsk, dst_mtu(dst)); newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6; newinet->inet_rcv_saddr = LOOPBACK4_IPV6; if (__inet_inherit_port(sk, newsk) < 0) { inet_csk_prepare_forced_close(newsk); dccp_done(newsk); goto out; } *own_req = inet_ehash_nolisten(newsk, req_to_sk(req_unhash)); /* Clone pktoptions received with SYN, if we own the req */ if (*own_req && ireq->pktopts) { newnp->pktoptions = skb_clone(ireq->pktopts, GFP_ATOMIC); consume_skb(ireq->pktopts); ireq->pktopts = NULL; if (newnp->pktoptions) skb_set_owner_r(newnp->pktoptions, newsk); } return newsk; out_overflow: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); out_nonewsk: dst_release(dst); out: __NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENDROPS); return NULL; }
168,127
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: netscreen_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { int pkt_len; char line[NETSCREEN_LINE_LENGTH]; char cap_int[NETSCREEN_MAX_INT_NAME_LENGTH]; gboolean cap_dir; char cap_dst[13]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) { return FALSE; } if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } pkt_len = parse_netscreen_rec_hdr(phdr, line, cap_int, &cap_dir, cap_dst, err, err_info); if (pkt_len == -1) return FALSE; if (!parse_netscreen_hex_dump(wth->random_fh, pkt_len, cap_int, cap_dst, phdr, buf, err, err_info)) return FALSE; return TRUE; } Commit Message: Fix packet length handling. Treat the packet length as unsigned - it shouldn't be negative in the file. If it is, that'll probably cause the sscanf to fail, so we'll report the file as bad. Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to allocate a huge amount of memory, just as we do in other file readers. Use the now-validated packet size as the length in ws_buffer_assure_space(), so we are certain to have enough space, and don't allocate too much space. Merge the header and packet data parsing routines while we're at it. Bug: 12396 Change-Id: I7f981f9cdcbea7ecdeb88bfff2f12d875de2244f Reviewed-on: https://code.wireshark.org/review/15176 Reviewed-by: Guy Harris <[email protected]> CWE ID: CWE-20
netscreen_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) { char line[NETSCREEN_LINE_LENGTH]; if (file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) { return FALSE; } if (file_gets(line, NETSCREEN_LINE_LENGTH, wth->random_fh) == NULL) { *err = file_error(wth->random_fh, err_info); if (*err == 0) { *err = WTAP_ERR_SHORT_READ; } return FALSE; } return parse_netscreen_packet(wth->random_fh, phdr, buf, line, err, err_info); }
167,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() { if (pending_entry_index_ == -1) delete pending_entry_; pending_entry_ = NULL; pending_entry_index_ = -1; DiscardTransientEntry(); } Commit Message: Delete unneeded pending entries in DidFailProvisionalLoad to prevent a spoof. BUG=280512 BUG=278899 TEST=See bug for repro steps. Review URL: https://chromiumcodereview.appspot.com/23978003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@222146 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() { DiscardPendingEntry(); DiscardTransientEntry(); } void NavigationControllerImpl::DiscardPendingEntry() { if (pending_entry_index_ == -1) delete pending_entry_; pending_entry_ = NULL; pending_entry_index_ = -1; }
171,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebRunnerMainDelegate::CreateContentBrowserClient() { DCHECK(!browser_client_); browser_client_ = std::make_unique<WebRunnerContentBrowserClient>( std::move(context_channel_)); return browser_client_.get(); } Commit Message: [fuchsia] Implement browser tests for WebRunner Context service. Tests may interact with the WebRunner FIDL services and the underlying browser objects for end to end testing of service and browser functionality. * Add a browser test launcher main() for WebRunner. * Add some simple navigation tests. * Wire up GoBack()/GoForward() FIDL calls. * Add embedded test server resources and initialization logic. * Add missing deletion & notification calls to BrowserContext dtor. * Use FIDL events for navigation state changes. * Bug fixes: ** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(), so that they may use the MessageLoop during teardown. ** Fix Frame dtor to allow for null WindowTreeHosts (headless case) ** Fix std::move logic in Frame ctor which lead to no WebContents observer being registered. Bug: 871594 Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac Reviewed-on: https://chromium-review.googlesource.com/1164539 Commit-Queue: Kevin Marshall <[email protected]> Reviewed-by: Wez <[email protected]> Reviewed-by: Fabrice de Gans-Riberi <[email protected]> Reviewed-by: Scott Violet <[email protected]> Cr-Commit-Position: refs/heads/master@{#584155} CWE ID: CWE-264
WebRunnerMainDelegate::CreateContentBrowserClient() { DCHECK(context_channel_); DCHECK(!browser_client_); browser_client_ = std::make_unique<WebRunnerContentBrowserClient>( std::move(context_channel_)); return browser_client_.get(); }
172,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ipt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct ipt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->ip)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ipt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ipt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ipt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ipt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ipt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ipt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ipt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ipt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ipt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; }
167,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProxyChannelDelegate::ProxyChannelDelegate() : shutdown_event_(true, false) { } Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer. BUG=116317 TEST=ppapi, nacl tests, manual testing for experimental IPC proxy. Review URL: https://chromiumcodereview.appspot.com/10641016 [email protected] Review URL: https://chromiumcodereview.appspot.com/10625007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
ProxyChannelDelegate::ProxyChannelDelegate()
170,737
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ext4_free_io_end(ext4_io_end_t *io) { BUG_ON(!io); iput(io->inode); kfree(io); } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static void ext4_free_io_end(ext4_io_end_t *io)
167,544
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: usage(void) { fprintf(stderr, "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" " [-t life] [command [arg ...]]\n" " ssh-agent [-c | -s] -k\n"); exit(1); } Commit Message: add a whitelist of paths from which ssh-agent will load (via ssh-pkcs11-helper) a PKCS#11 module; ok markus@ CWE ID: CWE-426
usage(void) { fprintf(stderr, "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n" " ssh-agent [-c | -s] -k\n"); exit(1); }
168,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) { if (requested_pos < 0) return 0; Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); Cluster* const pCluster = Cluster::Create(this, -1, requested_pos); assert(pCluster); const ptrdiff_t idx = i - m_clusters; PreloadCluster(pCluster, idx); assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) { if (requested_pos < 0) return 0; Cluster** const ii = m_clusters; Cluster** i = ii; const long count = m_clusterCount + m_clusterPreloadCount; Cluster** const jj = ii + count; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pCluster = *k; assert(pCluster); const long long pos = pCluster->GetPosition(); assert(pos >= 0); if (pos < requested_pos) i = k + 1; else if (pos > requested_pos) j = k; else return pCluster; } assert(i == j); Cluster* const pCluster = Cluster::Create(this, -1, requested_pos); if (pCluster == NULL) return NULL; const ptrdiff_t idx = i - m_clusters; if (!PreloadCluster(pCluster, idx)) { delete pCluster; return NULL; } assert(m_clusters); assert(m_clusterPreloadCount > 0); assert(m_clusters[idx] == pCluster); return pCluster; }
173,812
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; } Commit Message: net: guard tcp_set_keepalive() to tcp sockets Its possible to use RAW sockets to get a crash in tcp_set_keepalive() / sk_reset_timer() Fix is to make sure socket is a SOCK_STREAM one. Reported-by: Dave Jones <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
int sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int val; int valbool; struct linger ling; int ret = 0; /* * Options without arguments */ if (optname == SO_BINDTODEVICE) return sock_bindtodevice(sk, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; lock_sock(sk); switch (optname) { case SO_DEBUG: if (val && !capable(CAP_NET_ADMIN)) ret = -EACCES; else sock_valbool_flag(sk, SOCK_DBG, valbool); break; case SO_REUSEADDR: sk->sk_reuse = (valbool ? SK_CAN_REUSE : SK_NO_REUSE); break; case SO_TYPE: case SO_PROTOCOL: case SO_DOMAIN: case SO_ERROR: ret = -ENOPROTOOPT; break; case SO_DONTROUTE: sock_valbool_flag(sk, SOCK_LOCALROUTE, valbool); break; case SO_BROADCAST: sock_valbool_flag(sk, SOCK_BROADCAST, valbool); break; case SO_SNDBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_wmem_max); set_sndbuf: sk->sk_userlocks |= SOCK_SNDBUF_LOCK; sk->sk_sndbuf = max_t(u32, val * 2, SOCK_MIN_SNDBUF); /* Wake up sending tasks if we upped the value. */ sk->sk_write_space(sk); break; case SO_SNDBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_sndbuf; case SO_RCVBUF: /* Don't error on this BSD doesn't and if you think * about it this is right. Otherwise apps have to * play 'guess the biggest size' games. RCVBUF/SNDBUF * are treated in BSD as hints */ val = min_t(u32, val, sysctl_rmem_max); set_rcvbuf: sk->sk_userlocks |= SOCK_RCVBUF_LOCK; /* * We double it on the way in to account for * "struct sk_buff" etc. overhead. Applications * assume that the SO_RCVBUF setting they make will * allow that much actual data to be received on that * socket. * * Applications are unaware that "struct sk_buff" and * other overheads allocate from the receive buffer * during socket buffer allocation. * * And after considering the possible alternatives, * returning the value we actually used in getsockopt * is the most desirable behavior. */ sk->sk_rcvbuf = max_t(u32, val * 2, SOCK_MIN_RCVBUF); break; case SO_RCVBUFFORCE: if (!capable(CAP_NET_ADMIN)) { ret = -EPERM; break; } goto set_rcvbuf; case SO_KEEPALIVE: #ifdef CONFIG_INET if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) tcp_set_keepalive(sk, valbool); #endif sock_valbool_flag(sk, SOCK_KEEPOPEN, valbool); break; case SO_OOBINLINE: sock_valbool_flag(sk, SOCK_URGINLINE, valbool); break; case SO_NO_CHECK: sk->sk_no_check = valbool; break; case SO_PRIORITY: if ((val >= 0 && val <= 6) || capable(CAP_NET_ADMIN)) sk->sk_priority = val; else ret = -EPERM; break; case SO_LINGER: if (optlen < sizeof(ling)) { ret = -EINVAL; /* 1003.1g */ break; } if (copy_from_user(&ling, optval, sizeof(ling))) { ret = -EFAULT; break; } if (!ling.l_onoff) sock_reset_flag(sk, SOCK_LINGER); else { #if (BITS_PER_LONG == 32) if ((unsigned int)ling.l_linger >= MAX_SCHEDULE_TIMEOUT/HZ) sk->sk_lingertime = MAX_SCHEDULE_TIMEOUT; else #endif sk->sk_lingertime = (unsigned int)ling.l_linger * HZ; sock_set_flag(sk, SOCK_LINGER); } break; case SO_BSDCOMPAT: sock_warn_obsolete_bsdism("setsockopt"); break; case SO_PASSCRED: if (valbool) set_bit(SOCK_PASSCRED, &sock->flags); else clear_bit(SOCK_PASSCRED, &sock->flags); break; case SO_TIMESTAMP: case SO_TIMESTAMPNS: if (valbool) { if (optname == SO_TIMESTAMP) sock_reset_flag(sk, SOCK_RCVTSTAMPNS); else sock_set_flag(sk, SOCK_RCVTSTAMPNS); sock_set_flag(sk, SOCK_RCVTSTAMP); sock_enable_timestamp(sk, SOCK_TIMESTAMP); } else { sock_reset_flag(sk, SOCK_RCVTSTAMP); sock_reset_flag(sk, SOCK_RCVTSTAMPNS); } break; case SO_TIMESTAMPING: if (val & ~SOF_TIMESTAMPING_MASK) { ret = -EINVAL; break; } sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE, val & SOF_TIMESTAMPING_TX_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE, val & SOF_TIMESTAMPING_TX_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE, val & SOF_TIMESTAMPING_RX_HARDWARE); if (val & SOF_TIMESTAMPING_RX_SOFTWARE) sock_enable_timestamp(sk, SOCK_TIMESTAMPING_RX_SOFTWARE); else sock_disable_timestamp(sk, (1UL << SOCK_TIMESTAMPING_RX_SOFTWARE)); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SOFTWARE, val & SOF_TIMESTAMPING_SOFTWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE, val & SOF_TIMESTAMPING_SYS_HARDWARE); sock_valbool_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE, val & SOF_TIMESTAMPING_RAW_HARDWARE); break; case SO_RCVLOWAT: if (val < 0) val = INT_MAX; sk->sk_rcvlowat = val ? : 1; break; case SO_RCVTIMEO: ret = sock_set_timeout(&sk->sk_rcvtimeo, optval, optlen); break; case SO_SNDTIMEO: ret = sock_set_timeout(&sk->sk_sndtimeo, optval, optlen); break; case SO_ATTACH_FILTER: ret = -EINVAL; if (optlen == sizeof(struct sock_fprog)) { struct sock_fprog fprog; ret = -EFAULT; if (copy_from_user(&fprog, optval, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, sk); } break; case SO_DETACH_FILTER: ret = sk_detach_filter(sk); break; case SO_PASSSEC: if (valbool) set_bit(SOCK_PASSSEC, &sock->flags); else clear_bit(SOCK_PASSSEC, &sock->flags); break; case SO_MARK: if (!capable(CAP_NET_ADMIN)) ret = -EPERM; else sk->sk_mark = val; break; /* We implement the SO_SNDLOWAT etc to not be settable (1003.1g 5.3) */ case SO_RXQ_OVFL: sock_valbool_flag(sk, SOCK_RXQ_OVFL, valbool); break; case SO_WIFI_STATUS: sock_valbool_flag(sk, SOCK_WIFI_STATUS, valbool); break; case SO_PEEK_OFF: if (sock->ops->set_peek_off) sock->ops->set_peek_off(sk, val); else ret = -EOPNOTSUPP; break; case SO_NOFCS: sock_valbool_flag(sk, SOCK_NOFCS, valbool); break; default: ret = -ENOPROTOOPT; break; } release_sock(sk); return ret; }
166,547
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_verifier_state *vstate = env->cur_state; struct bpf_func_state *state = vstate->frame[vstate->curframe]; struct bpf_reg_state *regs = state->regs, *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u32 dst = insn->dst_reg, src = insn->src_reg; u8 opcode = BPF_OP(insn->code); dst_reg = &regs[dst]; if ((known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } switch (ptr_reg->type) { case PTR_TO_MAP_VALUE_OR_NULL: verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", dst, reg_type_str[ptr_reg->type]); return -EACCES; case CONST_PTR_TO_MAP: case PTR_TO_PACKET_END: case PTR_TO_SOCKET: case PTR_TO_SOCKET_OR_NULL: verbose(env, "R%d pointer arithmetic on %s prohibited\n", dst, reg_type_str[ptr_reg->type]); return -EACCES; case PTR_TO_MAP_VALUE: if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) { verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n", off_reg == dst_reg ? dst : src); return -EACCES; } /* fall-through */ default: break; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) return -EINVAL; switch (opcode) { case BPF_ADD: /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->raw = ptr_reg->raw; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; dst_reg->raw = ptr_reg->raw; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->raw = 0; } break; case BPF_SUB: if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->raw = ptr_reg->raw; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; dst_reg->raw = ptr_reg->raw; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->raw = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit. */ verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) return -EINVAL; __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); /* For unprivileged we require that resulting offset must be in bounds * in order to be able to sanitize access later on. */ if (!env->allow_ptr_leaks) { if (dst_reg->type == PTR_TO_MAP_VALUE && check_map_access(env, dst, dst_reg->off, 1, false)) { verbose(env, "R%d pointer arithmetic of map value goes out of range, " "prohibited for !root\n", dst); return -EACCES; } else if (dst_reg->type == PTR_TO_STACK && check_stack_access(env, dst_reg, dst_reg->off + dst_reg->var_off.value, 1)) { verbose(env, "R%d stack pointer arithmetic goes out of range, " "prohibited for !root\n", dst); return -EACCES; } } return 0; } Commit Message: bpf: prevent out of bounds speculation on pointer arithmetic Jann reported that the original commit back in b2157399cc98 ("bpf: prevent out-of-bounds speculation") was not sufficient to stop CPU from speculating out of bounds memory access: While b2157399cc98 only focussed on masking array map access for unprivileged users for tail calls and data access such that the user provided index gets sanitized from BPF program and syscall side, there is still a more generic form affected from BPF programs that applies to most maps that hold user data in relation to dynamic map access when dealing with unknown scalars or "slow" known scalars as access offset, for example: - Load a map value pointer into R6 - Load an index into R7 - Do a slow computation (e.g. with a memory dependency) that loads a limit into R8 (e.g. load the limit from a map for high latency, then mask it to make the verifier happy) - Exit if R7 >= R8 (mispredicted branch) - Load R0 = R6[R7] - Load R0 = R6[R0] For unknown scalars there are two options in the BPF verifier where we could derive knowledge from in order to guarantee safe access to the memory: i) While </>/<=/>= variants won't allow to derive any lower or upper bounds from the unknown scalar where it would be safe to add it to the map value pointer, it is possible through ==/!= test however. ii) another option is to transform the unknown scalar into a known scalar, for example, through ALU ops combination such as R &= <imm> followed by R |= <imm> or any similar combination where the original information from the unknown scalar would be destroyed entirely leaving R with a constant. The initial slow load still precedes the latter ALU ops on that register, so the CPU executes speculatively from that point. Once we have the known scalar, any compare operation would work then. A third option only involving registers with known scalars could be crafted as described in [0] where a CPU port (e.g. Slow Int unit) would be filled with many dependent computations such that the subsequent condition depending on its outcome has to wait for evaluation on its execution port and thereby executing speculatively if the speculated code can be scheduled on a different execution port, or any other form of mistraining as described in [1], for example. Given this is not limited to only unknown scalars, not only map but also stack access is affected since both is accessible for unprivileged users and could potentially be used for out of bounds access under speculation. In order to prevent any of these cases, the verifier is now sanitizing pointer arithmetic on the offset such that any out of bounds speculation would be masked in a way where the pointer arithmetic result in the destination register will stay unchanged, meaning offset masked into zero similar as in array_index_nospec() case. With regards to implementation, there are three options that were considered: i) new insn for sanitation, ii) push/pop insn and sanitation as inlined BPF, iii) reuse of ax register and sanitation as inlined BPF. Option i) has the downside that we end up using from reserved bits in the opcode space, but also that we would require each JIT to emit masking as native arch opcodes meaning mitigation would have slow adoption till everyone implements it eventually which is counter-productive. Option ii) and iii) have both in common that a temporary register is needed in order to implement the sanitation as inlined BPF since we are not allowed to modify the source register. While a push / pop insn in ii) would be useful to have in any case, it requires once again that every JIT needs to implement it first. While possible, amount of changes needed would also be unsuitable for a -stable patch. Therefore, the path which has fewer changes, less BPF instructions for the mitigation and does not require anything to be changed in the JITs is option iii) which this work is pursuing. The ax register is already mapped to a register in all JITs (modulo arm32 where it's mapped to stack as various other BPF registers there) and used in constant blinding for JITs-only so far. It can be reused for verifier rewrites under certain constraints. The interpreter's tmp "register" has therefore been remapped into extending the register set with hidden ax register and reusing that for a number of instructions that needed the prior temporary variable internally (e.g. div, mod). This allows for zero increase in stack space usage in the interpreter, and enables (restricted) generic use in rewrites otherwise as long as such a patchlet does not make use of these instructions. The sanitation mask is dynamic and relative to the offset the map value or stack pointer currently holds. There are various cases that need to be taken under consideration for the masking, e.g. such operation could look as follows: ptr += val or val += ptr or ptr -= val. Thus, the value to be sanitized could reside either in source or in destination register, and the limit is different depending on whether the ALU op is addition or subtraction and depending on the current known and bounded offset. The limit is derived as follows: limit := max_value_size - (smin_value + off). For subtraction: limit := umax_value + off. This holds because we do not allow any pointer arithmetic that would temporarily go out of bounds or would have an unknown value with mixed signed bounds where it is unclear at verification time whether the actual runtime value would be either negative or positive. For example, we have a derived map pointer value with constant offset and bounded one, so limit based on smin_value works because the verifier requires that statically analyzed arithmetic on the pointer must be in bounds, and thus it checks if resulting smin_value + off and umax_value + off is still within map value bounds at time of arithmetic in addition to time of access. Similarly, for the case of stack access we derive the limit as follows: MAX_BPF_STACK + off for subtraction and -off for the case of addition where off := ptr_reg->off + ptr_reg->var_off.value. Subtraction is a special case for the masking which can be in form of ptr += -val, ptr -= -val, or ptr -= val. In the first two cases where we know that the value is negative, we need to temporarily negate the value in order to do the sanitation on a positive value where we later swap the ALU op, and restore original source register if the value was in source. The sanitation of pointer arithmetic alone is still not fully sufficient as is, since a scenario like the following could happen ... PTR += 0x1000 (e.g. K-based imm) PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON PTR += 0x1000 PTR -= BIG_NUMBER_WITH_SLOW_COMPARISON [...] ... which under speculation could end up as ... PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] PTR += 0x1000 PTR -= 0 [ truncated by mitigation ] [...] ... and therefore still access out of bounds. To prevent such case, the verifier is also analyzing safety for potential out of bounds access under speculative execution. Meaning, it is also simulating pointer access under truncation. We therefore "branch off" and push the current verification state after the ALU operation with known 0 to the verification stack for later analysis. Given the current path analysis succeeded it is likely that the one under speculation can be pruned. In any case, it is also subject to existing complexity limits and therefore anything beyond this point will be rejected. In terms of pruning, it needs to be ensured that the verification state from speculative execution simulation must never prune a non-speculative execution path, therefore, we mark verifier state accordingly at the time of push_stack(). If verifier detects out of bounds access under speculative execution from one of the possible paths that includes a truncation, it will reject such program. Given we mask every reg-based pointer arithmetic for unprivileged programs, we've been looking into how it could affect real-world programs in terms of size increase. As the majority of programs are targeted for privileged-only use case, we've unconditionally enabled masking (with its alu restrictions on top of it) for privileged programs for the sake of testing in order to check i) whether they get rejected in its current form, and ii) by how much the number of instructions and size will increase. We've tested this by using Katran, Cilium and test_l4lb from the kernel selftests. For Katran we've evaluated balancer_kern.o, Cilium bpf_lxc.o and an older test object bpf_lxc_opt_-DUNKNOWN.o and l4lb we've used test_l4lb.o as well as test_l4lb_noinline.o. We found that none of the programs got rejected by the verifier with this change, and that impact is rather minimal to none. balancer_kern.o had 13,904 bytes (1,738 insns) xlated and 7,797 bytes JITed before and after the change. Most complex program in bpf_lxc.o had 30,544 bytes (3,817 insns) xlated and 18,538 bytes JITed before and after and none of the other tail call programs in bpf_lxc.o had any changes either. For the older bpf_lxc_opt_-DUNKNOWN.o object we found a small increase from 20,616 bytes (2,576 insns) and 12,536 bytes JITed before to 20,664 bytes (2,582 insns) and 12,558 bytes JITed after the change. Other programs from that object file had similar small increase. Both test_l4lb.o had no change and remained at 6,544 bytes (817 insns) xlated and 3,401 bytes JITed and for test_l4lb_noinline.o constant at 5,080 bytes (634 insns) xlated and 3,313 bytes JITed. This can be explained in that LLVM typically optimizes stack based pointer arithmetic by using K-based operations and that use of dynamic map access is not overly frequent. However, in future we may decide to optimize the algorithm further under known guarantees from branch and value speculation. Latter seems also unclear in terms of prediction heuristics that today's CPUs apply as well as whether there could be collisions in e.g. the predictor's Value History/Pattern Table for triggering out of bounds access, thus masking is performed unconditionally at this point but could be subject to relaxation later on. We were generally also brainstorming various other approaches for mitigation, but the blocker was always lack of available registers at runtime and/or overhead for runtime tracking of limits belonging to a specific pointer. Thus, we found this to be minimally intrusive under given constraints. With that in place, a simple example with sanitized access on unprivileged load at post-verification time looks as follows: # bpftool prog dump xlated id 282 [...] 28: (79) r1 = *(u64 *)(r7 +0) 29: (79) r2 = *(u64 *)(r7 +8) 30: (57) r1 &= 15 31: (79) r3 = *(u64 *)(r0 +4608) 32: (57) r3 &= 1 33: (47) r3 |= 1 34: (2d) if r2 > r3 goto pc+19 35: (b4) (u32) r11 = (u32) 20479 | 36: (1f) r11 -= r2 | Dynamic sanitation for pointer 37: (4f) r11 |= r2 | arithmetic with registers 38: (87) r11 = -r11 | containing bounded or known 39: (c7) r11 s>>= 63 | scalars in order to prevent 40: (5f) r11 &= r2 | out of bounds speculation. 41: (0f) r4 += r11 | 42: (71) r4 = *(u8 *)(r4 +0) 43: (6f) r4 <<= r1 [...] For the case where the scalar sits in the destination register as opposed to the source register, the following code is emitted for the above example: [...] 16: (b4) (u32) r11 = (u32) 20479 17: (1f) r11 -= r2 18: (4f) r11 |= r2 19: (87) r11 = -r11 20: (c7) r11 s>>= 63 21: (5f) r2 &= r11 22: (0f) r2 += r0 23: (61) r0 = *(u32 *)(r2 +0) [...] JIT blinding example with non-conflicting use of r10: [...] d5: je 0x0000000000000106 _ d7: mov 0x0(%rax),%edi | da: mov $0xf153246,%r10d | Index load from map value and e0: xor $0xf153259,%r10 | (const blinded) mask with 0x1f. e7: and %r10,%rdi |_ ea: mov $0x2f,%r10d | f0: sub %rdi,%r10 | Sanitized addition. Both use r10 f3: or %rdi,%r10 | but do not interfere with each f6: neg %r10 | other. (Neither do these instructions f9: sar $0x3f,%r10 | interfere with the use of ax as temp fd: and %r10,%rdi | in interpreter.) 100: add %rax,%rdi |_ 103: mov 0x0(%rdi),%eax [...] Tested that it fixes Jann's reproducer, and also checked that test_verifier and test_progs suite with interpreter, JIT and JIT with hardening enabled on x86-64 and arm64 runs successfully. [0] Speculose: Analyzing the Security Implications of Speculative Execution in CPUs, Giorgi Maisuradze and Christian Rossow, https://arxiv.org/pdf/1801.04084.pdf [1] A Systematic Evaluation of Transient Execution Attacks and Defenses, Claudio Canella, Jo Van Bulck, Michael Schwarz, Moritz Lipp, Benjamin von Berg, Philipp Ortner, Frank Piessens, Dmitry Evtyushkin, Daniel Gruss, https://arxiv.org/pdf/1811.05441.pdf Fixes: b2157399cc98 ("bpf: prevent out-of-bounds speculation") Reported-by: Jann Horn <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> CWE ID: CWE-189
static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn, const struct bpf_reg_state *ptr_reg, const struct bpf_reg_state *off_reg) { struct bpf_verifier_state *vstate = env->cur_state; struct bpf_func_state *state = vstate->frame[vstate->curframe]; struct bpf_reg_state *regs = state->regs, *dst_reg; bool known = tnum_is_const(off_reg->var_off); s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; u32 dst = insn->dst_reg, src = insn->src_reg; u8 opcode = BPF_OP(insn->code); int ret; dst_reg = &regs[dst]; if ((known && (smin_val != smax_val || umin_val != umax_val)) || smin_val > smax_val || umin_val > umax_val) { /* Taint dst register if offset had invalid bounds derived from * e.g. dead branches. */ __mark_reg_unknown(dst_reg); return 0; } if (BPF_CLASS(insn->code) != BPF_ALU64) { /* 32-bit ALU ops on pointers produce (meaningless) scalars */ verbose(env, "R%d 32-bit pointer arithmetic prohibited\n", dst); return -EACCES; } switch (ptr_reg->type) { case PTR_TO_MAP_VALUE_OR_NULL: verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", dst, reg_type_str[ptr_reg->type]); return -EACCES; case CONST_PTR_TO_MAP: case PTR_TO_PACKET_END: case PTR_TO_SOCKET: case PTR_TO_SOCKET_OR_NULL: verbose(env, "R%d pointer arithmetic on %s prohibited\n", dst, reg_type_str[ptr_reg->type]); return -EACCES; case PTR_TO_MAP_VALUE: if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) { verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n", off_reg == dst_reg ? dst : src); return -EACCES; } /* fall-through */ default: break; } /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. * The id may be overwritten later if we create a new variable offset. */ dst_reg->type = ptr_reg->type; dst_reg->id = ptr_reg->id; if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) return -EINVAL; switch (opcode) { case BPF_ADD: ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); if (ret < 0) { verbose(env, "R%d tried to add from different maps or paths\n", dst); return ret; } /* We can take a fixed offset as long as it doesn't overflow * the s32 'off' field */ if (known && (ptr_reg->off + smin_val == (s64)(s32)(ptr_reg->off + smin_val))) { /* pointer += K. Accumulate it into fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->off = ptr_reg->off + smin_val; dst_reg->raw = ptr_reg->raw; break; } /* A new variable offset is created. Note that off_reg->off * == 0, since it's a scalar. * dst_reg gets the pointer type and since some positive * integer value was added to the pointer, give it a new 'id' * if it's a PTR_TO_PACKET. * this creates a new 'base' pointer, off_reg (variable) gets * added into the variable offset, and we copy the fixed offset * from ptr_reg. */ if (signed_add_overflows(smin_ptr, smin_val) || signed_add_overflows(smax_ptr, smax_val)) { dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr + smin_val; dst_reg->smax_value = smax_ptr + smax_val; } if (umin_ptr + umin_val < umin_ptr || umax_ptr + umax_val < umax_ptr) { dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { dst_reg->umin_value = umin_ptr + umin_val; dst_reg->umax_value = umax_ptr + umax_val; } dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; dst_reg->raw = ptr_reg->raw; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ dst_reg->raw = 0; } break; case BPF_SUB: ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); if (ret < 0) { verbose(env, "R%d tried to sub from different maps or paths\n", dst); return ret; } if (dst_reg == off_reg) { /* scalar -= pointer. Creates an unknown scalar */ verbose(env, "R%d tried to subtract pointer from scalar\n", dst); return -EACCES; } /* We don't allow subtraction from FP, because (according to * test_verifier.c test "invalid fp arithmetic", JITs might not * be able to deal with it. */ if (ptr_reg->type == PTR_TO_STACK) { verbose(env, "R%d subtraction from stack pointer prohibited\n", dst); return -EACCES; } if (known && (ptr_reg->off - smin_val == (s64)(s32)(ptr_reg->off - smin_val))) { /* pointer -= K. Subtract it from fixed offset */ dst_reg->smin_value = smin_ptr; dst_reg->smax_value = smax_ptr; dst_reg->umin_value = umin_ptr; dst_reg->umax_value = umax_ptr; dst_reg->var_off = ptr_reg->var_off; dst_reg->id = ptr_reg->id; dst_reg->off = ptr_reg->off - smin_val; dst_reg->raw = ptr_reg->raw; break; } /* A new variable offset is created. If the subtrahend is known * nonnegative, then any reg->range we had before is still good. */ if (signed_sub_overflows(smin_ptr, smax_val) || signed_sub_overflows(smax_ptr, smin_val)) { /* Overflow possible, we know nothing */ dst_reg->smin_value = S64_MIN; dst_reg->smax_value = S64_MAX; } else { dst_reg->smin_value = smin_ptr - smax_val; dst_reg->smax_value = smax_ptr - smin_val; } if (umin_ptr < umax_val) { /* Overflow possible, we know nothing */ dst_reg->umin_value = 0; dst_reg->umax_value = U64_MAX; } else { /* Cannot overflow (as long as bounds are consistent) */ dst_reg->umin_value = umin_ptr - umax_val; dst_reg->umax_value = umax_ptr - umin_val; } dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); dst_reg->off = ptr_reg->off; dst_reg->raw = ptr_reg->raw; if (reg_is_pkt_pointer(ptr_reg)) { dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range to zero */ if (smin_val < 0) dst_reg->raw = 0; } break; case BPF_AND: case BPF_OR: case BPF_XOR: /* bitwise ops on pointers are troublesome, prohibit. */ verbose(env, "R%d bitwise operator %s on pointer prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; default: /* other operators (e.g. MUL,LSH) produce non-pointer results */ verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", dst, bpf_alu_string[opcode >> 4]); return -EACCES; } if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) return -EINVAL; __update_reg_bounds(dst_reg); __reg_deduce_bounds(dst_reg); __reg_bound_offset(dst_reg); /* For unprivileged we require that resulting offset must be in bounds * in order to be able to sanitize access later on. */ if (!env->allow_ptr_leaks) { if (dst_reg->type == PTR_TO_MAP_VALUE && check_map_access(env, dst, dst_reg->off, 1, false)) { verbose(env, "R%d pointer arithmetic of map value goes out of range, " "prohibited for !root\n", dst); return -EACCES; } else if (dst_reg->type == PTR_TO_STACK && check_stack_access(env, dst_reg, dst_reg->off + dst_reg->var_off.value, 1)) { verbose(env, "R%d stack pointer arithmetic goes out of range, " "prohibited for !root\n", dst); return -EACCES; } } return 0; }
170,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentLoader::DidInstallNewDocument( Document* document, const ContentSecurityPolicy* previous_csp) { document->SetReadyState(Document::kLoading); if (content_security_policy_) { document->InitContentSecurityPolicy(content_security_policy_.Release(), nullptr, previous_csp); } if (history_item_ && IsBackForwardLoadType(load_type_)) document->SetStateForNewFormElements(history_item_->GetDocumentState()); DCHECK(document->GetFrame()); document->GetFrame()->GetClientHintsPreferences().UpdateFrom( client_hints_preferences_); Settings* settings = document->GetSettings(); fetcher_->SetImagesEnabled(settings->GetImagesEnabled()); fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically()); const AtomicString& dns_prefetch_control = response_.HttpHeaderField(http_names::kXDNSPrefetchControl); if (!dns_prefetch_control.IsEmpty()) document->ParseDNSPrefetchControlHeader(dns_prefetch_control); String header_content_language = response_.HttpHeaderField(http_names::kContentLanguage); if (!header_content_language.IsEmpty()) { wtf_size_t comma_index = header_content_language.find(','); header_content_language.Truncate(comma_index); header_content_language = header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>); if (!header_content_language.IsEmpty()) document->SetContentLanguage(AtomicString(header_content_language)); } String referrer_policy_header = response_.HttpHeaderField(http_names::kReferrerPolicy); if (!referrer_policy_header.IsNull()) { UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); } if (response_.IsSignedExchangeInnerResponse()) UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse); GetLocalFrameClient().DidCreateNewDocument(); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void DocumentLoader::DidInstallNewDocument( void DocumentLoader::DidInstallNewDocument(Document* document) { document->SetReadyState(Document::kLoading); if (content_security_policy_) { document->InitContentSecurityPolicy( content_security_policy_.Release(), GetFrameLoader().GetLastOriginDocument()); } if (history_item_ && IsBackForwardLoadType(load_type_)) document->SetStateForNewFormElements(history_item_->GetDocumentState()); DCHECK(document->GetFrame()); document->GetFrame()->GetClientHintsPreferences().UpdateFrom( client_hints_preferences_); Settings* settings = document->GetSettings(); fetcher_->SetImagesEnabled(settings->GetImagesEnabled()); fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically()); const AtomicString& dns_prefetch_control = response_.HttpHeaderField(http_names::kXDNSPrefetchControl); if (!dns_prefetch_control.IsEmpty()) document->ParseDNSPrefetchControlHeader(dns_prefetch_control); String header_content_language = response_.HttpHeaderField(http_names::kContentLanguage); if (!header_content_language.IsEmpty()) { wtf_size_t comma_index = header_content_language.find(','); header_content_language.Truncate(comma_index); header_content_language = header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>); if (!header_content_language.IsEmpty()) document->SetContentLanguage(AtomicString(header_content_language)); } String referrer_policy_header = response_.HttpHeaderField(http_names::kReferrerPolicy); if (!referrer_policy_header.IsNull()) { UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader); document->ParseAndSetReferrerPolicy(referrer_policy_header); } if (response_.IsSignedExchangeInnerResponse()) UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse); GetLocalFrameClient().DidCreateNewDocument(); }
173,056
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { bool oldHorizontalWritingMode = isHorizontalWritingMode(); RenderBoxModelObject::styleDidChange(diff, oldStyle); RenderStyle* newStyle = style(); if (needsLayout() && oldStyle) { RenderBlock::removePercentHeightDescendantIfNeeded(this); if (isOutOfFlowPositioned() && newStyle->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle->marginBefore() && parent() && !parent()->normalChildNeedsLayout()) parent()->setChildNeedsLayout(); } if (RenderBlock::hasPercentHeightContainerMap() && firstChild() && oldHorizontalWritingMode != isHorizontalWritingMode()) RenderBlock::clearPercentHeightDescendantsFrom(this); if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) { if (int left = layer()->scrollableArea()->scrollXOffset()) { left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToXOffset(left); } if (int top = layer()->scrollableArea()->scrollYOffset()) { top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToYOffset(top); } } if (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer) { RenderObject* parentToInvalidate = parent(); for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) { parentToInvalidate->invalidateBackgroundObscurationStatus(); parentToInvalidate = parentToInvalidate->parent(); } } if (isDocumentElement() || isBody()) document().view()->recalculateScrollbarOverlayStyle(); updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle); updateGridPositionAfterStyleChange(oldStyle); } Commit Message: Separate repaint and layout requirements of StyleDifference (Step 1) Previously StyleDifference was an enum that proximately bigger values imply smaller values (e.g. StyleDifferenceLayout implies StyleDifferenceRepaint). This causes unnecessary repaints in some cases on layout change. Convert StyleDifference to a structure containing relatively independent flags. This change doesn't directly improve the result, but can make further repaint optimizations possible. Step 1 doesn't change any functionality. RenderStyle still generate the legacy StyleDifference enum when comparing styles and convert the result to the new StyleDifference. Implicit requirements are not handled during the conversion. Converted call sites to use the new StyleDifference according to the following conversion rules: - diff == StyleDifferenceEqual (&& !context) => diff.hasNoChange() - diff == StyleDifferenceRepaint => diff.needsRepaintObjectOnly() - diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintLayer => diff.needsRepaintLayer() - diff >= StyleDifferenceRepaint => diff.needsRepaint() || diff.needsLayout() - diff >= StyleDifferenceRepaintLayer => diff.needsRepaintLayer() || diff.needsLayout() - diff > StyleDifferenceRepaintLayer => diff.needsLayout() - diff == StyleDifferencePositionedMovementLayoutOnly => diff.needsPositionedMovementLayoutOnly() - diff == StyleDifferenceLayout => diff.needsFullLayout() BUG=358460 TEST=All existing layout tests. [email protected], [email protected], [email protected] Committed: https://src.chromium.org/viewvc/blink?view=rev&revision=171983 Review URL: https://codereview.chromium.org/236203020 git-svn-id: svn://svn.chromium.org/blink/trunk@172331 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) { bool oldHorizontalWritingMode = isHorizontalWritingMode(); RenderBoxModelObject::styleDidChange(diff, oldStyle); RenderStyle* newStyle = style(); if (needsLayout() && oldStyle) { RenderBlock::removePercentHeightDescendantIfNeeded(this); if (isOutOfFlowPositioned() && newStyle->hasStaticBlockPosition(isHorizontalWritingMode()) && oldStyle->marginBefore() != newStyle->marginBefore() && parent() && !parent()->normalChildNeedsLayout()) parent()->setChildNeedsLayout(); } if (RenderBlock::hasPercentHeightContainerMap() && firstChild() && oldHorizontalWritingMode != isHorizontalWritingMode()) RenderBlock::clearPercentHeightDescendantsFrom(this); if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) { if (int left = layer()->scrollableArea()->scrollXOffset()) { left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToXOffset(left); } if (int top = layer()->scrollableArea()->scrollYOffset()) { top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom(); layer()->scrollableArea()->scrollToYOffset(top); } } if (diff.needsRepaint()) { RenderObject* parentToInvalidate = parent(); for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) { parentToInvalidate->invalidateBackgroundObscurationStatus(); parentToInvalidate = parentToInvalidate->parent(); } } if (isDocumentElement() || isBody()) document().view()->recalculateScrollbarOverlayStyle(); updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle); updateGridPositionAfterStyleChange(oldStyle); }
171,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CrosLibrary::TestApi::SetKeyboardLibrary( KeyboardLibrary* library, bool own) { library_->keyboard_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::SetKeyboardLibrary(
170,639
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) + len > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); } Commit Message: Prevent arithmetic overflow on bounds check CWE ID: CWE-125
static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl, unsigned char **p, unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t len; ((void) ssl); /* * PSK parameters: * * opaque psk_identity_hint<0..2^16-1>; */ if( (*p) > end - 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } len = (*p)[0] << 8 | (*p)[1]; *p += 2; if( (*p) > end - len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message " "(psk_identity_hint length)" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } /* * Note: we currently ignore the PKS identity hint, as we only allow one * PSK to be provisionned on the client. This could be changed later if * someone needs that feature. */ *p += len; ret = 0; return( ret ); }
170,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BackgroundLoaderOffliner::StartSnapshot() { if (!pending_request_.get()) { DVLOG(1) << "Pending request was cleared during delay."; return; } DCHECK(is_low_bar_met_) << "Minimum quality must have been reached before saving a snapshot"; AddLoadingSignal("Snapshotting"); SavePageRequest request(*pending_request_.get()); if (page_load_state_ != SUCCESS) { Offliner::RequestStatus status; switch (page_load_state_) { case RETRIABLE_NET_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_NET_ERROR; break; case RETRIABLE_HTTP_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_HTTP_ERROR; break; case NONRETRIABLE: status = Offliner::RequestStatus::LOADING_FAILED_NO_RETRY; break; default: NOTREACHED(); status = Offliner::RequestStatus::LOADING_FAILED; } std::move(completion_callback_).Run(request, status); ResetState(); return; } content::WebContents* web_contents( content::WebContentsObserver::web_contents()); Offliner::RequestStatus loaded_page_error = CanSavePageInBackground(web_contents); if (loaded_page_error != Offliner::RequestStatus::UNKNOWN) { std::move(completion_callback_).Run(request, loaded_page_error); ResetState(); return; } save_state_ = SAVING; RequestStats& image_stats = stats_[ResourceDataType::IMAGE]; RequestStats& css_stats = stats_[ResourceDataType::TEXT_CSS]; RequestStats& xhr_stats = stats_[ResourceDataType::XHR]; bool image_complete = (image_stats.requested == image_stats.completed); bool css_complete = (css_stats.requested == css_stats.completed); bool xhr_complete = (xhr_stats.requested == xhr_stats.completed); RecordResourceCompletionUMA(image_complete, css_complete, xhr_complete); if (IsOfflinePagesLoadSignalCollectingEnabled()) { signal_data_.SetDouble("StartedImages", image_stats.requested); signal_data_.SetDouble("CompletedImages", image_stats.completed); signal_data_.SetDouble("StartedCSS", css_stats.requested); signal_data_.SetDouble("CompletedCSS", css_stats.completed); signal_data_.SetDouble("StartedXHR", xhr_stats.requested); signal_data_.SetDouble("CompletedXHR", xhr_stats.completed); std::string headers = base::StringPrintf( "%s\r\n%s\r\n\r\n", kContentTransferEncodingBinary, kXHeaderForSignals); std::string body; base::JSONWriter::Write(signal_data_, &body); std::string content_type = kContentType; std::string content_location = base::StringPrintf( "cid:signal-data-%" PRId64 "@mhtml.blink", request.request_id()); content::MHTMLExtraParts* extra_parts = content::MHTMLExtraParts::FromWebContents(web_contents); DCHECK(extra_parts); if (extra_parts != nullptr) { extra_parts->AddExtraMHTMLPart(content_type, content_location, headers, body); } } std::unique_ptr<OfflinePageArchiver> archiver(new OfflinePageMHTMLArchiver()); OfflinePageModel::SavePageParams params; params.url = web_contents->GetLastCommittedURL(); params.client_id = request.client_id(); params.proposed_offline_id = request.request_id(); params.is_background = true; params.use_page_problem_detectors = true; params.request_origin = request.request_origin(); if (!request.original_url().is_empty()) params.original_url = request.original_url(); else if (params.url != request.url()) params.original_url = request.url(); offline_page_model_->SavePage( params, std::move(archiver), web_contents, base::Bind(&BackgroundLoaderOffliner::OnPageSaved, weak_ptr_factory_.GetWeakPtr())); } Commit Message: Remove unused histograms from the background loader offliner. Bug: 975512 Change-Id: I87b0a91bed60e3a9e8a1fd9ae9b18cac27a0859f Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1683361 Reviewed-by: Cathy Li <[email protected]> Reviewed-by: Steven Holte <[email protected]> Commit-Queue: Peter Williamson <[email protected]> Cr-Commit-Position: refs/heads/master@{#675332} CWE ID: CWE-119
void BackgroundLoaderOffliner::StartSnapshot() { if (!pending_request_.get()) { DVLOG(1) << "Pending request was cleared during delay."; return; } DCHECK(is_low_bar_met_) << "Minimum quality must have been reached before saving a snapshot"; AddLoadingSignal("Snapshotting"); SavePageRequest request(*pending_request_.get()); if (page_load_state_ != SUCCESS) { Offliner::RequestStatus status; switch (page_load_state_) { case RETRIABLE_NET_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_NET_ERROR; break; case RETRIABLE_HTTP_ERROR: status = Offliner::RequestStatus::LOADING_FAILED_HTTP_ERROR; break; case NONRETRIABLE: status = Offliner::RequestStatus::LOADING_FAILED_NO_RETRY; break; default: NOTREACHED(); status = Offliner::RequestStatus::LOADING_FAILED; } std::move(completion_callback_).Run(request, status); ResetState(); return; } content::WebContents* web_contents( content::WebContentsObserver::web_contents()); Offliner::RequestStatus loaded_page_error = CanSavePageInBackground(web_contents); if (loaded_page_error != Offliner::RequestStatus::UNKNOWN) { std::move(completion_callback_).Run(request, loaded_page_error); ResetState(); return; } save_state_ = SAVING; RequestStats& image_stats = stats_[ResourceDataType::IMAGE]; RequestStats& css_stats = stats_[ResourceDataType::TEXT_CSS]; RequestStats& xhr_stats = stats_[ResourceDataType::XHR]; if (IsOfflinePagesLoadSignalCollectingEnabled()) { signal_data_.SetDouble("StartedImages", image_stats.requested); signal_data_.SetDouble("CompletedImages", image_stats.completed); signal_data_.SetDouble("StartedCSS", css_stats.requested); signal_data_.SetDouble("CompletedCSS", css_stats.completed); signal_data_.SetDouble("StartedXHR", xhr_stats.requested); signal_data_.SetDouble("CompletedXHR", xhr_stats.completed); std::string headers = base::StringPrintf( "%s\r\n%s\r\n\r\n", kContentTransferEncodingBinary, kXHeaderForSignals); std::string body; base::JSONWriter::Write(signal_data_, &body); std::string content_type = kContentType; std::string content_location = base::StringPrintf( "cid:signal-data-%" PRId64 "@mhtml.blink", request.request_id()); content::MHTMLExtraParts* extra_parts = content::MHTMLExtraParts::FromWebContents(web_contents); DCHECK(extra_parts); if (extra_parts != nullptr) { extra_parts->AddExtraMHTMLPart(content_type, content_location, headers, body); } } std::unique_ptr<OfflinePageArchiver> archiver(new OfflinePageMHTMLArchiver()); OfflinePageModel::SavePageParams params; params.url = web_contents->GetLastCommittedURL(); params.client_id = request.client_id(); params.proposed_offline_id = request.request_id(); params.is_background = true; params.use_page_problem_detectors = true; params.request_origin = request.request_origin(); if (!request.original_url().is_empty()) params.original_url = request.original_url(); else if (params.url != request.url()) params.original_url = request.url(); offline_page_model_->SavePage( params, std::move(archiver), web_contents, base::Bind(&BackgroundLoaderOffliner::OnPageSaved, weak_ptr_factory_.GetWeakPtr())); }
172,484
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlDetectSAX2(ctxt); GROW; if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && (ctxt->input->end - ctxt->input->cur >= 4)) { xmlChar start[4]; xmlCharEncoding enc; start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) xmlSwitchEncoding(ctxt, enc); } if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ ctxt->instate = XML_PARSER_EOF; return; } } if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0"); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL)) xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID); ctxt->instate = XML_PARSER_DTD; ctxt->external = 1; while (((RAW == '<') && (NXT(1) == '?')) || ((RAW == '<') && (NXT(1) == '!')) || (RAW == '%') || IS_BLANK_CH(CUR)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; GROW; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlDetectSAX2(ctxt); GROW; if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && (ctxt->input->end - ctxt->input->cur >= 4)) { xmlChar start[4]; xmlCharEncoding enc; start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) xmlSwitchEncoding(ctxt, enc); } if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ ctxt->instate = XML_PARSER_EOF; return; } } if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0"); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL)) xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID); ctxt->instate = XML_PARSER_DTD; ctxt->external = 1; while (((RAW == '<') && (NXT(1) == '?')) || ((RAW == '<') && (NXT(1) == '!')) || (RAW == '%') || IS_BLANK_CH(CUR)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; GROW; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); } }
171,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool ShouldAutofocus(const HTMLFormControlElement* element) { if (!element->isConnected()) return false; if (!element->IsAutofocusable()) return false; Document& doc = element->GetDocument(); if (doc.IsSandboxed(WebSandboxFlags::kAutomaticFeatures)) { doc.AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kError, "Blocked autofocusing on a form control because the form's frame is " "sandboxed and the 'allow-scripts' permission is not set.")); return false; } if (!doc.IsInMainFrame() && !doc.TopFrameOrigin()->CanAccess(doc.GetSecurityOrigin())) { doc.AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kError, "Blocked autofocusing on a form control in a cross-origin subframe.")); return false; } return true; } Commit Message: autofocus: Fix a crash with an autofocus element in a document without browsing context. ShouldAutofocus() should check existence of the browsing context. Otherwise, doc.TopFrameOrigin() returns null. Before crrev.com/695830, ShouldAutofocus() was called only for rendered elements. That is to say, the document always had browsing context. Bug: 1003228 Change-Id: I2a941c34e9707d44869a6d7585dc7fb9f06e3bf4 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1800902 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Keishi Hattori <[email protected]> Cr-Commit-Position: refs/heads/master@{#696291} CWE ID: CWE-704
static bool ShouldAutofocus(const HTMLFormControlElement* element) { if (!element->isConnected()) return false; if (!element->IsAutofocusable()) return false; Document& doc = element->GetDocument(); if (!doc.GetFrame()) return false; if (doc.IsSandboxed(WebSandboxFlags::kAutomaticFeatures)) { doc.AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kError, "Blocked autofocusing on a form control because the form's frame is " "sandboxed and the 'allow-scripts' permission is not set.")); return false; } if (!doc.IsInMainFrame() && !doc.TopFrameOrigin()->CanAccess(doc.GetSecurityOrigin())) { doc.AddConsoleMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kSecurity, mojom::ConsoleMessageLevel::kError, "Blocked autofocusing on a form control in a cross-origin subframe.")); return false; } return true; }
172,349
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FindBarController::ChangeTabContents(TabContentsWrapper* contents) { if (tab_contents_) { registrar_.RemoveAll(); find_bar_->StopAnimation(); } tab_contents_ = contents; if (find_bar_->IsFindBarVisible() && (!tab_contents_ || !tab_contents_->GetFindManager()->find_ui_active())) { find_bar_->Hide(false); } if (!tab_contents_) return; registrar_.Add(this, NotificationType::FIND_RESULT_AVAILABLE, Source<TabContents>(tab_contents_->tab_contents())); registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, Source<NavigationController>(&tab_contents_->controller())); MaybeSetPrepopulateText(); if (tab_contents_->GetFindManager()->find_ui_active()) { find_bar_->Show(false); } UpdateFindBarForCurrentResult(); } Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature. BUG=71097 TEST=zero visible change Review URL: http://codereview.chromium.org/6480117 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void FindBarController::ChangeTabContents(TabContentsWrapper* contents) { if (tab_contents_) { registrar_.RemoveAll(); find_bar_->StopAnimation(); } tab_contents_ = contents; if (find_bar_->IsFindBarVisible() && (!tab_contents_ || !tab_contents_->find_tab_helper()->find_ui_active())) { find_bar_->Hide(false); } if (!tab_contents_) return; registrar_.Add(this, NotificationType::FIND_RESULT_AVAILABLE, Source<TabContents>(tab_contents_->tab_contents())); registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, Source<NavigationController>(&tab_contents_->controller())); MaybeSetPrepopulateText(); if (tab_contents_->find_tab_helper()->find_ui_active()) { find_bar_->Show(false); } UpdateFindBarForCurrentResult(); }
170,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this, image_transform_png_set_palette_to_rgb_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); this->next->mod(this->next, that, pp, display); }
173,639
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static char* get_private_subtags(const char* loc_name) { char* result =NULL; int singletonPos = 0; int len =0; const char* mod_loc_name =NULL; if( loc_name && (len = strlen(loc_name)>0 ) ){ mod_loc_name = loc_name ; len = strlen(mod_loc_name); while( (singletonPos = getSingletonPos(mod_loc_name))!= -1){ if( singletonPos!=-1){ if( (*(mod_loc_name+singletonPos)=='x') || (*(mod_loc_name+singletonPos)=='X') ){ /* private subtag start found */ if( singletonPos + 2 == len){ /* loc_name ends with '-x-' ; return NULL */ } else{ /* result = mod_loc_name + singletonPos +2; */ result = estrndup(mod_loc_name + singletonPos+2 , (len -( singletonPos +2) ) ); } break; } else{ if( singletonPos + 1 >= len){ /* String end */ break; } else { /* singleton found but not a private subtag , hence check further in the string for the private subtag */ mod_loc_name = mod_loc_name + singletonPos +1; len = strlen(mod_loc_name); } } } } /* end of while */ } return result; }
167,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_set_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp palette, int num_palette) { png_debug1(1, "in %s storage function", "PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) png_error(png_ptr, "Invalid palette length"); else { png_warning(png_ptr, "Invalid palette length"); return; } } /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. */ #ifdef PNG_FREE_ME_SUPPORTED png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); #endif /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead * of num_palette entries, in case of an invalid PNG file that has * too-large sample values. */ png_ptr->palette = (png_colorp)png_calloc(png_ptr, PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color)); png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color)); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; #ifdef PNG_FREE_ME_SUPPORTED info_ptr->free_me |= PNG_FREE_PLTE; #else png_ptr->flags |= PNG_FLAG_FREE_PLTE; #endif info_ptr->valid |= PNG_INFO_PLTE; } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_set_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp palette, int num_palette) { png_uint_32 max_palette_length; png_debug1(1, "in %s storage function", "PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ? (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH; if (num_palette < 0 || num_palette > (int) max_palette_length) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) png_error(png_ptr, "Invalid palette length"); else { png_warning(png_ptr, "Invalid palette length"); return; } } /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. */ #ifdef PNG_FREE_ME_SUPPORTED png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); #endif /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead * of num_palette entries, in case of an invalid PNG file or incorrect * call to png_set_PLTE() with too-large sample values. */ png_ptr->palette = (png_colorp)png_calloc(png_ptr, PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color)); png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color)); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; #ifdef PNG_FREE_ME_SUPPORTED info_ptr->free_me |= PNG_FREE_PLTE; #else png_ptr->flags |= PNG_FLAG_FREE_PLTE; #endif info_ptr->valid |= PNG_INFO_PLTE; }
172,183
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap) { RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context); ScriptPromise promise = resolver->promise(); resolver->resolve(imageBitmap); return promise; } Commit Message: Fix crash when creating an ImageBitmap from an invalid canvas BUG=354356 Review URL: https://codereview.chromium.org/211313003 git-svn-id: svn://svn.chromium.org/blink/trunk@169973 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
static ScriptPromise fulfillImageBitmap(ExecutionContext* context, PassRefPtrWillBeRawPtr<ImageBitmap> imageBitmap) { RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(context); ScriptPromise promise = resolver->promise(); if (imageBitmap) { resolver->resolve(imageBitmap); } else { v8::Isolate* isolate = ScriptState::current()->isolate(); resolver->reject(ScriptValue(v8::Null(isolate), isolate)); } return promise; }
171,395
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NetworkHandler::SetCookie(const std::string& name, const std::string& value, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, Maybe<bool> secure, Maybe<bool> http_only, Maybe<std::string> same_site, Maybe<double> expires, std::unique_ptr<SetCookieCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &SetCookieOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), name, value, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), secure.fromMaybe(false), http_only.fromMaybe(false), same_site.fromMaybe(""), expires.fromMaybe(-1), base::BindOnce(&CookieSetOnIO, std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::SetCookie(const std::string& name, const std::string& value, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, Maybe<bool> secure, Maybe<bool> http_only, Maybe<std::string> same_site, Maybe<double> expires, std::unique_ptr<SetCookieCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &SetCookieOnIO, base::Unretained(storage_partition_->GetURLRequestContext()), name, value, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), secure.fromMaybe(false), http_only.fromMaybe(false), same_site.fromMaybe(""), expires.fromMaybe(-1), base::BindOnce(&CookieSetOnIO, std::move(callback)))); }
172,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if ((id == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } Commit Message: Added check for out of bounds read (https://github.com/ImageMagick/ImageMagick/issues/108). CWE ID: CWE-125
static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } }
168,796
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); }
172,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: main(void) { unsigned int i; unsigned char buf[MAX_LENGTH]; unsigned long crc; unsigned char c; int inchar; /* Skip 8-byte signature */ for (i=8; i; i--) { c=GETBREAK; putchar(c); } if (inchar != EOF) for (;;) { /* Read the length */ unsigned long length; /* must be 32 bits! */ c=GETBREAK; buf[0] = c; length = c; length <<= 8; c=GETBREAK; buf[1] = c; length += c; length <<= 8; c=GETBREAK; buf[2] = c; length += c; length <<= 8; c=GETBREAK; buf[3] = c; length += c; /* Read the chunkname */ c=GETBREAK; buf[4] = c; c=GETBREAK; buf[5] = c; c=GETBREAK; buf[6] = c; c=GETBREAK; buf[7] = c; /* The iTXt chunk type expressed as integers is (105, 84, 88, 116) */ if (buf[4] == 105 && buf[5] == 84 && buf[6] == 88 && buf[7] == 116) { if (length >= MAX_LENGTH-12) break; /* To do: handle this more gracefully */ /* Initialize the CRC */ crc = crc32(0, Z_NULL, 0); /* Copy the data bytes */ for (i=8; i < length + 12; i++) { c=GETBREAK; buf[i] = c; } /* Calculate the CRC */ crc = crc32(crc, buf+4, (uInt)length+4); for (;;) { /* Check the CRC */ if (((crc >> 24) & 0xff) == buf[length+8] && ((crc >> 16) & 0xff) == buf[length+9] && ((crc >> 8) & 0xff) == buf[length+10] && ((crc ) & 0xff) == buf[length+11]) break; length++; if (length >= MAX_LENGTH-12) break; c=GETBREAK; buf[length+11]=c; /* Update the CRC */ crc = crc32(crc, buf+7+length, 1); } /* Update length bytes */ buf[0] = (unsigned char)((length << 24) & 0xff); buf[1] = (unsigned char)((length << 16) & 0xff); buf[2] = (unsigned char)((length << 8) & 0xff); buf[3] = (unsigned char)((length ) & 0xff); /* Write the fixed iTXt chunk (length, name, data, crc) */ for (i=0; i<length+12; i++) putchar(buf[i]); } else { /* Copy bytes that were already read (length and chunk name) */ for (i=0; i<8; i++) putchar(buf[i]); /* Copy data bytes and CRC */ for (i=8; i< length+12; i++) { c=GETBREAK; putchar(c); } if (inchar == EOF) { break; } /* The IEND chunk type expressed as integers is (73, 69, 78, 68) */ if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68) break; } if (inchar == EOF) break; if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68) break; } return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
main(void) { unsigned int i; unsigned char buf[MAX_LENGTH]; unsigned long crc; unsigned char c; int inchar; /* Skip 8-byte signature */ for (i=8; i; i--) { GETBREAK; putchar(c); } if (inchar == c) /* !EOF */ for (;;) { /* Read the length */ unsigned long length; /* must be 32 bits! */ GETBREAK; buf[0] = c; length = c; length <<= 8; GETBREAK; buf[1] = c; length += c; length <<= 8; GETBREAK; buf[2] = c; length += c; length <<= 8; GETBREAK; buf[3] = c; length += c; /* Read the chunkname */ GETBREAK; buf[4] = c; GETBREAK; buf[5] = c; GETBREAK; buf[6] = c; GETBREAK; buf[7] = c; /* The iTXt chunk type expressed as integers is (105, 84, 88, 116) */ if (buf[4] == 105 && buf[5] == 84 && buf[6] == 88 && buf[7] == 116) { if (length >= MAX_LENGTH-12) break; /* To do: handle this more gracefully */ /* Initialize the CRC */ crc = crc32(0, Z_NULL, 0); /* Copy the data bytes */ for (i=8; i < length + 12; i++) { GETBREAK; buf[i] = c; } if (inchar != c) /* EOF */ break; /* Calculate the CRC */ crc = crc32(crc, buf+4, (uInt)length+4); for (;;) { /* Check the CRC */ if (((crc >> 24) & 0xffU) == buf[length+8] && ((crc >> 16) & 0xffU) == buf[length+9] && ((crc >> 8) & 0xffU) == buf[length+10] && ((crc ) & 0xffU) == buf[length+11]) break; length++; if (length >= MAX_LENGTH-12) break; GETBREAK; buf[length+11] = c; /* Update the CRC */ crc = crc32(crc, buf+7+length, 1); } if (inchar != c) /* EOF */ break; /* Update length bytes */ buf[0] = (unsigned char)((length >> 24) & 0xffU); buf[1] = (unsigned char)((length >> 16) & 0xffU); buf[2] = (unsigned char)((length >> 8) & 0xffU); buf[3] = (unsigned char)((length ) & 0xffU); /* Write the fixed iTXt chunk (length, name, data, crc) */ for (i=0; i<length+12; i++) putchar(buf[i]); } else { if (inchar != c) /* EOF */ break; /* Copy bytes that were already read (length and chunk name) */ for (i=0; i<8; i++) putchar(buf[i]); /* Copy data bytes and CRC */ for (i=8; i< length+12; i++) { GETBREAK; putchar(c); } if (inchar != c) /* EOF */ { break; } /* The IEND chunk type expressed as integers is (73, 69, 78, 68) */ if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68) break; } if (inchar != c) /* EOF */ break; if (buf[4] == 73 && buf[5] == 69 && buf[6] == 78 && buf[7] == 68) break; } return 0; }
173,727
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cg_getattr(const char *path, struct stat *sb) { struct timespec now; struct fuse_context *fc = fuse_get_context(); char * cgdir = NULL; char *fpath = NULL, *path1, *path2; struct cgfs_files *k = NULL; const char *cgroup; const char *controller = NULL; int ret = -ENOENT; if (!fc) return -EIO; memset(sb, 0, sizeof(struct stat)); if (clock_gettime(CLOCK_REALTIME, &now) < 0) return -EINVAL; sb->st_uid = sb->st_gid = 0; sb->st_atim = sb->st_mtim = sb->st_ctim = now; sb->st_size = 0; if (strcmp(path, "/cgroup") == 0) { sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { path1 = "/"; path2 = cgdir; } else { path1 = cgdir; path2 = fpath; } /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys. * Then check that caller's cgroup is under path if fpath is a child * cgroup, or cgdir if fpath is a file */ if (is_child_cgroup(controller, path1, path2)) { if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00555; sb->st_nlink = 2; ret = 0; goto out; } if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) { ret = -EACCES; goto out; } sb->st_mode = S_IFDIR | 00755; k = cgfs_get_key(controller, cgroup, "tasks"); if (!k) { sb->st_uid = sb->st_gid = 0; } else { sb->st_uid = k->uid; sb->st_gid = k->gid; } free_key(k); sb->st_nlink = 2; ret = 0; goto out; } if ((k = cgfs_get_key(controller, path1, path2)) != NULL) { sb->st_mode = S_IFREG | k->mode; sb->st_nlink = 1; sb->st_uid = k->uid; sb->st_gid = k->gid; sb->st_size = 0; free_key(k); if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) { ret = -EACCES; goto out; } ret = 0; } out: free(cgdir); return ret; } Commit Message: Fix checking of parent directories Taken from the justification in the launchpad bug: To a task in freezer cgroup /a/b/c/d, it should appear that there are no cgroups other than its descendents. Since this is a filesystem, we must have the parent directories, but each parent cgroup should only contain the child which the task can see. So, when this task looks at /a/b, it should see only directory 'c' and no files. Attempt to create /a/b/x should result in -EPERM, whether /a/b/x already exists or not. Attempts to query /a/b/x should result in -ENOENT whether /a/b/x exists or not. Opening /a/b/tasks should result in -ENOENT. The caller_may_see_dir checks specifically whether a task may see a cgroup directory - i.e. /a/b/x if opening /a/b/x/tasks, and /a/b/c/d if doing opendir('/a/b/c/d'). caller_is_in_ancestor() will return true if the caller in /a/b/c/d looks at /a/b/c/d/e. If the caller is in a child cgroup of the queried one - i.e. if the task in /a/b/c/d queries /a/b, then *nextcg will container the next (the only) directory which he can see in the path - 'c'. Beyond this, regular DAC permissions should apply, with the root-in-user-namespace privilege over its mapped uids being respected. The fc_may_access check does this check for both directories and files. This is CVE-2015-1342 (LP: #1508481) Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static int cg_getattr(const char *path, struct stat *sb) { struct timespec now; struct fuse_context *fc = fuse_get_context(); char * cgdir = NULL; char *fpath = NULL, *path1, *path2; struct cgfs_files *k = NULL; const char *cgroup; const char *controller = NULL; int ret = -ENOENT; if (!fc) return -EIO; memset(sb, 0, sizeof(struct stat)); if (clock_gettime(CLOCK_REALTIME, &now) < 0) return -EINVAL; sb->st_uid = sb->st_gid = 0; sb->st_atim = sb->st_mtim = sb->st_ctim = now; sb->st_size = 0; if (strcmp(path, "/cgroup") == 0) { sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } controller = pick_controller_from_path(fc, path); if (!controller) return -EIO; cgroup = find_cgroup_in_path(path); if (!cgroup) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00755; sb->st_nlink = 2; return 0; } get_cgdir_and_path(cgroup, &cgdir, &fpath); if (!fpath) { path1 = "/"; path2 = cgdir; } else { path1 = cgdir; path2 = fpath; } /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys. * Then check that caller's cgroup is under path if fpath is a child * cgroup, or cgdir if fpath is a file */ if (is_child_cgroup(controller, path1, path2)) { if (!caller_may_see_dir(fc->pid, controller, cgroup)) { ret = -ENOENT; goto out; } if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { /* this is just /cgroup/controller, return it as a dir */ sb->st_mode = S_IFDIR | 00555; sb->st_nlink = 2; ret = 0; goto out; } if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) { ret = -EACCES; goto out; } sb->st_mode = S_IFDIR | 00755; k = cgfs_get_key(controller, cgroup, "tasks"); if (!k) { sb->st_uid = sb->st_gid = 0; } else { sb->st_uid = k->uid; sb->st_gid = k->gid; } free_key(k); sb->st_nlink = 2; ret = 0; goto out; } if ((k = cgfs_get_key(controller, path1, path2)) != NULL) { sb->st_mode = S_IFREG | k->mode; sb->st_nlink = 1; sb->st_uid = k->uid; sb->st_gid = k->gid; sb->st_size = 0; free_key(k); if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { ret = -ENOENT; goto out; } if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) { ret = -EACCES; goto out; } ret = 0; } out: free(cgdir); return ret; }
166,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile) : profile_(profile), push_subscription_count_(0), pending_push_subscription_count_(0), notification_manager_(profile), push_messaging_service_observer_(PushMessagingServiceObserver::Create()), weak_factory_(this) { DCHECK(profile); HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this); registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); } Commit Message: Remove some senseless indirection from the Push API code Four files to call one Java function. Let's just call it directly. BUG= Change-Id: I6e988e9a000051dd7e3dd2b517a33a09afc2fff6 Reviewed-on: https://chromium-review.googlesource.com/749147 Reviewed-by: Anita Woodruff <[email protected]> Commit-Queue: Peter Beverloo <[email protected]> Cr-Commit-Position: refs/heads/master@{#513464} CWE ID: CWE-119
PushMessagingServiceImpl::PushMessagingServiceImpl(Profile* profile) : profile_(profile), push_subscription_count_(0), pending_push_subscription_count_(0), notification_manager_(profile), weak_factory_(this) { DCHECK(profile); HostContentSettingsMapFactory::GetForProfile(profile_)->AddObserver(this); registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING, content::NotificationService::AllSources()); }
172,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int NsGetParameter(preproc_effect_t *effect, void *pParam, uint32_t *pValueSize, void *pValue) { int status = 0; return status; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int NsGetParameter(preproc_effect_t *effect, int NsGetParameter(preproc_effect_t *effect __unused, void *pParam __unused, uint32_t *pValueSize __unused, void *pValue __unused) { int status = 0; return status; }
173,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); } Commit Message: disallow creation (of empty files) in read-only mode; reported by Michal Zalewski, feedback & ok deraadt@ CWE ID: CWE-269
process_open(u_int32_t id) { u_int32_t pflags; Attrib a; char *name; int r, handle, fd, flags, mode, status = SSH2_FX_FAILURE; if ((r = sshbuf_get_cstring(iqueue, &name, NULL)) != 0 || (r = sshbuf_get_u32(iqueue, &pflags)) != 0 || /* portable flags */ (r = decode_attrib(iqueue, &a)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); debug3("request %u: open flags %d", id, pflags); flags = flags_from_portable(pflags); mode = (a.flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a.perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) != O_RDONLY || (flags & (O_CREAT|O_TRUNC)) != 0)) { verbose("Refusing open request in read-only mode"); status = SSH2_FX_PERMISSION_DENIED; } else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, flags, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); free(name); }
167,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static InputMethodStatusConnection* GetInstance() { return Singleton<InputMethodStatusConnection, LeakySingletonTraits<InputMethodStatusConnection> >::get(); } 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 InputMethodStatusConnection* GetInstance() { virtual void Connect() { MaybeRestoreConnections(); }
170,535
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: do_uncompress( compress_filter_context_t *zfx, z_stream *zs, IOBUF a, size_t *ret_len ) { int zrc; int rc=0; size_t n; int nread, count; int refill = !zs->avail_in; if( DBG_FILTER ) log_debug("begin inflate: avail_in=%u, avail_out=%u, inbuf=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, (unsigned)zfx->inbufsize ); do { if( zs->avail_in < zfx->inbufsize && refill ) { n = zs->avail_in; if( !n ) zs->next_in = BYTEF_CAST (zfx->inbuf); count = zfx->inbufsize - n; nread = iobuf_read( a, zfx->inbuf + n, count ); nread = iobuf_read( a, zfx->inbuf + n, count ); if( nread == -1 ) nread = 0; n += nread; /* If we use the undocumented feature to suppress * the zlib header, we have to give inflate an * extra dummy byte to read */ if( nread < count && zfx->algo == 1 ) { *(zfx->inbuf + n) = 0xFF; /* is it really needed ? */ zfx->algo1hack = 1; n++; } zs->avail_in = n; } log_debug("enter inflate: avail_in=%u, avail_out=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out); zrc = inflate ( zs, Z_SYNC_FLUSH ); if( DBG_FILTER ) log_debug("leave inflate: avail_in=%u, avail_out=%u, zrc=%d\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, zrc); if( zrc == Z_STREAM_END ) rc = -1; /* eof */ else if( zrc != Z_OK && zrc != Z_BUF_ERROR ) { if( zs->msg ) log_fatal("zlib inflate problem: %s\n", zs->msg ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); } } while( zs->avail_out && zrc != Z_STREAM_END && zrc != Z_BUF_ERROR ); *ret_len = zfx->outbufsize - zs->avail_out; if( DBG_FILTER ) } Commit Message: CWE ID: CWE-20
do_uncompress( compress_filter_context_t *zfx, z_stream *zs, IOBUF a, size_t *ret_len ) { int zrc; int rc = 0; int leave = 0; size_t n; int nread, count; int refill = !zs->avail_in; if( DBG_FILTER ) log_debug("begin inflate: avail_in=%u, avail_out=%u, inbuf=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, (unsigned)zfx->inbufsize ); do { if( zs->avail_in < zfx->inbufsize && refill ) { n = zs->avail_in; if( !n ) zs->next_in = BYTEF_CAST (zfx->inbuf); count = zfx->inbufsize - n; nread = iobuf_read( a, zfx->inbuf + n, count ); nread = iobuf_read( a, zfx->inbuf + n, count ); if( nread == -1 ) nread = 0; n += nread; /* Algo 1 has no zlib header which requires us to to give * inflate an extra dummy byte to read. To be on the safe * side we allow for up to 4 ff bytes. */ if( nread < count && zfx->algo == 1 && zfx->algo1hack < 4) { *(zfx->inbuf + n) = 0xFF; zfx->algo1hack++; n++; leave = 1; } zs->avail_in = n; } log_debug("enter inflate: avail_in=%u, avail_out=%u\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out); zrc = inflate ( zs, Z_SYNC_FLUSH ); if( DBG_FILTER ) log_debug("leave inflate: avail_in=%u, avail_out=%u, zrc=%d\n", (unsigned)zs->avail_in, (unsigned)zs->avail_out, zrc); if( zrc == Z_STREAM_END ) rc = -1; /* eof */ else if( zrc != Z_OK && zrc != Z_BUF_ERROR ) { if( zs->msg ) log_fatal("zlib inflate problem: %s\n", zs->msg ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); else log_fatal("zlib inflate problem: rc=%d\n", zrc ); } } while (zs->avail_out && zrc != Z_STREAM_END && zrc != Z_BUF_ERROR && !leave); *ret_len = zfx->outbufsize - zs->avail_out; if( DBG_FILTER ) }
165,053
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if ( sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) == 3 ) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } } Commit Message: Issue #287: made CSR/CSC readers more robust against invalid input (case #1). CWE ID: CWE-119
void edge_sparse_csr_reader_double( const char* i_csr_file_in, unsigned int** o_row_idx, unsigned int** o_column_idx, double** o_values, unsigned int* o_row_count, unsigned int* o_column_count, unsigned int* o_element_count ) { FILE *l_csr_file_handle; const unsigned int l_line_length = 512; char l_line[512/*l_line_length*/+1]; unsigned int l_header_read = 0; unsigned int* l_row_idx_id = NULL; unsigned int l_i = 0; l_csr_file_handle = fopen( i_csr_file_in, "r" ); if ( l_csr_file_handle == NULL ) { fprintf( stderr, "cannot open CSR file!\n" ); return; } while (fgets(l_line, l_line_length, l_csr_file_handle) != NULL) { if ( strlen(l_line) == l_line_length ) { fprintf( stderr, "could not read file length!\n" ); return; } /* check if we are still reading comments header */ if ( l_line[0] == '%' ) { continue; } else { /* if we are the first line after comment header, we allocate our data structures */ if ( l_header_read == 0 ) { if (3 == sscanf(l_line, "%u %u %u", o_row_count, o_column_count, o_element_count) && 0 != *o_row_count && 0 != *o_column_count && 0 != *o_element_count) { /* allocate CSC datastructure matching mtx file */ *o_column_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_element_count)); *o_row_idx = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count + 1)); *o_values = (double*) malloc(sizeof(double) * (*o_element_count)); l_row_idx_id = (unsigned int*) malloc(sizeof(unsigned int) * (*o_row_count)); /* check if mallocs were successful */ if ( ( *o_row_idx == NULL ) || ( *o_column_idx == NULL ) || ( *o_values == NULL ) || ( l_row_idx_id == NULL ) ) { fprintf( stderr, "could not allocate sp data!\n" ); return; } /* set everything to zero for init */ memset(*o_row_idx, 0, sizeof(unsigned int)*(*o_row_count + 1)); memset(*o_column_idx, 0, sizeof(unsigned int)*(*o_element_count)); memset(*o_values, 0, sizeof(double)*(*o_element_count)); memset(l_row_idx_id, 0, sizeof(unsigned int)*(*o_row_count)); /* init column idx */ for ( l_i = 0; l_i < (*o_row_count + 1); l_i++) (*o_row_idx)[l_i] = (*o_element_count); /* init */ (*o_row_idx)[0] = 0; l_i = 0; l_header_read = 1; } else { fprintf( stderr, "could not csr description!\n" ); return; } /* now we read the actual content */ } else { unsigned int l_row, l_column; double l_value; /* read a line of content */ if ( sscanf(l_line, "%u %u %lf", &l_row, &l_column, &l_value) != 3 ) { fprintf( stderr, "could not read element!\n" ); return; } /* adjust numbers to zero termination */ l_row--; l_column--; /* add these values to row and value structure */ (*o_column_idx)[l_i] = l_column; (*o_values)[l_i] = l_value; l_i++; /* handle columns, set id to own for this column, yeah we need to handle empty columns */ l_row_idx_id[l_row] = 1; (*o_row_idx)[l_row+1] = l_i; } } } /* close mtx file */ fclose( l_csr_file_handle ); /* check if we read a file which was consistent */ if ( l_i != (*o_element_count) ) { fprintf( stderr, "we were not able to read all elements!\n" ); return; } /* let's handle empty rows */ for ( l_i = 0; l_i < (*o_row_count); l_i++) { if ( l_row_idx_id[l_i] == 0 ) { (*o_row_idx)[l_i+1] = (*o_row_idx)[l_i]; } } /* free helper data structure */ if ( l_row_idx_id != NULL ) { free( l_row_idx_id ); } }
168,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int perf_pmu_register(struct pmu *pmu, const char *name, int type) { int cpu, ret; mutex_lock(&pmus_lock); ret = -ENOMEM; pmu->pmu_disable_count = alloc_percpu(int); if (!pmu->pmu_disable_count) goto unlock; pmu->type = -1; if (!name) goto skip_type; pmu->name = name; if (type < 0) { type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL); if (type < 0) { ret = type; goto free_pdc; } } pmu->type = type; if (pmu_bus_running) { ret = pmu_dev_alloc(pmu); if (ret) goto free_idr; } skip_type: pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr); if (pmu->pmu_cpu_context) goto got_cpu_context; ret = -ENOMEM; pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context); if (!pmu->pmu_cpu_context) goto free_dev; for_each_possible_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); __perf_event_init_context(&cpuctx->ctx); lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); cpuctx->ctx.type = cpu_context; cpuctx->ctx.pmu = pmu; __perf_cpu_hrtimer_init(cpuctx, cpu); INIT_LIST_HEAD(&cpuctx->rotation_list); cpuctx->unique_pmu = pmu; } got_cpu_context: if (!pmu->start_txn) { if (pmu->pmu_enable) { /* * If we have pmu_enable/pmu_disable calls, install * transaction stubs that use that to try and batch * hardware accesses. */ pmu->start_txn = perf_pmu_start_txn; pmu->commit_txn = perf_pmu_commit_txn; pmu->cancel_txn = perf_pmu_cancel_txn; } else { pmu->start_txn = perf_pmu_nop_void; pmu->commit_txn = perf_pmu_nop_int; pmu->cancel_txn = perf_pmu_nop_void; } } if (!pmu->pmu_enable) { pmu->pmu_enable = perf_pmu_nop_void; pmu->pmu_disable = perf_pmu_nop_void; } if (!pmu->event_idx) pmu->event_idx = perf_event_idx_default; list_add_rcu(&pmu->entry, &pmus); ret = 0; unlock: mutex_unlock(&pmus_lock); return ret; free_dev: device_del(pmu->dev); put_device(pmu->dev); free_idr: if (pmu->type >= PERF_TYPE_MAX) idr_remove(&pmu_idr, pmu->type); free_pdc: free_percpu(pmu->pmu_disable_count); goto unlock; } Commit Message: perf: Tighten (and fix) the grouping condition The fix from 9fc81d87420d ("perf: Fix events installation during moving group") was incomplete in that it failed to recognise that creating a group with events for different CPUs is semantically broken -- they cannot be co-scheduled. Furthermore, it leads to real breakage where, when we create an event for CPU Y and then migrate it to form a group on CPU X, the code gets confused where the counter is programmed -- triggered in practice as well by me via the perf fuzzer. Fix this by tightening the rules for creating groups. Only allow grouping of counters that can be co-scheduled in the same context. This means for the same task and/or the same cpu. Fixes: 9fc81d87420d ("perf: Fix events installation during moving group") Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
int perf_pmu_register(struct pmu *pmu, const char *name, int type) { int cpu, ret; mutex_lock(&pmus_lock); ret = -ENOMEM; pmu->pmu_disable_count = alloc_percpu(int); if (!pmu->pmu_disable_count) goto unlock; pmu->type = -1; if (!name) goto skip_type; pmu->name = name; if (type < 0) { type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL); if (type < 0) { ret = type; goto free_pdc; } } pmu->type = type; if (pmu_bus_running) { ret = pmu_dev_alloc(pmu); if (ret) goto free_idr; } skip_type: pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr); if (pmu->pmu_cpu_context) goto got_cpu_context; ret = -ENOMEM; pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context); if (!pmu->pmu_cpu_context) goto free_dev; for_each_possible_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); __perf_event_init_context(&cpuctx->ctx); lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); cpuctx->ctx.pmu = pmu; __perf_cpu_hrtimer_init(cpuctx, cpu); INIT_LIST_HEAD(&cpuctx->rotation_list); cpuctx->unique_pmu = pmu; } got_cpu_context: if (!pmu->start_txn) { if (pmu->pmu_enable) { /* * If we have pmu_enable/pmu_disable calls, install * transaction stubs that use that to try and batch * hardware accesses. */ pmu->start_txn = perf_pmu_start_txn; pmu->commit_txn = perf_pmu_commit_txn; pmu->cancel_txn = perf_pmu_cancel_txn; } else { pmu->start_txn = perf_pmu_nop_void; pmu->commit_txn = perf_pmu_nop_int; pmu->cancel_txn = perf_pmu_nop_void; } } if (!pmu->pmu_enable) { pmu->pmu_enable = perf_pmu_nop_void; pmu->pmu_disable = perf_pmu_nop_void; } if (!pmu->event_idx) pmu->event_idx = perf_event_idx_default; list_add_rcu(&pmu->entry, &pmus); ret = 0; unlock: mutex_unlock(&pmus_lock); return ret; free_dev: device_del(pmu->dev); put_device(pmu->dev); free_idr: if (pmu->type >= PERF_TYPE_MAX) idr_remove(&pmu_idr, pmu->type); free_pdc: free_percpu(pmu->pmu_disable_count); goto unlock; }
168,852
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size()) { return BAD_VALUE; } BufferMeta *buffer_meta = new BufferMeta(params, portIndex, true); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::allocateBufferWithBackup( OMX_U32 portIndex, const sp<IMemory> &params, OMX::buffer_id *buffer, OMX_U32 allottedSize) { if (params == NULL || buffer == NULL) { ALOGE("b/25884056"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); if (allottedSize > params->size() || portIndex >= NELEM(mNumPortBuffers)) { return BAD_VALUE; } // metadata buffers are not connected cross process; only copy if not meta bool copy = mMetadataType[portIndex] == kMetadataBufferTypeInvalid; BufferMeta *buffer_meta = new BufferMeta( params, portIndex, (portIndex == kPortIndexInput) && copy /* copyToOmx */, (portIndex == kPortIndexOutput) && copy /* copyFromOmx */, NULL /* data */); OMX_BUFFERHEADERTYPE *header; OMX_ERRORTYPE err = OMX_AllocateBuffer( mHandle, &header, portIndex, buffer_meta, allottedSize); if (err != OMX_ErrorNone) { CLOG_ERROR(allocateBufferWithBackup, err, SIMPLE_BUFFER(portIndex, (size_t)allottedSize, params->pointer())); delete buffer_meta; buffer_meta = NULL; *buffer = 0; return StatusFromOMXError(err); } CHECK_EQ(header->pAppPrivate, buffer_meta); memset(header->pBuffer, 0, header->nAllocLen); *buffer = makeBufferID(header); addActiveBuffer(portIndex, *buffer); sp<GraphicBufferSource> bufferSource(getGraphicBufferSource()); if (bufferSource != NULL && portIndex == kPortIndexInput) { bufferSource->addCodecBuffer(header); } CLOG_BUFFER(allocateBufferWithBackup, NEW_BUFFER_FMT(*buffer, portIndex, "%zu@%p :> %u@%p", params->size(), params->pointer(), allottedSize, header->pBuffer)); return OK; }
174,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1) - 1; defaultoptions(&h); lua_settop(L, 2); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); luaL_checkstack(L, 1, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); break; } case 'c': { if (size == 0) { if (!lua_isnumber(L, -1)) luaL_error(L, "format `c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); return lua_gettop(L) - 2; } Commit Message: Security: update Lua struct package for security. During an auditing Apple found that the "struct" Lua package we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains a security problem. A bound-checking statement fails because of integer overflow. The bug exists since we initially integrated this package with Lua, when scripting was introduced, so every version of Redis with EVAL/EVALSHA capabilities exposed is affected. Instead of just fixing the bug, the library was updated to the latest version shipped by the author. CWE ID: CWE-190
static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1) - 1; int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; }
170,163
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer) { usb_kill_urb(mixer->urb); usb_kill_urb(mixer->rc_urb); } Commit Message: ALSA: usb-audio: Kill stray URB at exiting USB-audio driver may leave a stray URB for the mixer interrupt when it exits by some error during probe. This leads to a use-after-free error as spotted by syzkaller like: ================================================================== BUG: KASAN: use-after-free in snd_usb_mixer_interrupt+0x604/0x6f0 Call Trace: <IRQ> __dump_stack lib/dump_stack.c:16 dump_stack+0x292/0x395 lib/dump_stack.c:52 print_address_description+0x78/0x280 mm/kasan/report.c:252 kasan_report_error mm/kasan/report.c:351 kasan_report+0x23d/0x350 mm/kasan/report.c:409 __asan_report_load8_noabort+0x19/0x20 mm/kasan/report.c:430 snd_usb_mixer_interrupt+0x604/0x6f0 sound/usb/mixer.c:2490 __usb_hcd_giveback_urb+0x2e0/0x650 drivers/usb/core/hcd.c:1779 .... Allocated by task 1484: save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59 save_stack+0x43/0xd0 mm/kasan/kasan.c:447 set_track mm/kasan/kasan.c:459 kasan_kmalloc+0xad/0xe0 mm/kasan/kasan.c:551 kmem_cache_alloc_trace+0x11e/0x2d0 mm/slub.c:2772 kmalloc ./include/linux/slab.h:493 kzalloc ./include/linux/slab.h:666 snd_usb_create_mixer+0x145/0x1010 sound/usb/mixer.c:2540 create_standard_mixer_quirk+0x58/0x80 sound/usb/quirks.c:516 snd_usb_create_quirk+0x92/0x100 sound/usb/quirks.c:560 create_composite_quirk+0x1c4/0x3e0 sound/usb/quirks.c:59 snd_usb_create_quirk+0x92/0x100 sound/usb/quirks.c:560 usb_audio_probe+0x1040/0x2c10 sound/usb/card.c:618 .... Freed by task 1484: save_stack_trace+0x1b/0x20 arch/x86/kernel/stacktrace.c:59 save_stack+0x43/0xd0 mm/kasan/kasan.c:447 set_track mm/kasan/kasan.c:459 kasan_slab_free+0x72/0xc0 mm/kasan/kasan.c:524 slab_free_hook mm/slub.c:1390 slab_free_freelist_hook mm/slub.c:1412 slab_free mm/slub.c:2988 kfree+0xf6/0x2f0 mm/slub.c:3919 snd_usb_mixer_free+0x11a/0x160 sound/usb/mixer.c:2244 snd_usb_mixer_dev_free+0x36/0x50 sound/usb/mixer.c:2250 __snd_device_free+0x1ff/0x380 sound/core/device.c:91 snd_device_free_all+0x8f/0xe0 sound/core/device.c:244 snd_card_do_free sound/core/init.c:461 release_card_device+0x47/0x170 sound/core/init.c:181 device_release+0x13f/0x210 drivers/base/core.c:814 .... Actually such a URB is killed properly at disconnection when the device gets probed successfully, and what we need is to apply it for the error-path, too. In this patch, we apply snd_usb_mixer_disconnect() at releasing. Also introduce a new flag, disconnected, to struct usb_mixer_interface for not performing the disconnection procedure twice. Reported-by: Andrey Konovalov <[email protected]> Tested-by: Andrey Konovalov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-416
void snd_usb_mixer_disconnect(struct usb_mixer_interface *mixer) { if (mixer->disconnected) return; if (mixer->urb) usb_kill_urb(mixer->urb); if (mixer->rc_urb) usb_kill_urb(mixer->rc_urb); mixer->disconnected = true; }
167,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap, int destroy, struct nlmsghdr *nlh, u32 portid) { struct in_ifaddr *promote = NULL; struct in_ifaddr *ifa, *ifa1 = *ifap; struct in_ifaddr *last_prim = in_dev->ifa_list; struct in_ifaddr *prev_prom = NULL; int do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev); ASSERT_RTNL(); /* 1. Deleting primary ifaddr forces deletion all secondaries * unless alias promotion is set **/ if (!(ifa1->ifa_flags & IFA_F_SECONDARY)) { struct in_ifaddr **ifap1 = &ifa1->ifa_next; while ((ifa = *ifap1) != NULL) { if (!(ifa->ifa_flags & IFA_F_SECONDARY) && ifa1->ifa_scope <= ifa->ifa_scope) last_prim = ifa; if (!(ifa->ifa_flags & IFA_F_SECONDARY) || ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) { ifap1 = &ifa->ifa_next; prev_prom = ifa; continue; } if (!do_promote) { inet_hash_remove(ifa); *ifap1 = ifa->ifa_next; rtmsg_ifa(RTM_DELADDR, ifa, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa); inet_free_ifa(ifa); } else { promote = ifa; break; } } } /* On promotion all secondaries from subnet are changing * the primary IP, we must remove all their routes silently * and later to add them back with new prefsrc. Do this * while all addresses are on the device list. */ for (ifa = promote; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask == ifa->ifa_mask && inet_ifa_match(ifa1->ifa_address, ifa)) fib_del_ifaddr(ifa, ifa1); } /* 2. Unlink it */ *ifap = ifa1->ifa_next; inet_hash_remove(ifa1); /* 3. Announce address deletion */ /* Send message first, then call notifier. At first sight, FIB update triggered by notifier will refer to already deleted ifaddr, that could confuse netlink listeners. It is not true: look, gated sees that route deleted and if it still thinks that ifaddr is valid, it will try to restore deleted routes... Grr. So that, this order is correct. */ rtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1); if (promote) { struct in_ifaddr *next_sec = promote->ifa_next; if (prev_prom) { prev_prom->ifa_next = promote->ifa_next; promote->ifa_next = last_prim->ifa_next; last_prim->ifa_next = promote; } promote->ifa_flags &= ~IFA_F_SECONDARY; rtmsg_ifa(RTM_NEWADDR, promote, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_UP, promote); for (ifa = next_sec; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) continue; fib_add_ifaddr(ifa); } } if (destroy) inet_free_ifa(ifa1); } Commit Message: ipv4: Don't do expensive useless work during inetdev destroy. When an inetdev is destroyed, every address assigned to the interface is removed. And in this scenerio we do two pointless things which can be very expensive if the number of assigned interfaces is large: 1) Address promotion. We are deleting all addresses, so there is no point in doing this. 2) A full nf conntrack table purge for every address. We only need to do this once, as is already caught by the existing masq_dev_notifier so masq_inet_event() can skip this. Reported-by: Solar Designer <[email protected]> Signed-off-by: David S. Miller <[email protected]> Tested-by: Cyrill Gorcunov <[email protected]> CWE ID: CWE-399
static void __inet_del_ifa(struct in_device *in_dev, struct in_ifaddr **ifap, int destroy, struct nlmsghdr *nlh, u32 portid) { struct in_ifaddr *promote = NULL; struct in_ifaddr *ifa, *ifa1 = *ifap; struct in_ifaddr *last_prim = in_dev->ifa_list; struct in_ifaddr *prev_prom = NULL; int do_promote = IN_DEV_PROMOTE_SECONDARIES(in_dev); ASSERT_RTNL(); if (in_dev->dead) goto no_promotions; /* 1. Deleting primary ifaddr forces deletion all secondaries * unless alias promotion is set **/ if (!(ifa1->ifa_flags & IFA_F_SECONDARY)) { struct in_ifaddr **ifap1 = &ifa1->ifa_next; while ((ifa = *ifap1) != NULL) { if (!(ifa->ifa_flags & IFA_F_SECONDARY) && ifa1->ifa_scope <= ifa->ifa_scope) last_prim = ifa; if (!(ifa->ifa_flags & IFA_F_SECONDARY) || ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) { ifap1 = &ifa->ifa_next; prev_prom = ifa; continue; } if (!do_promote) { inet_hash_remove(ifa); *ifap1 = ifa->ifa_next; rtmsg_ifa(RTM_DELADDR, ifa, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa); inet_free_ifa(ifa); } else { promote = ifa; break; } } } /* On promotion all secondaries from subnet are changing * the primary IP, we must remove all their routes silently * and later to add them back with new prefsrc. Do this * while all addresses are on the device list. */ for (ifa = promote; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask == ifa->ifa_mask && inet_ifa_match(ifa1->ifa_address, ifa)) fib_del_ifaddr(ifa, ifa1); } no_promotions: /* 2. Unlink it */ *ifap = ifa1->ifa_next; inet_hash_remove(ifa1); /* 3. Announce address deletion */ /* Send message first, then call notifier. At first sight, FIB update triggered by notifier will refer to already deleted ifaddr, that could confuse netlink listeners. It is not true: look, gated sees that route deleted and if it still thinks that ifaddr is valid, it will try to restore deleted routes... Grr. So that, this order is correct. */ rtmsg_ifa(RTM_DELADDR, ifa1, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_DOWN, ifa1); if (promote) { struct in_ifaddr *next_sec = promote->ifa_next; if (prev_prom) { prev_prom->ifa_next = promote->ifa_next; promote->ifa_next = last_prim->ifa_next; last_prim->ifa_next = promote; } promote->ifa_flags &= ~IFA_F_SECONDARY; rtmsg_ifa(RTM_NEWADDR, promote, nlh, portid); blocking_notifier_call_chain(&inetaddr_chain, NETDEV_UP, promote); for (ifa = next_sec; ifa; ifa = ifa->ifa_next) { if (ifa1->ifa_mask != ifa->ifa_mask || !inet_ifa_match(ifa1->ifa_address, ifa)) continue; fib_add_ifaddr(ifa); } } if (destroy) inet_free_ifa(ifa1); }
167,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static v8::Handle<v8::Value> convert1Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert1"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(a*, , V8a::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8a::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert1(); return v8::Handle<v8::Value>(); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static v8::Handle<v8::Value> convert1Callback(const v8::Arguments& args) { INC_STATS("DOM.TestObj.convert1"); if (args.Length() < 1) return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate()); TestObj* imp = V8TestObj::toNative(args.Holder()); EXCEPTION_BLOCK(a*, , V8a::HasInstance(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined)) ? V8a::toNative(v8::Handle<v8::Object>::Cast(MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined))) : 0); imp->convert1(); return v8::Handle<v8::Value>(); }
171,077
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SelectionEditor::NodeChildrenWillBeRemoved(ContainerNode& container) { if (selection_.IsNone()) return; const Position old_base = selection_.base_; const Position old_extent = selection_.extent_; const Position& new_base = ComputePositionForChildrenRemoval(old_base, container); const Position& new_extent = ComputePositionForChildrenRemoval(old_extent, container); if (new_base == old_base && new_extent == old_extent) return; selection_ = SelectionInDOMTree::Builder() .SetBaseAndExtent(new_base, new_extent) .SetIsHandleVisible(selection_.IsHandleVisible()) .Build(); MarkCacheDirty(); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
void SelectionEditor::NodeChildrenWillBeRemoved(ContainerNode& container) { if (selection_.IsNone()) return; const Position old_base = selection_.base_; const Position old_extent = selection_.extent_; const Position& new_base = ComputePositionForChildrenRemoval(old_base, container); const Position& new_extent = ComputePositionForChildrenRemoval(old_extent, container); if (new_base == old_base && new_extent == old_extent) return; selection_ = SelectionInDOMTree::Builder() .SetBaseAndExtent(new_base, new_extent) .Build(); MarkCacheDirty(); }
171,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); }
167,041
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); quantum_info=DestroyQuantumInfo(quantum_info); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); END_OF_READING: clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); } Commit Message: Added check for invalid number of frames. CWE ID: CWE-20
static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image, *image2=NULL, *rotated_image; PixelPacket *q; unsigned int status; MATHeader MATLAB_HDR; size_t size; size_t CellType; QuantumInfo *quantum_info; ImageInfo *clone_info; int i; ssize_t ldblk; unsigned char *BImgBuff = NULL; double MinVal, MaxVal; size_t Unknown6; unsigned z, z2; unsigned Frames; int logging; int sample_size; MagickOffsetType filepos=0x80; BlobInfo *blob; size_t one; unsigned int (*ReadBlobXXXLong)(Image *image); unsigned short (*ReadBlobXXXShort)(Image *image); void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter"); /* Open image file. */ image = AcquireImage(image_info); status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read MATLAB image. */ clone_info=CloneImageInfo(image_info); if(ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0) { image2=ReadMATImageV4(image_info,image,exception); if (image2 == NULL) goto MATLAB_KO; image=image2; goto END_OF_READING; } MATLAB_HDR.Version = ReadBlobLSBShort(image); if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule()," Endian %c%c", MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); if (!strncmp(MATLAB_HDR.EndianIndicator, "IM", 2)) { ReadBlobXXXLong = ReadBlobLSBLong; ReadBlobXXXShort = ReadBlobLSBShort; ReadBlobDoublesXXX = ReadBlobDoublesLSB; ReadBlobFloatsXXX = ReadBlobFloatsLSB; image->endian = LSBEndian; } else if (!strncmp(MATLAB_HDR.EndianIndicator, "MI", 2)) { ReadBlobXXXLong = ReadBlobMSBLong; ReadBlobXXXShort = ReadBlobMSBShort; ReadBlobDoublesXXX = ReadBlobDoublesMSB; ReadBlobFloatsXXX = ReadBlobFloatsMSB; image->endian = MSBEndian; } else goto MATLAB_KO; /* unsupported endian */ if (strncmp(MATLAB_HDR.identific, "MATLAB", 6)) MATLAB_KO: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); filepos = TellBlob(image); while(!EOFBlob(image)) /* object parser loop */ { Frames = 1; (void) SeekBlob(image,filepos,SEEK_SET); /* printf("pos=%X\n",TellBlob(image)); */ MATLAB_HDR.DataType = ReadBlobXXXLong(image); if(EOFBlob(image)) break; MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); if(EOFBlob(image)) break; filepos += MATLAB_HDR.ObjectSize + 4 + 4; image2 = image; #if defined(MAGICKCORE_ZLIB_DELEGATE) if(MATLAB_HDR.DataType == miCOMPRESSED) { image2 = DecompressBlock(image,MATLAB_HDR.ObjectSize,clone_info,exception); if(image2==NULL) continue; MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ } #endif if(MATLAB_HDR.DataType!=miMATRIX) continue; /* skip another objects. */ MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); if(image!=image2) MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); switch(MATLAB_HDR.DimFlag) { case 8: z2=z=1; break; /* 2D matrix*/ case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ Unknown6 = ReadBlobXXXLong(image2); (void) Unknown6; if(z!=3) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); break; case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ if(z!=3 && z!=1) ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); Frames = ReadBlobXXXLong(image2); if (Frames == 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); break; default: ThrowReaderException(CoderError, "MultidimensionalMatricesAreNotSupported"); } MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.StructureClass %d",MATLAB_HDR.StructureClass); if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ MATLAB_HDR.StructureClass != mxINT8_CLASS && MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ MATLAB_HDR.StructureClass != mxINT16_CLASS && MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ MATLAB_HDR.StructureClass != mxINT32_CLASS && MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ MATLAB_HDR.StructureClass != mxINT64_CLASS && MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix"); switch (MATLAB_HDR.NameFlag) { case 0: size = ReadBlobXXXLong(image2); /* Object name string size */ size = 4 * (ssize_t) ((size + 3 + 1) / 4); (void) SeekBlob(image2, size, SEEK_CUR); break; case 1: case 2: case 3: case 4: (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ break; default: goto MATLAB_KO; } CellType = ReadBlobXXXLong(image2); /* Additional object type */ if (logging) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "MATLAB_HDR.CellType: %.20g",(double) CellType); (void) ReadBlob(image2, 4, (unsigned char *) &size); /* data size */ NEXT_FRAME: switch (CellType) { case miINT8: case miUINT8: sample_size = 8; if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) image->depth = 1; else image->depth = 8; /* Byte type cell */ ldblk = (ssize_t) MATLAB_HDR.SizeX; break; case miINT16: case miUINT16: sample_size = 16; image->depth = 16; /* Word type cell */ ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); break; case miINT32: case miUINT32: sample_size = 32; image->depth = 32; /* Dword type cell */ ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miINT64: case miUINT64: sample_size = 64; image->depth = 64; /* Qword type cell */ ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; case miSINGLE: sample_size = 32; image->depth = 32; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex float type cell */ } ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); break; case miDOUBLE: sample_size = 64; image->depth = 64; /* double type cell */ (void) SetImageOption(clone_info,"quantum:format","floating-point"); DisableMSCWarning(4127) if (sizeof(double) != 8) RestoreMSCWarning ThrowReaderException(CoderError, "IncompatibleSizeOfDouble"); if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* complex double type cell */ } ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); break; default: ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix"); } (void) sample_size; image->columns = MATLAB_HDR.SizeX; image->rows = MATLAB_HDR.SizeY; quantum_info=AcquireQuantumInfo(clone_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); one=1; image->colors = one << image->depth; if (image->columns == 0 || image->rows == 0) goto MATLAB_KO; /* Image is gray when no complex flag is set and 2D Matrix */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) { SetImageColorspace(image,GRAYColorspace); image->type=GrayscaleType; } /* If ping is true, then only set image size and colors without reading any image data. */ if (image_info->ping) { size_t temp = image->columns; image->columns = image->rows; image->rows = temp; goto done_reading; /* !!!!!! BAD !!!! */ } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* ----- Load raster data ----- */ BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ if (BImgBuff == NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); MinVal = 0; MaxVal = 0; if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &quantum_info->minimum, &quantum_info->maximum); } /* Main loop for reading all scanlines */ if(z==1) z=0; /* read grey scanlines */ /* else read color scanlines */ do { for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); if (q == (PixelPacket *) NULL) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT set image pixels returns unexpected NULL on a row %u.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto done_reading; /* Skip image rotation, when cannot set image pixels */ } if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT cannot read scanrow %u from a file.", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) { FixLogical((unsigned char *)BImgBuff,ldblk); if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) { ImportQuantumPixelsFailed: if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to ImportQuantumPixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); break; } } else { if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) goto ImportQuantumPixelsFailed; if (z<=1 && /* fix only during a last pass z==0 || z==1 */ (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) FixSignedValues(q,MATLAB_HDR.SizeX); } if (!SyncAuthenticPixels(image,exception)) { if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), " MAT failed to sync image pixels for a row %u", (unsigned)(MATLAB_HDR.SizeY-i-1)); goto ExitLoop; } } } while(z-- >= 2); quantum_info=DestroyQuantumInfo(quantum_info); ExitLoop: /* Read complex part of numbers here */ if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) { /* Find Min and Max Values for complex parts of floats */ CellType = ReadBlobXXXLong(image2); /* Additional object type */ i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ if (CellType==miDOUBLE || CellType==miSINGLE) { CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); } if (CellType==miDOUBLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); InsertComplexDoubleRow((double *)BImgBuff, i, image, MinVal, MaxVal); } if (CellType==miSINGLE) for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) { ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); InsertComplexFloatRow((float *)BImgBuff, i, image, MinVal, MaxVal); } } /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ if ((MATLAB_HDR.DimFlag == 8) && ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) image->type=GrayscaleType; if (image->depth == 1) image->type=BilevelType; if(image2==image) image2 = NULL; /* Remove shadow copy to an image before rotation. */ /* Rotate image. */ rotated_image = RotateImage(image, 90.0, exception); if (rotated_image != (Image *) NULL) { /* Remove page offsets added by RotateImage */ rotated_image->page.x=0; rotated_image->page.y=0; blob = rotated_image->blob; rotated_image->blob = image->blob; rotated_image->colors = image->colors; image->blob = blob; AppendImageToList(&image,rotated_image); DeleteImageFromList(&image); } done_reading: if(image2!=NULL) if(image2!=image) { DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } } } /* Allocate next image structure. */ AcquireNextImage(image_info,image); if (image->next == (Image *) NULL) break; image=SyncNextImageInList(image); image->columns=image->rows=0; image->colors=0; /* row scan buffer is no longer needed */ RelinquishMagickMemory(BImgBuff); BImgBuff = NULL; if(--Frames>0) { z = z2; if(image2==NULL) image2 = image; goto NEXT_FRAME; } if(image2!=NULL) if(image2!=image) /* Does shadow temporary decompressed image exist? */ { /* CloseBlob(image2); */ DeleteImageFromList(&image2); if(clone_info) { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) unlink(clone_info->filename); } } } } RelinquishMagickMemory(BImgBuff); END_OF_READING: clone_info=DestroyImageInfo(clone_info); CloseBlob(image); { Image *p; ssize_t scene=0; /* Rewind list, removing any empty images while rewinding. */ p=image; image=NULL; while (p != (Image *) NULL) { Image *tmp=p; if ((p->rows == 0) || (p->columns == 0)) { p=p->previous; DeleteImageFromList(&tmp); } else { image=p; p=p->previous; } } /* Fix scene numbers */ for (p=image; p != (Image *) NULL; p=p->next) p->scene=scene++; } if(clone_info != NULL) /* cleanup garbage file from compression */ { if(clone_info->file) { fclose(clone_info->file); clone_info->file = NULL; (void) remove_utf8(clone_info->filename); } DestroyImageInfo(clone_info); clone_info = NULL; } if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),"return"); if(image==NULL) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); return (image); }
168,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PropertyTreeManager::SetupRootScrollNode() { cc::ScrollTree& scroll_tree = property_trees_.scroll_tree; scroll_tree.clear(); property_trees_.element_id_to_scroll_node_index.clear(); cc::ScrollNode& scroll_node = *scroll_tree.Node(scroll_tree.Insert(cc::ScrollNode(), kRealRootNodeId)); DCHECK_EQ(scroll_node.id, kSecondaryRootNodeId); scroll_node.transform_id = kSecondaryRootNodeId; scroll_node_map_.Set(ScrollPaintPropertyNode::Root(), scroll_node.id); root_layer_->SetScrollTreeIndex(scroll_node.id); } Commit Message: Reland "[CI] Make paint property nodes non-ref-counted" This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7. Reason for revert: Retry in M69. Original change's description: > Revert "[CI] Make paint property nodes non-ref-counted" > > This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123. > > Reason for revert: Caused bugs found by clusterfuzz > > Original change's description: > > [CI] Make paint property nodes non-ref-counted > > > > Now all paint property nodes are owned by ObjectPaintProperties > > (and LocalFrameView temporarily before removing non-RLS mode). > > Others just use raw pointers or references. > > > > Bug: 833496 > > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae > > Reviewed-on: https://chromium-review.googlesource.com/1031101 > > Reviewed-by: Tien-Ren Chen <[email protected]> > > Commit-Queue: Xianzhu Wang <[email protected]> > > Cr-Commit-Position: refs/heads/master@{#554626} > > [email protected],[email protected],[email protected] > > Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f > No-Presubmit: true > No-Tree-Checks: true > No-Try: true > Bug: 833496,837932,837943 > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 > Reviewed-on: https://chromium-review.googlesource.com/1034292 > Reviewed-by: Xianzhu Wang <[email protected]> > Commit-Queue: Xianzhu Wang <[email protected]> > Cr-Commit-Position: refs/heads/master@{#554653} [email protected],[email protected],[email protected] # Not skipping CQ checks because original CL landed > 1 day ago. Bug: 833496, 837932, 837943 Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992 Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2 Reviewed-on: https://chromium-review.googlesource.com/1083491 Commit-Queue: Xianzhu Wang <[email protected]> Reviewed-by: Xianzhu Wang <[email protected]> Cr-Commit-Position: refs/heads/master@{#563930} CWE ID:
void PropertyTreeManager::SetupRootScrollNode() { cc::ScrollTree& scroll_tree = property_trees_.scroll_tree; scroll_tree.clear(); property_trees_.element_id_to_scroll_node_index.clear(); cc::ScrollNode& scroll_node = *scroll_tree.Node(scroll_tree.Insert(cc::ScrollNode(), kRealRootNodeId)); DCHECK_EQ(scroll_node.id, kSecondaryRootNodeId); scroll_node.transform_id = kSecondaryRootNodeId; scroll_node_map_.Set(&ScrollPaintPropertyNode::Root(), scroll_node.id); root_layer_->SetScrollTreeIndex(scroll_node.id); }
171,830
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: hstore_slice_to_hstore(PG_FUNCTION_ARGS) { HStore *hs = PG_GETARG_HS(0); HEntry *entries = ARRPTR(hs); char *ptr = STRPTR(hs); ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(1); HStore *out; int nkeys; Pairs *key_pairs = hstoreArrayToPairs(key_array, &nkeys); Pairs *out_pairs; int bufsiz; int lastidx = 0; int i; int out_count = 0; if (nkeys == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } out_pairs = palloc(sizeof(Pairs) * nkeys); bufsiz = 0; /* * we exploit the fact that the pairs list is already sorted into strictly * increasing order to narrow the hstoreFindKey search; each search can * start one entry past the previous "found" entry, or at the lower bound * of the last search. */ for (i = 0; i < nkeys; ++i) { int idx = hstoreFindKey(hs, &lastidx, key_pairs[i].key, key_pairs[i].keylen); if (idx >= 0) { out_pairs[out_count].key = key_pairs[i].key; bufsiz += (out_pairs[out_count].keylen = key_pairs[i].keylen); out_pairs[out_count].val = HS_VAL(entries, ptr, idx); bufsiz += (out_pairs[out_count].vallen = HS_VALLEN(entries, idx)); out_pairs[out_count].isnull = HS_VALISNULL(entries, idx); out_pairs[out_count].needfree = false; ++out_count; } } /* * we don't use uniquePairs here because we know that the pairs list is * already sorted and uniq'ed. */ out = hstorePairs(out_pairs, out_count, bufsiz); PG_RETURN_POINTER(out); } Commit Message: Predict integer overflow to avoid buffer overruns. Several functions, mostly type input functions, calculated an allocation size such that the calculation wrapped to a small positive value when arguments implied a sufficiently-large requirement. Writes past the end of the inadvertent small allocation followed shortly thereafter. Coverity identified the path_in() vulnerability; code inspection led to the rest. In passing, add check_stack_depth() to prevent stack overflow in related functions. Back-patch to 8.4 (all supported versions). The non-comment hstore changes touch code that did not exist in 8.4, so that part stops at 9.0. Noah Misch and Heikki Linnakangas, reviewed by Tom Lane. Security: CVE-2014-0064 CWE ID: CWE-189
hstore_slice_to_hstore(PG_FUNCTION_ARGS) { HStore *hs = PG_GETARG_HS(0); HEntry *entries = ARRPTR(hs); char *ptr = STRPTR(hs); ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(1); HStore *out; int nkeys; Pairs *key_pairs = hstoreArrayToPairs(key_array, &nkeys); Pairs *out_pairs; int bufsiz; int lastidx = 0; int i; int out_count = 0; if (nkeys == 0) { out = hstorePairs(NULL, 0, 0); PG_RETURN_POINTER(out); } /* hstoreArrayToPairs() checked overflow */ out_pairs = palloc(sizeof(Pairs) * nkeys); bufsiz = 0; /* * we exploit the fact that the pairs list is already sorted into strictly * increasing order to narrow the hstoreFindKey search; each search can * start one entry past the previous "found" entry, or at the lower bound * of the last search. */ for (i = 0; i < nkeys; ++i) { int idx = hstoreFindKey(hs, &lastidx, key_pairs[i].key, key_pairs[i].keylen); if (idx >= 0) { out_pairs[out_count].key = key_pairs[i].key; bufsiz += (out_pairs[out_count].keylen = key_pairs[i].keylen); out_pairs[out_count].val = HS_VAL(entries, ptr, idx); bufsiz += (out_pairs[out_count].vallen = HS_VALLEN(entries, idx)); out_pairs[out_count].isnull = HS_VALISNULL(entries, idx); out_pairs[out_count].needfree = false; ++out_count; } } /* * we don't use uniquePairs here because we know that the pairs list is * already sorted and uniq'ed. */ out = hstorePairs(out_pairs, out_count, bufsiz); PG_RETURN_POINTER(out); }
166,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr, unsigned long shmlba) { struct shmid_kernel *shp; unsigned long addr; unsigned long size; struct file *file; int err; unsigned long flags; unsigned long prot; int acc_mode; struct ipc_namespace *ns; struct shm_file_data *sfd; struct path path; fmode_t f_mode; unsigned long populate = 0; err = -EINVAL; if (shmid < 0) goto out; else if ((addr = (ulong)shmaddr)) { if (addr & (shmlba - 1)) { if (shmflg & SHM_RND) addr &= ~(shmlba - 1); /* round down */ else #ifndef __ARCH_FORCE_SHMLBA if (addr & ~PAGE_MASK) #endif goto out; } flags = MAP_SHARED | MAP_FIXED; } else { if ((shmflg & SHM_REMAP)) goto out; flags = MAP_SHARED; } if (shmflg & SHM_RDONLY) { prot = PROT_READ; acc_mode = S_IRUGO; f_mode = FMODE_READ; } else { prot = PROT_READ | PROT_WRITE; acc_mode = S_IRUGO | S_IWUGO; f_mode = FMODE_READ | FMODE_WRITE; } if (shmflg & SHM_EXEC) { prot |= PROT_EXEC; acc_mode |= S_IXUGO; } /* * We cannot rely on the fs check since SYSV IPC does have an * additional creator id... */ ns = current->nsproxy->ipc_ns; rcu_read_lock(); shp = shm_obtain_object_check(ns, shmid); if (IS_ERR(shp)) { err = PTR_ERR(shp); goto out_unlock; } err = -EACCES; if (ipcperms(ns, &shp->shm_perm, acc_mode)) goto out_unlock; err = security_shm_shmat(shp, shmaddr, shmflg); if (err) goto out_unlock; ipc_lock_object(&shp->shm_perm); /* check if shm_destroy() is tearing down shp */ if (!ipc_valid_object(&shp->shm_perm)) { ipc_unlock_object(&shp->shm_perm); err = -EIDRM; goto out_unlock; } path = shp->shm_file->f_path; path_get(&path); shp->shm_nattch++; size = i_size_read(d_inode(path.dentry)); ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); err = -ENOMEM; sfd = kzalloc(sizeof(*sfd), GFP_KERNEL); if (!sfd) { path_put(&path); goto out_nattch; } file = alloc_file(&path, f_mode, is_file_hugepages(shp->shm_file) ? &shm_file_operations_huge : &shm_file_operations); err = PTR_ERR(file); if (IS_ERR(file)) { kfree(sfd); path_put(&path); goto out_nattch; } file->private_data = sfd; file->f_mapping = shp->shm_file->f_mapping; sfd->id = shp->shm_perm.id; sfd->ns = get_ipc_ns(ns); sfd->file = shp->shm_file; sfd->vm_ops = NULL; err = security_mmap_file(file, prot, flags); if (err) goto out_fput; if (down_write_killable(&current->mm->mmap_sem)) { err = -EINTR; goto out_fput; } if (addr && !(shmflg & SHM_REMAP)) { err = -EINVAL; if (addr + size < addr) goto invalid; if (find_vma_intersection(current->mm, addr, addr + size)) goto invalid; } addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL); *raddr = addr; err = 0; if (IS_ERR_VALUE(addr)) err = (long)addr; invalid: up_write(&current->mm->mmap_sem); if (populate) mm_populate(addr, populate); out_fput: fput(file); out_nattch: down_write(&shm_ids(ns).rwsem); shp = shm_lock(ns, shmid); shp->shm_nattch--; if (shm_may_destroy(ns, shp)) shm_destroy(ns, shp); else shm_unlock(shp); up_write(&shm_ids(ns).rwsem); return err; out_unlock: rcu_read_unlock(); out: return err; } Commit Message: ipc/shm: Fix shmat mmap nil-page protection The issue is described here, with a nice testcase: https://bugzilla.kernel.org/show_bug.cgi?id=192931 The problem is that shmat() calls do_mmap_pgoff() with MAP_FIXED, and the address rounded down to 0. For the regular mmap case, the protection mentioned above is that the kernel gets to generate the address -- arch_get_unmapped_area() will always check for MAP_FIXED and return that address. So by the time we do security_mmap_addr(0) things get funky for shmat(). The testcase itself shows that while a regular user crashes, root will not have a problem attaching a nil-page. There are two possible fixes to this. The first, and which this patch does, is to simply allow root to crash as well -- this is also regular mmap behavior, ie when hacking up the testcase and adding mmap(... |MAP_FIXED). While this approach is the safer option, the second alternative is to ignore SHM_RND if the rounded address is 0, thus only having MAP_SHARED flags. This makes the behavior of shmat() identical to the mmap() case. The downside of this is obviously user visible, but does make sense in that it maintains semantics after the round-down wrt 0 address and mmap. Passes shm related ltp tests. Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Davidlohr Bueso <[email protected]> Reported-by: Gareth Evans <[email protected]> Cc: Manfred Spraul <[email protected]> Cc: Michael Kerrisk <[email protected]> Signed-off-by: Andrew Morton <[email protected]> CWE ID: CWE-20
long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr, long do_shmat(int shmid, char __user *shmaddr, int shmflg, ulong *raddr, unsigned long shmlba) { struct shmid_kernel *shp; unsigned long addr; unsigned long size; struct file *file; int err; unsigned long flags; unsigned long prot; int acc_mode; struct ipc_namespace *ns; struct shm_file_data *sfd; struct path path; fmode_t f_mode; unsigned long populate = 0; err = -EINVAL; if (shmid < 0) goto out; else if ((addr = (ulong)shmaddr)) { if (addr & (shmlba - 1)) { /* * Round down to the nearest multiple of shmlba. * For sane do_mmap_pgoff() parameters, avoid * round downs that trigger nil-page and MAP_FIXED. */ if ((shmflg & SHM_RND) && addr >= shmlba) addr &= ~(shmlba - 1); else #ifndef __ARCH_FORCE_SHMLBA if (addr & ~PAGE_MASK) #endif goto out; } flags = MAP_SHARED | MAP_FIXED; } else { if ((shmflg & SHM_REMAP)) goto out; flags = MAP_SHARED; } if (shmflg & SHM_RDONLY) { prot = PROT_READ; acc_mode = S_IRUGO; f_mode = FMODE_READ; } else { prot = PROT_READ | PROT_WRITE; acc_mode = S_IRUGO | S_IWUGO; f_mode = FMODE_READ | FMODE_WRITE; } if (shmflg & SHM_EXEC) { prot |= PROT_EXEC; acc_mode |= S_IXUGO; } /* * We cannot rely on the fs check since SYSV IPC does have an * additional creator id... */ ns = current->nsproxy->ipc_ns; rcu_read_lock(); shp = shm_obtain_object_check(ns, shmid); if (IS_ERR(shp)) { err = PTR_ERR(shp); goto out_unlock; } err = -EACCES; if (ipcperms(ns, &shp->shm_perm, acc_mode)) goto out_unlock; err = security_shm_shmat(shp, shmaddr, shmflg); if (err) goto out_unlock; ipc_lock_object(&shp->shm_perm); /* check if shm_destroy() is tearing down shp */ if (!ipc_valid_object(&shp->shm_perm)) { ipc_unlock_object(&shp->shm_perm); err = -EIDRM; goto out_unlock; } path = shp->shm_file->f_path; path_get(&path); shp->shm_nattch++; size = i_size_read(d_inode(path.dentry)); ipc_unlock_object(&shp->shm_perm); rcu_read_unlock(); err = -ENOMEM; sfd = kzalloc(sizeof(*sfd), GFP_KERNEL); if (!sfd) { path_put(&path); goto out_nattch; } file = alloc_file(&path, f_mode, is_file_hugepages(shp->shm_file) ? &shm_file_operations_huge : &shm_file_operations); err = PTR_ERR(file); if (IS_ERR(file)) { kfree(sfd); path_put(&path); goto out_nattch; } file->private_data = sfd; file->f_mapping = shp->shm_file->f_mapping; sfd->id = shp->shm_perm.id; sfd->ns = get_ipc_ns(ns); sfd->file = shp->shm_file; sfd->vm_ops = NULL; err = security_mmap_file(file, prot, flags); if (err) goto out_fput; if (down_write_killable(&current->mm->mmap_sem)) { err = -EINTR; goto out_fput; } if (addr && !(shmflg & SHM_REMAP)) { err = -EINVAL; if (addr + size < addr) goto invalid; if (find_vma_intersection(current->mm, addr, addr + size)) goto invalid; } addr = do_mmap_pgoff(file, addr, size, prot, flags, 0, &populate, NULL); *raddr = addr; err = 0; if (IS_ERR_VALUE(addr)) err = (long)addr; invalid: up_write(&current->mm->mmap_sem); if (populate) mm_populate(addr, populate); out_fput: fput(file); out_nattch: down_write(&shm_ids(ns).rwsem); shp = shm_lock(ns, shmid); shp->shm_nattch--; if (shm_may_destroy(ns, shp)) shm_destroy(ns, shp); else shm_unlock(shp); up_write(&shm_ids(ns).rwsem); return err; out_unlock: rcu_read_unlock(); out: return err; }
168,379
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return -ENOMEM; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; } err = skb_append_datato_frags(sk,skb, getfrag, from, (length - transhdrlen)); if (!err) { struct frag_hdr fhdr; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); return 0; } /* There is not enough support do UPD LSO, * so follow normal path */ kfree_skb(skb); return err; } Commit Message: ipv6: make fragment identifications less predictable IPv6 fragment identification generation is way beyond what we use for IPv4 : It uses a single generator. Its not scalable and allows DOS attacks. Now inetpeer is IPv6 aware, we can use it to provide a more secure and scalable frag ident generator (per destination, instead of system wide) This patch : 1) defines a new secure_ipv6_id() helper 2) extends inet_getid() to provide 32bit results 3) extends ipv6_select_ident() with a new dest parameter Reported-by: Fernando Gont <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu,unsigned int flags, struct rt6_info *rt) { struct sk_buff *skb; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return -ENOMEM; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb,fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; } err = skb_append_datato_frags(sk,skb, getfrag, from, (length - transhdrlen)); if (!err) { struct frag_hdr fhdr; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr, rt); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; __skb_queue_tail(&sk->sk_write_queue, skb); return 0; } /* There is not enough support do UPD LSO, * so follow normal path */ kfree_skb(skb); return err; }
165,853
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, u32 val, ktime_t *abs_time, u32 bitset, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2 = FUTEX_KEY_INIT; struct futex_q q = futex_q_init; int res, ret; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); rt_waiter.task = NULL; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE); if (unlikely(ret != 0)) goto out; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* * Prepare to wait on uaddr. On success, increments q.key (key1) ref * count. */ ret = futex_wait_setup(uaddr, val, flags, &q, &hb); if (ret) goto out_key2; /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquisition by the requeue code. The * futex_requeue dropped our key1 reference and incremented our key2 * reference count. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (pi_mutex && rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(&q.key); out_key2: put_futex_key(&key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; } Commit Message: futex: Forbid uaddr == uaddr2 in futex_wait_requeue_pi() If uaddr == uaddr2, then we have broken the rule of only requeueing from a non-pi futex to a pi futex with this call. If we attempt this, as the trinity test suite manages to do, we miss early wakeups as q.key is equal to key2 (because they are the same uaddr). We will then attempt to dereference the pi_mutex (which would exist had the futex_q been properly requeued to a pi futex) and trigger a NULL pointer dereference. Signed-off-by: Darren Hart <[email protected]> Cc: Dave Jones <[email protected]> Cc: [email protected] Link: http://lkml.kernel.org/r/ad82bfe7f7d130247fbe2b5b4275654807774227.1342809673.git.dvhart@linux.intel.com Signed-off-by: Thomas Gleixner <[email protected]> CWE ID: CWE-20
static int futex_wait_requeue_pi(u32 __user *uaddr, unsigned int flags, u32 val, ktime_t *abs_time, u32 bitset, u32 __user *uaddr2) { struct hrtimer_sleeper timeout, *to = NULL; struct rt_mutex_waiter rt_waiter; struct rt_mutex *pi_mutex = NULL; struct futex_hash_bucket *hb; union futex_key key2 = FUTEX_KEY_INIT; struct futex_q q = futex_q_init; int res, ret; if (uaddr == uaddr2) return -EINVAL; if (!bitset) return -EINVAL; if (abs_time) { to = &timeout; hrtimer_init_on_stack(&to->timer, (flags & FLAGS_CLOCKRT) ? CLOCK_REALTIME : CLOCK_MONOTONIC, HRTIMER_MODE_ABS); hrtimer_init_sleeper(to, current); hrtimer_set_expires_range_ns(&to->timer, *abs_time, current->timer_slack_ns); } /* * The waiter is allocated on our stack, manipulated by the requeue * code while we sleep on uaddr. */ debug_rt_mutex_init_waiter(&rt_waiter); rt_waiter.task = NULL; ret = get_futex_key(uaddr2, flags & FLAGS_SHARED, &key2, VERIFY_WRITE); if (unlikely(ret != 0)) goto out; q.bitset = bitset; q.rt_waiter = &rt_waiter; q.requeue_pi_key = &key2; /* * Prepare to wait on uaddr. On success, increments q.key (key1) ref * count. */ ret = futex_wait_setup(uaddr, val, flags, &q, &hb); if (ret) goto out_key2; /* Queue the futex_q, drop the hb lock, wait for wakeup. */ futex_wait_queue_me(hb, &q, to); spin_lock(&hb->lock); ret = handle_early_requeue_pi_wakeup(hb, &q, &key2, to); spin_unlock(&hb->lock); if (ret) goto out_put_keys; /* * In order for us to be here, we know our q.key == key2, and since * we took the hb->lock above, we also know that futex_requeue() has * completed and we no longer have to concern ourselves with a wakeup * race with the atomic proxy lock acquisition by the requeue code. The * futex_requeue dropped our key1 reference and incremented our key2 * reference count. */ /* Check if the requeue code acquired the second futex for us. */ if (!q.rt_waiter) { /* * Got the lock. We might not be the anticipated owner if we * did a lock-steal - fix up the PI-state in that case. */ if (q.pi_state && (q.pi_state->owner != current)) { spin_lock(q.lock_ptr); ret = fixup_pi_state_owner(uaddr2, &q, current); spin_unlock(q.lock_ptr); } } else { /* * We have been woken up by futex_unlock_pi(), a timeout, or a * signal. futex_unlock_pi() will not destroy the lock_ptr nor * the pi_state. */ WARN_ON(!q.pi_state); pi_mutex = &q.pi_state->pi_mutex; ret = rt_mutex_finish_proxy_lock(pi_mutex, to, &rt_waiter, 1); debug_rt_mutex_free_waiter(&rt_waiter); spin_lock(q.lock_ptr); /* * Fixup the pi_state owner and possibly acquire the lock if we * haven't already. */ res = fixup_owner(uaddr2, &q, !ret); /* * If fixup_owner() returned an error, proprogate that. If it * acquired the lock, clear -ETIMEDOUT or -EINTR. */ if (res) ret = (res < 0) ? res : 0; /* Unqueue and drop the lock. */ unqueue_me_pi(&q); } /* * If fixup_pi_state_owner() faulted and was unable to handle the * fault, unlock the rt_mutex and return the fault to userspace. */ if (ret == -EFAULT) { if (pi_mutex && rt_mutex_owner(pi_mutex) == current) rt_mutex_unlock(pi_mutex); } else if (ret == -EINTR) { /* * We've already been requeued, but cannot restart by calling * futex_lock_pi() directly. We could restart this syscall, but * it would detect that the user space "val" changed and return * -EWOULDBLOCK. Save the overhead of the restart and return * -EWOULDBLOCK directly. */ ret = -EWOULDBLOCK; } out_put_keys: put_futex_key(&q.key); out_key2: put_futex_key(&key2); out: if (to) { hrtimer_cancel(&to->timer); destroy_hrtimer_on_stack(&to->timer); } return ret; }
166,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int efx_ethtool_set_ringparam(struct net_device *net_dev, struct ethtool_ringparam *ring) { struct efx_nic *efx = netdev_priv(net_dev); if (ring->rx_mini_pending || ring->rx_jumbo_pending || ring->rx_pending > EFX_MAX_DMAQ_SIZE || ring->tx_pending > EFX_MAX_DMAQ_SIZE) return -EINVAL; if (ring->rx_pending < EFX_MIN_RING_SIZE || ring->tx_pending < EFX_MIN_RING_SIZE) { netif_err(efx, drv, efx->net_dev, "TX and RX queues cannot be smaller than %ld\n", EFX_MIN_RING_SIZE); return -EINVAL; } return efx_realloc_channels(efx, ring->rx_pending, ring->tx_pending); } Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size [ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ] Currently an skb requiring TSO may not fit within a minimum-size TX queue. The TX queue selected for the skb may stall and trigger the TX watchdog repeatedly (since the problem skb will be retried after the TX reset). This issue is designated as CVE-2012-3412. Set the maximum number of TSO segments for our devices to 100. This should make no difference to behaviour unless the actual MSS is less than about 700. Increase the minimum TX queue size accordingly to allow for 2 worst-case skbs, so that there will definitely be space to add an skb after we wake a queue. To avoid invalidating existing configurations, change efx_ethtool_set_ringparam() to fix up values that are too small rather than returning -EINVAL. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> CWE ID: CWE-189
static int efx_ethtool_set_ringparam(struct net_device *net_dev, struct ethtool_ringparam *ring) { struct efx_nic *efx = netdev_priv(net_dev); u32 txq_entries; if (ring->rx_mini_pending || ring->rx_jumbo_pending || ring->rx_pending > EFX_MAX_DMAQ_SIZE || ring->tx_pending > EFX_MAX_DMAQ_SIZE) return -EINVAL; if (ring->rx_pending < EFX_RXQ_MIN_ENT) { netif_err(efx, drv, efx->net_dev, "RX queues cannot be smaller than %u\n", EFX_RXQ_MIN_ENT); return -EINVAL; } txq_entries = max(ring->tx_pending, EFX_TXQ_MIN_ENT(efx)); if (txq_entries != ring->tx_pending) netif_warn(efx, drv, efx->net_dev, "increasing TX queue size to minimum of %u\n", txq_entries); return efx_realloc_channels(efx, ring->rx_pending, txq_entries); }
165,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_size_of_type(int color_type, int bit_depth, unsigned int *colors) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_size_of_type(int color_type, int bit_depth, unsigned int *colors) image_size_of_type(int color_type, int bit_depth, unsigned int *colors, int small) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (small) { if (pixel_depth <= 8) /* there will be one row */ return 1 << pixel_depth; else return 256; } else if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } }
173,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { ip += n - 1; /* point to last one */ wp += n - 1; /* point to last one */ n -= stride; while (n > 0) { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp[stride] -= wp[0]; wp[stride] &= mask; wp--; ip--) n -= stride; } REPEAT(stride, wp[0] = CLAMP(ip[0]); wp--; ip--) } } } Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities in heap or stack allocated buffers. Reported as MSVR 35093, MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR 35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities in heap allocated buffers. Reported as MSVR 35094. Discovered by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. * libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1() that didn't reset the tif_rawcc and tif_rawcp members. I'm not completely sure if that could happen in practice outside of the odd behaviour of t2p_seekproc() of tiff2pdf). The report points that a better fix could be to check the return value of TIFFFlushData1() in places where it isn't done currently, but it seems this patch is enough. Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan & Suha Can from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787
horizontalDifference16(unsigned short *ip, int n, int stride, unsigned short *wp, uint16 *From14) { register int r1, g1, b1, a1, r2, g2, b2, a2, mask; /* assumption is unsigned pixel values */ #undef CLAMP #define CLAMP(v) From14[(v) >> 2] mask = CODE_MASK; if (n >= stride) { if (stride == 3) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); n -= 3; while (n > 0) { n -= 3; wp += 3; ip += 3; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; } } else if (stride == 4) { r2 = wp[0] = CLAMP(ip[0]); g2 = wp[1] = CLAMP(ip[1]); b2 = wp[2] = CLAMP(ip[2]); a2 = wp[3] = CLAMP(ip[3]); n -= 4; while (n > 0) { n -= 4; wp += 4; ip += 4; r1 = CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1; g1 = CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1; b1 = CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1; a1 = CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1; } } else { REPEAT(stride, wp[0] = CLAMP(ip[0]); wp++; ip++) n -= stride; while (n > 0) { REPEAT(stride, wp[0] = (uint16)((CLAMP(ip[0])-CLAMP(ip[-stride])) & mask); wp++; ip++) n -= stride; } } } }
166,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HTMLElement::setInnerHTML(const String& html, ExceptionCode& ec) { RefPtr<DocumentFragment> fragment = createFragmentFromSource(html, this, ec); if (fragment) replaceChildrenWithFragment(this, fragment.release(), ec); } Commit Message: There are too many poorly named functions to create a fragment from markup https://bugs.webkit.org/show_bug.cgi?id=87339 Reviewed by Eric Seidel. Source/WebCore: Moved all functions that create a fragment from markup to markup.h/cpp. There should be no behavioral change. * dom/Range.cpp: (WebCore::Range::createContextualFragment): * dom/Range.h: Removed createDocumentFragmentForElement. * dom/ShadowRoot.cpp: (WebCore::ShadowRoot::setInnerHTML): * editing/markup.cpp: (WebCore::createFragmentFromMarkup): (WebCore::createFragmentForInnerOuterHTML): Renamed from createFragmentFromSource. (WebCore::createFragmentForTransformToFragment): Moved from XSLTProcessor. (WebCore::removeElementPreservingChildren): Moved from Range. (WebCore::createContextualFragment): Ditto. * editing/markup.h: * html/HTMLElement.cpp: (WebCore::HTMLElement::setInnerHTML): (WebCore::HTMLElement::setOuterHTML): (WebCore::HTMLElement::insertAdjacentHTML): * inspector/DOMPatchSupport.cpp: (WebCore::DOMPatchSupport::patchNode): Added a FIXME since this code should be using one of the functions listed in markup.h * xml/XSLTProcessor.cpp: (WebCore::XSLTProcessor::transformToFragment): Source/WebKit/qt: Replace calls to Range::createDocumentFragmentForElement by calls to createContextualDocumentFragment. * Api/qwebelement.cpp: (QWebElement::appendInside): (QWebElement::prependInside): (QWebElement::prependOutside): (QWebElement::appendOutside): (QWebElement::encloseContentsWith): (QWebElement::encloseWith): git-svn-id: svn://svn.chromium.org/blink/trunk@118414 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-264
void HTMLElement::setInnerHTML(const String& html, ExceptionCode& ec) { if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, ec)) replaceChildrenWithFragment(this, fragment.release(), ec); }
170,441
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */ { const char *p; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); for (p = val; p < endptr; ) { zval **tmp; namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF); if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) { return FAILURE; } name = estrndup(p + 1, namelen); p += namelen + 1; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { efree(name); continue; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); efree(name); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */ Commit Message: CWE ID: CWE-416
PS_SERIALIZER_DECODE_FUNC(php_binary) /* {{{ */ { const char *p; char *name; const char *endptr = val + vallen; zval *current; int namelen; int has_value; php_unserialize_data_t var_hash; PHP_VAR_UNSERIALIZE_INIT(var_hash); for (p = val; p < endptr; ) { zval **tmp; namelen = ((unsigned char)(*p)) & (~PS_BIN_UNDEF); if (namelen < 0 || namelen > PS_BIN_MAX || (p + namelen) >= endptr) { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } name = estrndup(p + 1, namelen); p += namelen + 1; if (zend_hash_find(&EG(symbol_table), name, namelen + 1, (void **) &tmp) == SUCCESS) { if ((Z_TYPE_PP(tmp) == IS_ARRAY && Z_ARRVAL_PP(tmp) == &EG(symbol_table)) || *tmp == PS(http_session_vars)) { efree(name); continue; } } if (has_value) { ALLOC_INIT_ZVAL(current); if (php_var_unserialize(&current, (const unsigned char **) &p, (const unsigned char *) endptr, &var_hash TSRMLS_CC)) { php_set_session_var(name, namelen, current, &var_hash TSRMLS_CC); } else { PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return FAILURE; } var_push_dtor_no_addref(&var_hash, &current); } PS_ADD_VARL(name, namelen); efree(name); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); return SUCCESS; } /* }}} */
164,981
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: AccessibilityButtonState AXObject::checkboxOrRadioValue() const { const AtomicString& checkedAttribute = getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked); if (equalIgnoringCase(checkedAttribute, "true")) return ButtonStateOn; if (equalIgnoringCase(checkedAttribute, "mixed")) { AccessibilityRole role = ariaRoleAttribute(); if (role == CheckBoxRole || role == MenuItemCheckBoxRole) return ButtonStateMixed; } return ButtonStateOff; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
AccessibilityButtonState AXObject::checkboxOrRadioValue() const { const AtomicString& checkedAttribute = getAOMPropertyOrARIAAttribute(AOMStringProperty::kChecked); if (equalIgnoringASCIICase(checkedAttribute, "true")) return ButtonStateOn; if (equalIgnoringASCIICase(checkedAttribute, "mixed")) { AccessibilityRole role = ariaRoleAttribute(); if (role == CheckBoxRole || role == MenuItemCheckBoxRole) return ButtonStateMixed; } return ButtonStateOff; }
171,924
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::updateGraphicBufferInMeta_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer, OMX_BUFFERHEADERTYPE *header) { if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { return BAD_VALUE; } BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate); bufferMeta->setGraphicBuffer(graphicBuffer); if (mMetadataType[portIndex] == kMetadataBufferTypeGrallocSource && header->nAllocLen >= sizeof(VideoGrallocMetadata)) { VideoGrallocMetadata &metadata = *(VideoGrallocMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeGrallocSource; metadata.pHandle = graphicBuffer == NULL ? NULL : graphicBuffer->handle; } else if (mMetadataType[portIndex] == kMetadataBufferTypeANWBuffer && header->nAllocLen >= sizeof(VideoNativeMetadata)) { VideoNativeMetadata &metadata = *(VideoNativeMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeANWBuffer; metadata.pBuffer = graphicBuffer == NULL ? NULL : graphicBuffer->getNativeBuffer(); metadata.nFenceFd = -1; } else { CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x bad type (%d) or size (%u)", portString(portIndex), portIndex, buffer, mMetadataType[portIndex], header->nAllocLen); return BAD_VALUE; } CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x := %p", portString(portIndex), portIndex, buffer, graphicBuffer == NULL ? NULL : graphicBuffer->handle); return OK; } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
status_t OMXNodeInstance::updateGraphicBufferInMeta_l( OMX_U32 portIndex, const sp<GraphicBuffer>& graphicBuffer, OMX::buffer_id buffer, OMX_BUFFERHEADERTYPE *header) { if (header == NULL) { return BAD_VALUE; } if (portIndex != kPortIndexInput && portIndex != kPortIndexOutput) { return BAD_VALUE; } BufferMeta *bufferMeta = (BufferMeta *)(header->pAppPrivate); bufferMeta->setGraphicBuffer(graphicBuffer); if (mMetadataType[portIndex] == kMetadataBufferTypeGrallocSource && header->nAllocLen >= sizeof(VideoGrallocMetadata)) { VideoGrallocMetadata &metadata = *(VideoGrallocMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeGrallocSource; metadata.pHandle = graphicBuffer == NULL ? NULL : graphicBuffer->handle; } else if (mMetadataType[portIndex] == kMetadataBufferTypeANWBuffer && header->nAllocLen >= sizeof(VideoNativeMetadata)) { VideoNativeMetadata &metadata = *(VideoNativeMetadata *)(header->pBuffer); metadata.eType = kMetadataBufferTypeANWBuffer; metadata.pBuffer = graphicBuffer == NULL ? NULL : graphicBuffer->getNativeBuffer(); metadata.nFenceFd = -1; } else { CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x bad type (%d) or size (%u)", portString(portIndex), portIndex, buffer, mMetadataType[portIndex], header->nAllocLen); return BAD_VALUE; } CLOG_BUFFER(updateGraphicBufferInMeta, "%s:%u, %#x := %p", portString(portIndex), portIndex, buffer, graphicBuffer == NULL ? NULL : graphicBuffer->handle); return OK; }
173,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; int r; union { struct kvm_lapic_state *lapic; struct kvm_xsave *xsave; struct kvm_xcrs *xcrs; void *buffer; } u; u.buffer = NULL; switch (ioctl) { case KVM_GET_LAPIC: { r = -EINVAL; if (!vcpu->arch.apic) goto out; u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL); r = -ENOMEM; if (!u.lapic) goto out; r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state))) goto out; r = 0; break; } case KVM_SET_LAPIC: { r = -EINVAL; if (!vcpu->arch.apic) goto out; u.lapic = memdup_user(argp, sizeof(*u.lapic)); if (IS_ERR(u.lapic)) return PTR_ERR(u.lapic); r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic); break; } case KVM_INTERRUPT: { struct kvm_interrupt irq; r = -EFAULT; if (copy_from_user(&irq, argp, sizeof irq)) goto out; r = kvm_vcpu_ioctl_interrupt(vcpu, &irq); break; } case KVM_NMI: { r = kvm_vcpu_ioctl_nmi(vcpu); break; } case KVM_SET_CPUID: { struct kvm_cpuid __user *cpuid_arg = argp; struct kvm_cpuid cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries); break; } case KVM_SET_CPUID2: { struct kvm_cpuid2 __user *cpuid_arg = argp; struct kvm_cpuid2 cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid, cpuid_arg->entries); break; } case KVM_GET_CPUID2: { struct kvm_cpuid2 __user *cpuid_arg = argp; struct kvm_cpuid2 cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid, cpuid_arg->entries); if (r) goto out; r = -EFAULT; if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid)) goto out; r = 0; break; } case KVM_GET_MSRS: r = msr_io(vcpu, argp, kvm_get_msr, 1); break; case KVM_SET_MSRS: r = msr_io(vcpu, argp, do_set_msr, 0); break; case KVM_TPR_ACCESS_REPORTING: { struct kvm_tpr_access_ctl tac; r = -EFAULT; if (copy_from_user(&tac, argp, sizeof tac)) goto out; r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &tac, sizeof tac)) goto out; r = 0; break; }; case KVM_SET_VAPIC_ADDR: { struct kvm_vapic_addr va; r = -EINVAL; if (!irqchip_in_kernel(vcpu->kvm)) goto out; r = -EFAULT; if (copy_from_user(&va, argp, sizeof va)) goto out; r = 0; kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr); break; } case KVM_X86_SETUP_MCE: { u64 mcg_cap; r = -EFAULT; if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap)) goto out; r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap); break; } case KVM_X86_SET_MCE: { struct kvm_x86_mce mce; r = -EFAULT; if (copy_from_user(&mce, argp, sizeof mce)) goto out; r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce); break; } case KVM_GET_VCPU_EVENTS: { struct kvm_vcpu_events events; kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events); r = -EFAULT; if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events))) break; r = 0; break; } case KVM_SET_VCPU_EVENTS: { struct kvm_vcpu_events events; r = -EFAULT; if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events))) break; r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events); break; } case KVM_GET_DEBUGREGS: { struct kvm_debugregs dbgregs; kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs); r = -EFAULT; if (copy_to_user(argp, &dbgregs, sizeof(struct kvm_debugregs))) break; r = 0; break; } case KVM_SET_DEBUGREGS: { struct kvm_debugregs dbgregs; r = -EFAULT; if (copy_from_user(&dbgregs, argp, sizeof(struct kvm_debugregs))) break; r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs); break; } case KVM_GET_XSAVE: { u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL); r = -ENOMEM; if (!u.xsave) break; kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave); r = -EFAULT; if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave))) break; r = 0; break; } case KVM_SET_XSAVE: { u.xsave = memdup_user(argp, sizeof(*u.xsave)); if (IS_ERR(u.xsave)) return PTR_ERR(u.xsave); r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave); break; } case KVM_GET_XCRS: { u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL); r = -ENOMEM; if (!u.xcrs) break; kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs); r = -EFAULT; if (copy_to_user(argp, u.xcrs, sizeof(struct kvm_xcrs))) break; r = 0; break; } case KVM_SET_XCRS: { u.xcrs = memdup_user(argp, sizeof(*u.xcrs)); if (IS_ERR(u.xcrs)) return PTR_ERR(u.xcrs); r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs); break; } case KVM_SET_TSC_KHZ: { u32 user_tsc_khz; r = -EINVAL; user_tsc_khz = (u32)arg; if (user_tsc_khz >= kvm_max_guest_tsc_khz) goto out; if (user_tsc_khz == 0) user_tsc_khz = tsc_khz; kvm_set_tsc_khz(vcpu, user_tsc_khz); r = 0; goto out; } case KVM_GET_TSC_KHZ: { r = vcpu->arch.virtual_tsc_khz; goto out; } case KVM_KVMCLOCK_CTRL: { r = kvm_set_guest_paused(vcpu); goto out; } default: r = -EINVAL; } out: kfree(u.buffer); return r; } Commit Message: KVM: x86: Convert vapic synchronization to _cached functions (CVE-2013-6368) In kvm_lapic_sync_from_vapic and kvm_lapic_sync_to_vapic there is the potential to corrupt kernel memory if userspace provides an address that is at the end of a page. This patches concerts those functions to use kvm_write_guest_cached and kvm_read_guest_cached. It also checks the vapic_address specified by userspace during ioctl processing and returns an error to userspace if the address is not a valid GPA. This is generally not guest triggerable, because the required write is done by firmware that runs before the guest. Also, it only affects AMD processors and oldish Intel that do not have the FlexPriority feature (unless you disable FlexPriority, of course; then newer processors are also affected). Fixes: b93463aa59d6 ('KVM: Accelerated apic support') Reported-by: Andrew Honig <[email protected]> Cc: [email protected] Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-20
long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; int r; union { struct kvm_lapic_state *lapic; struct kvm_xsave *xsave; struct kvm_xcrs *xcrs; void *buffer; } u; u.buffer = NULL; switch (ioctl) { case KVM_GET_LAPIC: { r = -EINVAL; if (!vcpu->arch.apic) goto out; u.lapic = kzalloc(sizeof(struct kvm_lapic_state), GFP_KERNEL); r = -ENOMEM; if (!u.lapic) goto out; r = kvm_vcpu_ioctl_get_lapic(vcpu, u.lapic); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, u.lapic, sizeof(struct kvm_lapic_state))) goto out; r = 0; break; } case KVM_SET_LAPIC: { r = -EINVAL; if (!vcpu->arch.apic) goto out; u.lapic = memdup_user(argp, sizeof(*u.lapic)); if (IS_ERR(u.lapic)) return PTR_ERR(u.lapic); r = kvm_vcpu_ioctl_set_lapic(vcpu, u.lapic); break; } case KVM_INTERRUPT: { struct kvm_interrupt irq; r = -EFAULT; if (copy_from_user(&irq, argp, sizeof irq)) goto out; r = kvm_vcpu_ioctl_interrupt(vcpu, &irq); break; } case KVM_NMI: { r = kvm_vcpu_ioctl_nmi(vcpu); break; } case KVM_SET_CPUID: { struct kvm_cpuid __user *cpuid_arg = argp; struct kvm_cpuid cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_set_cpuid(vcpu, &cpuid, cpuid_arg->entries); break; } case KVM_SET_CPUID2: { struct kvm_cpuid2 __user *cpuid_arg = argp; struct kvm_cpuid2 cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_set_cpuid2(vcpu, &cpuid, cpuid_arg->entries); break; } case KVM_GET_CPUID2: { struct kvm_cpuid2 __user *cpuid_arg = argp; struct kvm_cpuid2 cpuid; r = -EFAULT; if (copy_from_user(&cpuid, cpuid_arg, sizeof cpuid)) goto out; r = kvm_vcpu_ioctl_get_cpuid2(vcpu, &cpuid, cpuid_arg->entries); if (r) goto out; r = -EFAULT; if (copy_to_user(cpuid_arg, &cpuid, sizeof cpuid)) goto out; r = 0; break; } case KVM_GET_MSRS: r = msr_io(vcpu, argp, kvm_get_msr, 1); break; case KVM_SET_MSRS: r = msr_io(vcpu, argp, do_set_msr, 0); break; case KVM_TPR_ACCESS_REPORTING: { struct kvm_tpr_access_ctl tac; r = -EFAULT; if (copy_from_user(&tac, argp, sizeof tac)) goto out; r = vcpu_ioctl_tpr_access_reporting(vcpu, &tac); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &tac, sizeof tac)) goto out; r = 0; break; }; case KVM_SET_VAPIC_ADDR: { struct kvm_vapic_addr va; r = -EINVAL; if (!irqchip_in_kernel(vcpu->kvm)) goto out; r = -EFAULT; if (copy_from_user(&va, argp, sizeof va)) goto out; r = kvm_lapic_set_vapic_addr(vcpu, va.vapic_addr); break; } case KVM_X86_SETUP_MCE: { u64 mcg_cap; r = -EFAULT; if (copy_from_user(&mcg_cap, argp, sizeof mcg_cap)) goto out; r = kvm_vcpu_ioctl_x86_setup_mce(vcpu, mcg_cap); break; } case KVM_X86_SET_MCE: { struct kvm_x86_mce mce; r = -EFAULT; if (copy_from_user(&mce, argp, sizeof mce)) goto out; r = kvm_vcpu_ioctl_x86_set_mce(vcpu, &mce); break; } case KVM_GET_VCPU_EVENTS: { struct kvm_vcpu_events events; kvm_vcpu_ioctl_x86_get_vcpu_events(vcpu, &events); r = -EFAULT; if (copy_to_user(argp, &events, sizeof(struct kvm_vcpu_events))) break; r = 0; break; } case KVM_SET_VCPU_EVENTS: { struct kvm_vcpu_events events; r = -EFAULT; if (copy_from_user(&events, argp, sizeof(struct kvm_vcpu_events))) break; r = kvm_vcpu_ioctl_x86_set_vcpu_events(vcpu, &events); break; } case KVM_GET_DEBUGREGS: { struct kvm_debugregs dbgregs; kvm_vcpu_ioctl_x86_get_debugregs(vcpu, &dbgregs); r = -EFAULT; if (copy_to_user(argp, &dbgregs, sizeof(struct kvm_debugregs))) break; r = 0; break; } case KVM_SET_DEBUGREGS: { struct kvm_debugregs dbgregs; r = -EFAULT; if (copy_from_user(&dbgregs, argp, sizeof(struct kvm_debugregs))) break; r = kvm_vcpu_ioctl_x86_set_debugregs(vcpu, &dbgregs); break; } case KVM_GET_XSAVE: { u.xsave = kzalloc(sizeof(struct kvm_xsave), GFP_KERNEL); r = -ENOMEM; if (!u.xsave) break; kvm_vcpu_ioctl_x86_get_xsave(vcpu, u.xsave); r = -EFAULT; if (copy_to_user(argp, u.xsave, sizeof(struct kvm_xsave))) break; r = 0; break; } case KVM_SET_XSAVE: { u.xsave = memdup_user(argp, sizeof(*u.xsave)); if (IS_ERR(u.xsave)) return PTR_ERR(u.xsave); r = kvm_vcpu_ioctl_x86_set_xsave(vcpu, u.xsave); break; } case KVM_GET_XCRS: { u.xcrs = kzalloc(sizeof(struct kvm_xcrs), GFP_KERNEL); r = -ENOMEM; if (!u.xcrs) break; kvm_vcpu_ioctl_x86_get_xcrs(vcpu, u.xcrs); r = -EFAULT; if (copy_to_user(argp, u.xcrs, sizeof(struct kvm_xcrs))) break; r = 0; break; } case KVM_SET_XCRS: { u.xcrs = memdup_user(argp, sizeof(*u.xcrs)); if (IS_ERR(u.xcrs)) return PTR_ERR(u.xcrs); r = kvm_vcpu_ioctl_x86_set_xcrs(vcpu, u.xcrs); break; } case KVM_SET_TSC_KHZ: { u32 user_tsc_khz; r = -EINVAL; user_tsc_khz = (u32)arg; if (user_tsc_khz >= kvm_max_guest_tsc_khz) goto out; if (user_tsc_khz == 0) user_tsc_khz = tsc_khz; kvm_set_tsc_khz(vcpu, user_tsc_khz); r = 0; goto out; } case KVM_GET_TSC_KHZ: { r = vcpu->arch.virtual_tsc_khz; goto out; } case KVM_KVMCLOCK_CTRL: { r = kvm_set_guest_paused(vcpu); goto out; } default: r = -EINVAL; } out: kfree(u.buffer); return r; }
165,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int hidp_setup_hid(struct hidp_session *session, struct hidp_connadd_req *req) { struct hid_device *hid; int err; session->rd_data = kzalloc(req->rd_size, GFP_KERNEL); if (!session->rd_data) return -ENOMEM; if (copy_from_user(session->rd_data, req->rd_data, req->rd_size)) { err = -EFAULT; goto fault; } session->rd_size = req->rd_size; hid = hid_allocate_device(); if (IS_ERR(hid)) { err = PTR_ERR(hid); goto fault; } session->hid = hid; hid->driver_data = session; hid->bus = BUS_BLUETOOTH; hid->vendor = req->vendor; hid->product = req->product; hid->version = req->version; hid->country = req->country; strncpy(hid->name, req->name, 128); snprintf(hid->phys, sizeof(hid->phys), "%pMR", &bt_sk(session->ctrl_sock->sk)->src); snprintf(hid->uniq, sizeof(hid->uniq), "%pMR", &bt_sk(session->ctrl_sock->sk)->dst); hid->dev.parent = &session->conn->dev; hid->ll_driver = &hidp_hid_driver; hid->hid_get_raw_report = hidp_get_raw_report; hid->hid_output_raw_report = hidp_output_raw_report; /* True if device is blacklisted in drivers/hid/hid-core.c */ if (hid_ignore(hid)) { hid_destroy_device(session->hid); session->hid = NULL; return -ENODEV; } return 0; fault: kfree(session->rd_data); session->rd_data = NULL; return err; } Commit Message: Bluetooth: Fix incorrect strncpy() in hidp_setup_hid() The length parameter should be sizeof(req->name) - 1 because there is no guarantee that string provided by userspace will contain the trailing '\0'. Can be easily reproduced by manually setting req->name to 128 non-zero bytes prior to ioctl(HIDPCONNADD) and checking the device name setup on input subsystem: $ cat /sys/devices/pnp0/00\:04/tty/ttyS0/hci0/hci0\:1/input8/name AAAAAA[...]AAAAAAAAf0:af:f0:af:f0:af ("f0:af:f0:af:f0:af" is the device bluetooth address, taken from "phys" field in struct hid_device due to overflow.) Cc: [email protected] Signed-off-by: Anderson Lizardo <[email protected]> Acked-by: Marcel Holtmann <[email protected]> Signed-off-by: Gustavo Padovan <[email protected]> CWE ID: CWE-200
static int hidp_setup_hid(struct hidp_session *session, struct hidp_connadd_req *req) { struct hid_device *hid; int err; session->rd_data = kzalloc(req->rd_size, GFP_KERNEL); if (!session->rd_data) return -ENOMEM; if (copy_from_user(session->rd_data, req->rd_data, req->rd_size)) { err = -EFAULT; goto fault; } session->rd_size = req->rd_size; hid = hid_allocate_device(); if (IS_ERR(hid)) { err = PTR_ERR(hid); goto fault; } session->hid = hid; hid->driver_data = session; hid->bus = BUS_BLUETOOTH; hid->vendor = req->vendor; hid->product = req->product; hid->version = req->version; hid->country = req->country; strncpy(hid->name, req->name, sizeof(req->name) - 1); snprintf(hid->phys, sizeof(hid->phys), "%pMR", &bt_sk(session->ctrl_sock->sk)->src); snprintf(hid->uniq, sizeof(hid->uniq), "%pMR", &bt_sk(session->ctrl_sock->sk)->dst); hid->dev.parent = &session->conn->dev; hid->ll_driver = &hidp_hid_driver; hid->hid_get_raw_report = hidp_get_raw_report; hid->hid_output_raw_report = hidp_output_raw_report; /* True if device is blacklisted in drivers/hid/hid-core.c */ if (hid_ignore(hid)) { hid_destroy_device(session->hid); session->hid = NULL; return -ENODEV; } return 0; fault: kfree(session->rd_data); session->rd_data = NULL; return err; }
166,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len) { struct sc_path path; struct sc_file *file; unsigned char *p; int ok = 0; int r; size_t len; sc_format_path(str_path, &path); if (SC_SUCCESS != sc_select_file(card, &path, &file)) { goto err; } len = file ? file->size : 4096; p = realloc(*data, len); if (!p) { goto err; } *data = p; *data_len = len; r = sc_read_binary(card, 0, p, len, 0); if (r < 0) goto err; *data_len = r; ok = 1; err: sc_file_free(file); return ok; } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
int read_file(struct sc_card *card, char *str_path, unsigned char **data, size_t *data_len) { struct sc_path path; struct sc_file *file; unsigned char *p; int ok = 0; int r; size_t len; sc_format_path(str_path, &path); if (SC_SUCCESS != sc_select_file(card, &path, &file)) { goto err; } len = file && file->size > 0 ? file->size : 4096; p = realloc(*data, len); if (!p) { goto err; } *data = p; *data_len = len; r = sc_read_binary(card, 0, p, len, 0); if (r < 0) goto err; *data_len = r; ok = 1; err: sc_file_free(file); return ok; }
169,082
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } Commit Message: * tools/tiffcp.c: fix out-of-bounds write on tiled images with odd tile width vs image width. Reported as MSVR 35103 by Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-787
DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb + tilew > imagew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; }
166,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ext4_put_super(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int i, err; ext4_unregister_li_request(sb); dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); flush_workqueue(sbi->rsv_conversion_wq); destroy_workqueue(sbi->rsv_conversion_wq); if (sbi->s_journal) { err = jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; if (err < 0) ext4_abort(sb, "Couldn't clean up the journal"); } ext4_unregister_sysfs(sb); ext4_es_unregister_shrinker(sbi); del_timer_sync(&sbi->s_err_report); ext4_release_system_zone(sb); ext4_mb_release(sb); ext4_ext_release(sb); ext4_xattr_put_super(sb); if (!(sb->s_flags & MS_RDONLY)) { ext4_clear_feature_journal_needs_recovery(sb); es->s_state = cpu_to_le16(sbi->s_mount_state); } if (!(sb->s_flags & MS_RDONLY)) ext4_commit_super(sb, 1); for (i = 0; i < sbi->s_gdb_count; i++) brelse(sbi->s_group_desc[i]); kvfree(sbi->s_group_desc); kvfree(sbi->s_flex_groups); percpu_counter_destroy(&sbi->s_freeclusters_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyclusters_counter); brelse(sbi->s_sbh); #ifdef CONFIG_QUOTA for (i = 0; i < EXT4_MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif /* Debugging code just in case the in-memory inode orphan list * isn't empty. The on-disk one can be non-empty if we've * detected an error and taken the fs readonly, but the * in-memory list had better be clean by this point. */ if (!list_empty(&sbi->s_orphan)) dump_orphan_list(sb, sbi); J_ASSERT(list_empty(&sbi->s_orphan)); sync_blockdev(sb->s_bdev); invalidate_bdev(sb->s_bdev); if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) { /* * Invalidate the journal device's buffers. We don't want them * floating about in memory - the physical journal device may * hotswapped, and it breaks the `ro-after' testing code. */ sync_blockdev(sbi->journal_bdev); invalidate_bdev(sbi->journal_bdev); ext4_blkdev_remove(sbi); } if (sbi->s_mb_cache) { ext4_xattr_destroy_cache(sbi->s_mb_cache); sbi->s_mb_cache = NULL; } if (sbi->s_mmp_tsk) kthread_stop(sbi->s_mmp_tsk); sb->s_fs_info = NULL; /* * Now that we are completely done shutting down the * superblock, we need to actually destroy the kobject. */ kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->s_blockgroup_lock); kfree(sbi); } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
static void ext4_put_super(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; int i, err; ext4_unregister_li_request(sb); dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); flush_workqueue(sbi->rsv_conversion_wq); destroy_workqueue(sbi->rsv_conversion_wq); if (sbi->s_journal) { err = jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; if (err < 0) ext4_abort(sb, "Couldn't clean up the journal"); } ext4_unregister_sysfs(sb); ext4_es_unregister_shrinker(sbi); del_timer_sync(&sbi->s_err_report); ext4_release_system_zone(sb); ext4_mb_release(sb); ext4_ext_release(sb); if (!(sb->s_flags & MS_RDONLY)) { ext4_clear_feature_journal_needs_recovery(sb); es->s_state = cpu_to_le16(sbi->s_mount_state); } if (!(sb->s_flags & MS_RDONLY)) ext4_commit_super(sb, 1); for (i = 0; i < sbi->s_gdb_count; i++) brelse(sbi->s_group_desc[i]); kvfree(sbi->s_group_desc); kvfree(sbi->s_flex_groups); percpu_counter_destroy(&sbi->s_freeclusters_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyclusters_counter); brelse(sbi->s_sbh); #ifdef CONFIG_QUOTA for (i = 0; i < EXT4_MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif /* Debugging code just in case the in-memory inode orphan list * isn't empty. The on-disk one can be non-empty if we've * detected an error and taken the fs readonly, but the * in-memory list had better be clean by this point. */ if (!list_empty(&sbi->s_orphan)) dump_orphan_list(sb, sbi); J_ASSERT(list_empty(&sbi->s_orphan)); sync_blockdev(sb->s_bdev); invalidate_bdev(sb->s_bdev); if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) { /* * Invalidate the journal device's buffers. We don't want them * floating about in memory - the physical journal device may * hotswapped, and it breaks the `ro-after' testing code. */ sync_blockdev(sbi->journal_bdev); invalidate_bdev(sbi->journal_bdev); ext4_blkdev_remove(sbi); } if (sbi->s_mb_cache) { ext4_xattr_destroy_cache(sbi->s_mb_cache); sbi->s_mb_cache = NULL; } if (sbi->s_mmp_tsk) kthread_stop(sbi->s_mmp_tsk); sb->s_fs_info = NULL; /* * Now that we are completely done shutting down the * superblock, we need to actually destroy the kobject. */ kobject_put(&sbi->s_kobj); wait_for_completion(&sbi->s_kobj_unregister); if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->s_blockgroup_lock); kfree(sbi); }
169,987
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: mrb_obj_clone(mrb_state *mrb, mrb_value self) { struct RObject *p; mrb_value clone; if (mrb_immediate_p(self)) { mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self); } if (mrb_type(self) == MRB_TT_SCLASS) { mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class"); } p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self)); p->c = mrb_singleton_class_clone(mrb, self); mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c); clone = mrb_obj_value(p); init_copy(mrb, clone, self); p->flags = mrb_obj_ptr(self)->flags; return clone; } Commit Message: Allow `Object#clone` to copy frozen status only; fix #4036 Copying all flags from the original object may overwrite the clone's flags e.g. the embedded flag. CWE ID: CWE-476
mrb_obj_clone(mrb_state *mrb, mrb_value self) { struct RObject *p; mrb_value clone; if (mrb_immediate_p(self)) { mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self); } if (mrb_type(self) == MRB_TT_SCLASS) { mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class"); } p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self)); p->c = mrb_singleton_class_clone(mrb, self); mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c); clone = mrb_obj_value(p); init_copy(mrb, clone, self); p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN; return clone; }
169,202
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t MediaPlayer::setDataSource( const sp<IMediaHTTPService> &httpService, const char *url, const KeyedVector<String8, String8> *headers) { ALOGV("setDataSource(%s)", url); status_t err = BAD_VALUE; if (url != NULL) { const sp<IMediaPlayerService>& service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(httpService, url, headers))) { player.clear(); } err = attachNewPlayer(player); } } return err; } Commit Message: Don't use sp<>& because they may end up pointing to NULL after a NULL check was performed. Bug: 28166152 Change-Id: Iab2ea30395b620628cc6f3d067dd4f6fcda824fe CWE ID: CWE-476
status_t MediaPlayer::setDataSource( const sp<IMediaHTTPService> &httpService, const char *url, const KeyedVector<String8, String8> *headers) { ALOGV("setDataSource(%s)", url); status_t err = BAD_VALUE; if (url != NULL) { const sp<IMediaPlayerService> service(getMediaPlayerService()); if (service != 0) { sp<IMediaPlayer> player(service->create(this, mAudioSessionId)); if ((NO_ERROR != doSetRetransmitEndpoint(player)) || (NO_ERROR != player->setDataSource(httpService, url, headers))) { player.clear(); } err = attachNewPlayer(player); } } return err; }
173,537
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if ((image->columns == 0) || (image->rows == 0)) { char primitive[MaxTextExtent]; register char *p; SegmentInfo bounds; /* Determine size of image canvas. */ while (ReadBlobString(image,primitive) != (char *) NULL) { for (p=primitive; (*p == ' ') || (*p == '\t'); p++) ; if (LocaleNCompare(BoundingBox,p,strlen(BoundingBox)) != 0) continue; (void) sscanf(p,"viewbox %lf %lf %lf %lf",&bounds.x1,&bounds.y1, &bounds.x2,&bounds.y2); image->columns=(size_t) floor((bounds.x2-bounds.x1)+0.5); image->rows=(size_t) floor((bounds.y2-bounds.y1)+0.5); break; } } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/ DefaultResolution; draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory(GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image), GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "viewbox" DrawInfo *draw_info; Image *image; MagickBooleanType status; /* Open image. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if ((image->columns == 0) || (image->rows == 0)) { char primitive[MaxTextExtent]; register char *p; SegmentInfo bounds; /* Determine size of image canvas. */ while (ReadBlobString(image,primitive) != (char *) NULL) { for (p=primitive; (*p == ' ') || (*p == '\t'); p++) ; if (LocaleNCompare(BoundingBox,p,strlen(BoundingBox)) != 0) continue; (void) sscanf(p,"viewbox %lf %lf %lf %lf",&bounds.x1,&bounds.y1, &bounds.x2,&bounds.y2); image->columns=(size_t) floor((bounds.x2-bounds.x1)+0.5); image->rows=(size_t) floor((bounds.y2-bounds.y1)+0.5); break; } } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/ DefaultResolution; draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/ DefaultResolution; image->columns=(size_t) (draw_info->affine.sx*image->columns); image->rows=(size_t) (draw_info->affine.sy*image->rows); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } /* Render drawing. */ if (GetBlobStreamData(image) == (unsigned char *) NULL) draw_info->primitive=FileToString(image->filename,~0UL,exception); else { draw_info->primitive=(char *) AcquireMagickMemory(GetBlobSize(image)+1); if (draw_info->primitive != (char *) NULL) { CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image), GetBlobSize(image)); draw_info->primitive[GetBlobSize(image)]='\0'; } } (void) DrawImage(image,draw_info); draw_info=DestroyDrawInfo(draw_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } }
167,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength", image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/350 CWE ID: CWE-787
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); }
168,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: parse_file (FILE* input_file, char* directory, char *body_filename, char *body_pref, int flags) { uint32 d; uint16 key; Attr *attr = NULL; File *file = NULL; int rtf_size = 0, html_size = 0; MessageBody body; memset (&body, '\0', sizeof (MessageBody)); /* store the program options in our file global variables */ g_flags = flags; /* check that this is in fact a TNEF file */ d = geti32(input_file); if (d != TNEF_SIGNATURE) { fprintf (stdout, "Seems not to be a TNEF file\n"); return 1; } /* Get the key */ key = geti16(input_file); debug_print ("TNEF Key: %hx\n", key); /* The rest of the file is a series of 'messages' and 'attachments' */ while ( data_left( input_file ) ) { attr = read_object( input_file ); if ( attr == NULL ) break; /* This signals the beginning of a file */ if (attr->name == attATTACHRENDDATA) { if (file) { file_write (file, directory); file_free (file); } else { file = CHECKED_XCALLOC (File, 1); } } /* Add the data to our lists. */ switch (attr->lvl_type) { case LVL_MESSAGE: if (attr->name == attBODY) { body.text_body = get_text_data (attr); } else if (attr->name == attMAPIPROPS) { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { int i; for (i = 0; mapi_attrs[i]; i++) { MAPI_Attr *a = mapi_attrs[i]; if (a->name == MAPI_BODY_HTML) { body.html_bodies = get_html_data (a); html_size = a->num_values; } else if (a->name == MAPI_RTF_COMPRESSED) { body.rtf_bodies = get_rtf_data (a); rtf_size = a->num_values; } } /* cannot save attributes to file, since they * are not attachment attributes */ /* file_add_mapi_attrs (file, mapi_attrs); */ mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case LVL_ATTACHMENT: file_add_attr (file, attr); break; default: fprintf (stderr, "Invalid lvl type on attribute: %d\n", attr->lvl_type); return 1; break; } attr_free (attr); XFREE (attr); } if (file) { file_write (file, directory); file_free (file); XFREE (file); } /* Write the message body */ if (flags & SAVEBODY) { int i = 0; int all_flag = 0; if (strcmp (body_pref, "all") == 0) { all_flag = 1; body_pref = "rht"; } for (; i < 3; i++) { File **files = get_body_files (body_filename, body_pref[i], &body); if (files) { int j = 0; for (; files[j]; j++) { file_write(files[j], directory); file_free (files[j]); XFREE(files[j]); } XFREE(files); if (!all_flag) break; } } } if (body.text_body) { free_bodies(body.text_body, 1); XFREE(body.text_body); } if (rtf_size > 0) { free_bodies(body.rtf_bodies, rtf_size); XFREE(body.rtf_bodies); } if (html_size > 0) { free_bodies(body.html_bodies, html_size); XFREE(body.html_bodies); } return 0; } Commit Message: Check types to avoid invalid reads/writes. CWE ID: CWE-125
parse_file (FILE* input_file, char* directory, char *body_filename, char *body_pref, int flags) { uint32 d; uint16 key; Attr *attr = NULL; File *file = NULL; int rtf_size = 0, html_size = 0; MessageBody body; memset (&body, '\0', sizeof (MessageBody)); /* store the program options in our file global variables */ g_flags = flags; /* check that this is in fact a TNEF file */ d = geti32(input_file); if (d != TNEF_SIGNATURE) { fprintf (stdout, "Seems not to be a TNEF file\n"); return 1; } /* Get the key */ key = geti16(input_file); debug_print ("TNEF Key: %hx\n", key); /* The rest of the file is a series of 'messages' and 'attachments' */ while ( data_left( input_file ) ) { attr = read_object( input_file ); if ( attr == NULL ) break; /* This signals the beginning of a file */ if (attr->name == attATTACHRENDDATA) { if (file) { file_write (file, directory); file_free (file); } else { file = CHECKED_XCALLOC (File, 1); } } /* Add the data to our lists. */ switch (attr->lvl_type) { case LVL_MESSAGE: if (attr->name == attBODY) { body.text_body = get_text_data (attr); } else if (attr->name == attMAPIPROPS) { MAPI_Attr **mapi_attrs = mapi_attr_read (attr->len, attr->buf); if (mapi_attrs) { int i; for (i = 0; mapi_attrs[i]; i++) { MAPI_Attr *a = mapi_attrs[i]; if (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML) { body.html_bodies = get_html_data (a); html_size = a->num_values; } else if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED) { body.rtf_bodies = get_rtf_data (a); rtf_size = a->num_values; } } /* cannot save attributes to file, since they * are not attachment attributes */ /* file_add_mapi_attrs (file, mapi_attrs); */ mapi_attr_free_list (mapi_attrs); XFREE (mapi_attrs); } } break; case LVL_ATTACHMENT: file_add_attr (file, attr); break; default: fprintf (stderr, "Invalid lvl type on attribute: %d\n", attr->lvl_type); return 1; break; } attr_free (attr); XFREE (attr); } if (file) { file_write (file, directory); file_free (file); XFREE (file); } /* Write the message body */ if (flags & SAVEBODY) { int i = 0; int all_flag = 0; if (strcmp (body_pref, "all") == 0) { all_flag = 1; body_pref = "rht"; } for (; i < 3; i++) { File **files = get_body_files (body_filename, body_pref[i], &body); if (files) { int j = 0; for (; files[j]; j++) { file_write(files[j], directory); file_free (files[j]); XFREE(files[j]); } XFREE(files); if (!all_flag) break; } } } if (body.text_body) { free_bodies(body.text_body, 1); XFREE(body.text_body); } if (rtf_size > 0) { free_bodies(body.rtf_bodies, rtf_size); XFREE(body.rtf_bodies); } if (html_size > 0) { free_bodies(body.html_bodies, html_size); XFREE(body.html_bodies); } return 0; }
168,353
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadItemImpl::OnDownloadRenamedToFinalName( DownloadFileManager* file_manager, const FilePath& full_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); VLOG(20) << __FUNCTION__ << "()" << " full_path = \"" << full_path.value() << "\"" << " needed rename = " << NeedsRename() << " " << DebugString(false); DCHECK(NeedsRename()); if (!full_path.empty()) { target_path_ = full_path; SetFullPath(full_path); delegate_->DownloadRenamedToFinalName(this); if (delegate_->ShouldOpenDownload(this)) Completed(); else delegate_delayed_complete_ = true; BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::CompleteDownload, file_manager, GetGlobalId())); } } Commit Message: Refactors to simplify rename pathway in DownloadFileManager. This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted due to CrOS failure) with the completion logic moved to after the auto-opening. The tests that test the auto-opening (for web store install) were waiting for download completion to check install, and hence were failing when completion was moved earlier. Doing this right would probably require another state (OPENED). BUG=123998 BUG-134930 [email protected] Review URL: https://chromiumcodereview.appspot.com/10701040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void DownloadItemImpl::OnDownloadRenamedToFinalName( DownloadFileManager* file_manager, const FilePath& full_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); VLOG(20) << __FUNCTION__ << "()" << " full_path = \"" << full_path.value() << "\"" << " needed rename = " << NeedsRename() << " " << DebugString(false); DCHECK(NeedsRename()); if (full_path.empty()) // Indicates error; also reported // by DownloadManagerImpl::OnDownloadInterrupted. return; // full_path is now the current and target file path. target_path_ = full_path; SetFullPath(full_path); delegate_->DownloadRenamedToFinalName(this); // Complete the download and release the DownloadFile. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&DownloadFileManager::CompleteDownload, file_manager, GetGlobalId(), base::Bind(&DownloadItemImpl::OnDownloadFileReleased, weak_ptr_factory_.GetWeakPtr()))); } void DownloadItemImpl::OnDownloadFileReleased() { if (delegate_->ShouldOpenDownload(this)) Completed(); else delegate_delayed_complete_ = true; }
170,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: stf_status ikev2parent_inI1outR1(struct msg_digest *md) { struct state *st = md->st; lset_t policy = POLICY_IKEV2_ALLOW; struct connection *c = find_host_connection(&md->iface->ip_addr, md->iface->port, &md->sender, md->sender_port, POLICY_IKEV2_ALLOW); /* retrieve st->st_gi */ #if 0 if (c == NULL) { /* * make up a policy from the thing that was proposed, and see * if we can find a connection with that policy. */ pb_stream pre_sa_pbs = sa_pd->pbs; policy = preparse_isakmp_sa_body(&pre_sa_pbs); c = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); } #endif if (c == NULL) { /* See if a wildcarded connection can be found. * We cannot pick the right connection, so we're making a guess. * All Road Warrior connections are fair game: * we pick the first we come across (if any). * If we don't find any, we pick the first opportunistic * with the smallest subnet that includes the peer. * There is, of course, no necessary relationship between * an Initiator's address and that of its client, * but Food Groups kind of assumes one. */ { struct connection *d; d = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); for (; d != NULL; d = d->hp_next) { if (d->kind == CK_GROUP) { /* ignore */ } else { if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)) { /* must be Road Warrior: we have a winner */ c = d; break; } /* Opportunistic or Shunt: pick tightest match */ if (addrinsubnet(&md->sender, &d->spd.that.client) && (c == NULL || !subnetinsubnet(&c->spd.that. client, &d->spd.that. client))) c = d; } } } if (c == NULL) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but no connection has been authorized%s%s", ip_str( &md->iface->ip_addr), ntohs(portof(&md->iface->ip_addr)), (policy != LEMPTY) ? " with policy=" : "", (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : ""); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } if (c->kind != CK_TEMPLATE) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but \"%s\" forbids connection", ip_str( &md->iface->ip_addr), pluto_port, c->name); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } c = rw_instantiate(c, &md->sender, NULL, NULL); } else { /* we found a non-wildcard conn. double check if it needs instantiation anyway (eg vnet=) */ /* vnet=/vhost= should have set CK_TEMPLATE on connection loading */ if ((c->kind == CK_TEMPLATE) && c->spd.that.virt) { DBG(DBG_CONTROL, DBG_log( "local endpoint has virt (vnet/vhost) set without wildcards - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } else if ((c->kind == CK_TEMPLATE) && (c->policy & POLICY_IKEV2_ALLOW_NARROWING)) { DBG(DBG_CONTROL, DBG_log( "local endpoint has narrowing=yes - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } } DBG_log("found connection: %s\n", c ? c->name : "<none>"); if (!st) { st = new_state(); /* set up new state */ memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE); /* initialize_new_state expects valid icookie/rcookie values, so create it now */ get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender); initialize_new_state(st, c, policy, 0, NULL_FD, pcim_stranger_crypto); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_R1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; md->st = st; md->from_state = STATE_IKEv2_BASE; } /* check,as a responder, are we under dos attack or not * if yes go to 6 message exchange mode. it is a config option for now. * TBD set force_busy dynamically * Paul: Can we check for STF_TOOMUCHCRYPTO ? */ if (force_busy == TRUE) { u_char dcookie[SHA1_DIGEST_SIZE]; chunk_t dc; ikev2_get_dcookie( dcookie, st->st_ni, &md->sender, st->st_icookie); dc.ptr = dcookie; dc.len = SHA1_DIGEST_SIZE; /* check if I1 packet contian KE and a v2N payload with type COOKIE */ if ( md->chain[ISAKMP_NEXT_v2KE] && md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE)) { u_int8_t spisize; const pb_stream *dc_pbs; chunk_t blob; DBG(DBG_CONTROLMORE, DBG_log("received a DOS cookie in I1 verify it")); /* we received dcookie we send earlier verify it */ spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n. isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; blob.ptr = dc_pbs->cur + spisize; blob.len = pbs_left(dc_pbs) - spisize; DBG(DBG_CONTROLMORE, DBG_dump_chunk("dcookie received in I1 Packet", blob); DBG_dump("dcookie computed", dcookie, SHA1_DIGEST_SIZE)); if (memcmp(blob.ptr, dcookie, SHA1_DIGEST_SIZE) != 0) { libreswan_log( "mismatch in DOS v2N_COOKIE,send a new one"); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL + v2N_INVALID_IKE_SPI; } DBG(DBG_CONTROLMORE, DBG_log("dcookie received match with computed one")); } else { /* we are under DOS attack I1 contains no DOS COOKIE */ DBG(DBG_CONTROLMORE, DBG_log( "busy mode on. receieved I1 without a valid dcookie"); DBG_log("send a dcookie and forget this state")); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL; } } else { DBG(DBG_CONTROLMORE, DBG_log("will not send/process a dcookie")); } /* * We have to agree to the DH group before we actually know who * we are talking to. If we support the group, we use it. * * It is really too hard here to go through all the possible policies * that might permit this group. If we think we are being DOS'ed * then we should demand a cookie. */ { struct ikev2_ke *ke; ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; st->st_oakley.group = lookup_group(ke->isak_group); if (st->st_oakley.group == NULL) { char fromname[ADDRTOT_BUF]; addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); libreswan_log( "rejecting I1 from %s:%u, invalid DH group=%u", fromname, md->sender_port, ke->isak_group); return v2N_INVALID_KE_PAYLOAD; } } /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, "ikev2_inI1outR1 KE"); stf_status e; ke->md = md; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_inI1outR1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, pcim_stranger_crypto); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } } else { e = ikev2_parent_inI1outR1_tail((struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20
stf_status ikev2parent_inI1outR1(struct msg_digest *md) { struct state *st = md->st; lset_t policy = POLICY_IKEV2_ALLOW; struct connection *c = find_host_connection(&md->iface->ip_addr, md->iface->port, &md->sender, md->sender_port, POLICY_IKEV2_ALLOW); /* retrieve st->st_gi */ #if 0 if (c == NULL) { /* * make up a policy from the thing that was proposed, and see * if we can find a connection with that policy. */ pb_stream pre_sa_pbs = sa_pd->pbs; policy = preparse_isakmp_sa_body(&pre_sa_pbs); c = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); } #endif if (c == NULL) { /* See if a wildcarded connection can be found. * We cannot pick the right connection, so we're making a guess. * All Road Warrior connections are fair game: * we pick the first we come across (if any). * If we don't find any, we pick the first opportunistic * with the smallest subnet that includes the peer. * There is, of course, no necessary relationship between * an Initiator's address and that of its client, * but Food Groups kind of assumes one. */ { struct connection *d; d = find_host_connection(&md->iface->ip_addr, pluto_port, (ip_address*)NULL, md->sender_port, policy); for (; d != NULL; d = d->hp_next) { if (d->kind == CK_GROUP) { /* ignore */ } else { if (d->kind == CK_TEMPLATE && !(d->policy & POLICY_OPPO)) { /* must be Road Warrior: we have a winner */ c = d; break; } /* Opportunistic or Shunt: pick tightest match */ if (addrinsubnet(&md->sender, &d->spd.that.client) && (c == NULL || !subnetinsubnet(&c->spd.that. client, &d->spd.that. client))) c = d; } } } if (c == NULL) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but no connection has been authorized%s%s", ip_str( &md->iface->ip_addr), ntohs(portof(&md->iface->ip_addr)), (policy != LEMPTY) ? " with policy=" : "", (policy != LEMPTY) ? bitnamesof(sa_policy_bit_names, policy) : ""); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } if (c->kind != CK_TEMPLATE) { loglog(RC_LOG_SERIOUS, "initial parent SA message received on %s:%u" " but \"%s\" forbids connection", ip_str( &md->iface->ip_addr), pluto_port, c->name); return STF_FAIL + v2N_NO_PROPOSAL_CHOSEN; } c = rw_instantiate(c, &md->sender, NULL, NULL); } else { /* we found a non-wildcard conn. double check if it needs instantiation anyway (eg vnet=) */ /* vnet=/vhost= should have set CK_TEMPLATE on connection loading */ if ((c->kind == CK_TEMPLATE) && c->spd.that.virt) { DBG(DBG_CONTROL, DBG_log( "local endpoint has virt (vnet/vhost) set without wildcards - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } else if ((c->kind == CK_TEMPLATE) && (c->policy & POLICY_IKEV2_ALLOW_NARROWING)) { DBG(DBG_CONTROL, DBG_log( "local endpoint has narrowing=yes - needs instantiation")); c = rw_instantiate(c, &md->sender, NULL, NULL); } } DBG_log("found connection: %s\n", c ? c->name : "<none>"); if (!st) { st = new_state(); /* set up new state */ memcpy(st->st_icookie, md->hdr.isa_icookie, COOKIE_SIZE); /* initialize_new_state expects valid icookie/rcookie values, so create it now */ get_cookie(FALSE, st->st_rcookie, COOKIE_SIZE, &md->sender); initialize_new_state(st, c, policy, 0, NULL_FD, pcim_stranger_crypto); st->st_ikev2 = TRUE; change_state(st, STATE_PARENT_R1); st->st_msgid_lastack = INVALID_MSGID; st->st_msgid_nextuse = 0; md->st = st; md->from_state = STATE_IKEv2_BASE; } /* check,as a responder, are we under dos attack or not * if yes go to 6 message exchange mode. it is a config option for now. * TBD set force_busy dynamically * Paul: Can we check for STF_TOOMUCHCRYPTO ? */ if (force_busy == TRUE) { u_char dcookie[SHA1_DIGEST_SIZE]; chunk_t dc; ikev2_get_dcookie( dcookie, st->st_ni, &md->sender, st->st_icookie); dc.ptr = dcookie; dc.len = SHA1_DIGEST_SIZE; /* check if I1 packet contian KE and a v2N payload with type COOKIE */ if ( md->chain[ISAKMP_NEXT_v2KE] && md->chain[ISAKMP_NEXT_v2N] && (md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type == v2N_COOKIE)) { u_int8_t spisize; const pb_stream *dc_pbs; chunk_t blob; DBG(DBG_CONTROLMORE, DBG_log("received a DOS cookie in I1 verify it")); /* we received dcookie we send earlier verify it */ spisize = md->chain[ISAKMP_NEXT_v2N]->payload.v2n. isan_spisize; dc_pbs = &md->chain[ISAKMP_NEXT_v2N]->pbs; blob.ptr = dc_pbs->cur + spisize; blob.len = pbs_left(dc_pbs) - spisize; DBG(DBG_CONTROLMORE, DBG_dump_chunk("dcookie received in I1 Packet", blob); DBG_dump("dcookie computed", dcookie, SHA1_DIGEST_SIZE)); if (memcmp(blob.ptr, dcookie, SHA1_DIGEST_SIZE) != 0) { libreswan_log( "mismatch in DOS v2N_COOKIE,send a new one"); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL + v2N_INVALID_IKE_SPI; } DBG(DBG_CONTROLMORE, DBG_log("dcookie received match with computed one")); } else { /* we are under DOS attack I1 contains no DOS COOKIE */ DBG(DBG_CONTROLMORE, DBG_log( "busy mode on. receieved I1 without a valid dcookie"); DBG_log("send a dcookie and forget this state")); SEND_NOTIFICATION_AA(v2N_COOKIE, &dc); return STF_FAIL; } } else { DBG(DBG_CONTROLMORE, DBG_log("will not send/process a dcookie")); } /* * We have to agree to the DH group before we actually know who * we are talking to. If we support the group, we use it. * * It is really too hard here to go through all the possible policies * that might permit this group. If we think we are being DOS'ed * then we should demand a cookie. */ { struct ikev2_ke *ke; char fromname[ADDRTOT_BUF]; addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); if (!md->chain[ISAKMP_NEXT_v2KE]) { /* is this a notify? If so, log it */ if(md->chain[ISAKMP_NEXT_v2N]) { libreswan_log("Received Notify(%d): %s", md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type, enum_name(&ikev2_notify_names, md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type)); } libreswan_log( "rejecting I1 from %s:%u, no KE payload present", fromname, md->sender_port); return STF_FAIL + v2N_INVALID_KE_PAYLOAD; } ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; st->st_oakley.group = lookup_group(ke->isak_group); if (st->st_oakley.group == NULL) { libreswan_log( "rejecting I1 from %s:%u, invalid DH group=%u", fromname, md->sender_port, ke->isak_group); return STF_FAIL + v2N_INVALID_KE_PAYLOAD; } } /* now. we need to go calculate the nonce, and the KE */ { struct ke_continuation *ke = alloc_thing( struct ke_continuation, "ikev2_inI1outR1 KE"); stf_status e; ke->md = md; set_suspended(st, ke->md); if (!st->st_sec_in_use) { pcrc_init(&ke->ke_pcrc); ke->ke_pcrc.pcrc_func = ikev2_parent_inI1outR1_continue; e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, pcim_stranger_crypto); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } } else { e = ikev2_parent_inI1outR1_tail((struct pluto_crypto_req_cont *)ke, NULL); } reset_globals(); return e; } }
166,474
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PermissionsContainsFunction::RunImpl() { scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_)); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, &error_); if (!permissions.get()) return false; results_ = Contains::Results::Create( GetExtension()->GetActivePermissions()->Contains(*permissions)); return true; } Commit Message: Check prefs before allowing extension file access in the permissions API. [email protected] BUG=169632 Review URL: https://chromiumcodereview.appspot.com/11884008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176853 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool PermissionsContainsFunction::RunImpl() { scoped_ptr<Contains::Params> params(Contains::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); ExtensionPrefs* prefs = ExtensionSystem::Get(profile_)->extension_prefs(); scoped_refptr<PermissionSet> permissions = helpers::UnpackPermissionSet(params->permissions, prefs->AllowFileAccess(extension_->id()), &error_); if (!permissions.get()) return false; results_ = Contains::Results::Create( GetExtension()->GetActivePermissions()->Contains(*permissions)); return true; }
171,442
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int HttpStreamParser::DoReadHeadersComplete(int result) { if (result == 0) result = ERR_CONNECTION_CLOSED; if (result < 0 && result != ERR_CONNECTION_CLOSED) { io_state_ = STATE_DONE; return result; } if (result == ERR_CONNECTION_CLOSED && read_buf_->offset() == 0 && connection_->is_reused()) { io_state_ = STATE_DONE; return result; } if (read_buf_->offset() == 0 && result != ERR_CONNECTION_CLOSED) response_->response_time = base::Time::Now(); if (result == ERR_CONNECTION_CLOSED) { io_state_ = STATE_DONE; return ERR_EMPTY_RESPONSE; } else { int end_offset; if (response_header_start_offset_ >= 0) { io_state_ = STATE_READ_BODY_COMPLETE; end_offset = read_buf_->offset(); } else { io_state_ = STATE_BODY_PENDING; end_offset = 0; } int rv = DoParseResponseHeaders(end_offset); if (rv < 0) return rv; return result; } } read_buf_->set_offset(read_buf_->offset() + result); DCHECK_LE(read_buf_->offset(), read_buf_->capacity()); DCHECK_GE(result, 0); int end_of_header_offset = ParseResponseHeaders(); if (end_of_header_offset < -1) return end_of_header_offset; if (end_of_header_offset == -1) { io_state_ = STATE_READ_HEADERS; if (read_buf_->offset() - read_buf_unused_offset_ >= kMaxHeaderBufSize) { io_state_ = STATE_DONE; return ERR_RESPONSE_HEADERS_TOO_BIG; } } else { read_buf_unused_offset_ = end_of_header_offset; if (response_->headers->response_code() / 100 == 1) { io_state_ = STATE_REQUEST_SENT; response_header_start_offset_ = -1; } else { io_state_ = STATE_BODY_PENDING; CalculateResponseBodySize(); if (response_body_length_ == 0) { io_state_ = STATE_DONE; int extra_bytes = read_buf_->offset() - read_buf_unused_offset_; if (extra_bytes) { CHECK_GT(extra_bytes, 0); memmove(read_buf_->StartOfBuffer(), read_buf_->StartOfBuffer() + read_buf_unused_offset_, extra_bytes); } read_buf_->SetCapacity(extra_bytes); read_buf_unused_offset_ = 0; return OK; } } } return result; } Commit Message: net: don't process truncated headers on HTTPS connections. This change causes us to not process any headers unless they are correctly terminated with a \r\n\r\n sequence. BUG=244260 Review URL: https://chromiumcodereview.appspot.com/15688012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@202927 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int HttpStreamParser::DoReadHeadersComplete(int result) { if (result == 0) result = ERR_CONNECTION_CLOSED; if (result < 0 && result != ERR_CONNECTION_CLOSED) { io_state_ = STATE_DONE; return result; } if (result == ERR_CONNECTION_CLOSED && read_buf_->offset() == 0 && connection_->is_reused()) { io_state_ = STATE_DONE; return result; } if (read_buf_->offset() == 0 && result != ERR_CONNECTION_CLOSED) response_->response_time = base::Time::Now(); if (result == ERR_CONNECTION_CLOSED) { io_state_ = STATE_DONE; return ERR_EMPTY_RESPONSE; } else if (request_->url.SchemeIs("https")) { // The connection was closed in the middle of the headers. For HTTPS we // don't parse partial headers. Return a different error code so that we // know that we shouldn't attempt to retry the request. io_state_ = STATE_DONE; return ERR_HEADERS_TRUNCATED; } // Parse things as well as we can and let the caller decide what to do. int end_offset; if (response_header_start_offset_ >= 0) { io_state_ = STATE_READ_BODY_COMPLETE; end_offset = read_buf_->offset(); } else { io_state_ = STATE_BODY_PENDING; end_offset = 0; } int rv = DoParseResponseHeaders(end_offset); if (rv < 0) return rv; return result; } read_buf_->set_offset(read_buf_->offset() + result); DCHECK_LE(read_buf_->offset(), read_buf_->capacity()); DCHECK_GE(result, 0); int end_of_header_offset = ParseResponseHeaders(); if (end_of_header_offset < -1) return end_of_header_offset; if (end_of_header_offset == -1) { io_state_ = STATE_READ_HEADERS; if (read_buf_->offset() - read_buf_unused_offset_ >= kMaxHeaderBufSize) { io_state_ = STATE_DONE; return ERR_RESPONSE_HEADERS_TOO_BIG; } } else { read_buf_unused_offset_ = end_of_header_offset; if (response_->headers->response_code() / 100 == 1) { io_state_ = STATE_REQUEST_SENT; response_header_start_offset_ = -1; } else { io_state_ = STATE_BODY_PENDING; CalculateResponseBodySize(); if (response_body_length_ == 0) { io_state_ = STATE_DONE; int extra_bytes = read_buf_->offset() - read_buf_unused_offset_; if (extra_bytes) { CHECK_GT(extra_bytes, 0); memmove(read_buf_->StartOfBuffer(), read_buf_->StartOfBuffer() + read_buf_unused_offset_, extra_bytes); } read_buf_->SetCapacity(extra_bytes); read_buf_unused_offset_ = 0; return OK; } } } return result; }
171,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: __releases(kernel_lock) __acquires(kernel_lock) { struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -EINVAL; int blocksize; unsigned int db_count; unsigned int i; int needs_recovery, has_huge_files; __u64 blocks_count; int err; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); return -ENOMEM; } sb->s_fs_info = sbi; sbi->s_mount_opt = 0; sbi->s_resuid = EXT4_DEF_RESUID; sbi->s_resgid = EXT4_DEF_RESGID; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part, sectors[1]); unlock_kernel(); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { ext4_msg(sb, KERN_ERR, "unable to set blocksize"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { ext4_msg(sb, KERN_ERR, "unable to read superblock"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written); /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sbi->s_mount_opt, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) { ext4_msg(sb, KERN_WARNING, deprecated_msg, "bsdgroups", "2.6.38"); set_opt(sbi->s_mount_opt, GRPID); } if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sbi->s_mount_opt, NO_UID32); #ifdef CONFIG_EXT4_FS_XATTR if (def_mount_opts & EXT4_DEFM_XATTR_USER) set_opt(sbi->s_mount_opt, XATTR_USER); #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL if (def_mount_opts & EXT4_DEFM_ACL) set_opt(sbi->s_mount_opt, POSIX_ACL); #endif if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) set_opt(sbi->s_mount_opt, JOURNAL_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) set_opt(sbi->s_mount_opt, ORDERED_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) set_opt(sbi->s_mount_opt, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sbi->s_mount_opt, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sbi->s_mount_opt, ERRORS_CONT); else set_opt(sbi->s_mount_opt, ERRORS_RO); sbi->s_resuid = le16_to_cpu(es->s_def_resuid); sbi->s_resgid = le16_to_cpu(es->s_def_resgid); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; set_opt(sbi->s_mount_opt, BARRIER); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ set_opt(sbi->s_mount_opt, DELALLOC); if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext4_msg(sb, KERN_WARNING, "feature flags set on rev 0 fs, " "running e2fsck is recommended"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY))) goto failed_mount; blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { ext4_msg(sb, KERN_ERR, "Unsupported filesystem blocksize %d", blocksize); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { ext4_msg(sb, KERN_ERR, "bad block size %d", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { ext4_msg(sb, KERN_ERR, "Can't read superblock on 2nd try"); goto failed_mount; } es = (struct ext4_super_block *)(((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { ext4_msg(sb, KERN_ERR, "Magic mismatch, very weird!"); goto failed_mount; } } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext4_msg(sb, KERN_ERR, "unsupported inode size: %d", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { ext4_msg(sb, KERN_ERR, "unsupported descriptor size %lu", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif sb->s_dirt = 1; } if (sbi->s_blocks_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#blocks per group too big: %lu", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#inodes per group too big: %lu", sbi->s_inodes_per_group); goto failed_mount; } /* * Test whether we have more sectors than will fit in sector_t, * and whether the max offset is addressable by the page cache. */ if ((ext4_blocks_count(es) > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) || (ext4_blocks_count(es) > (pgoff_t)(~0ULL) >> (PAGE_CACHE_SHIFT - sb->s_blocksize_bits))) { ext4_msg(sb, KERN_ERR, "filesystem" " too large to mount safely on this system"); if (sizeof(sector_t) < 8) ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled"); ret = -EFBIG; goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* check blocks count against device size */ blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; if (blocks_count && ext4_blocks_count(es) > blocks_count) { ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu " "exceeds size of device (%llu blocks)", ext4_blocks_count(es), blocks_count); goto failed_mount; } /* * It makes no sense for the first data block to be beyond the end * of the filesystem. */ if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) { ext4_msg(sb, KERN_WARNING, "bad geometry: first data" "block %u is beyond end of filesystem (%llu)", le32_to_cpu(es->s_first_data_block), ext4_blocks_count(es)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) { ext4_msg(sb, KERN_WARNING, "groups count too large: %u " "(block count %llu, first data block %u, " "blocks per group %lu)", sbi->s_groups_count, ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } sbi->s_groups_count = blocks_count; sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count, (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb))); db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory"); goto failed_mount; } #ifdef CONFIG_PROC_FS if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); #endif bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext4_msg(sb, KERN_ERR, "can't read group descriptor %d", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb)) { ext4_msg(sb, KERN_ERR, "group descriptors corrupted!"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { ext4_msg(sb, KERN_ERR, "unable to initialize " "flex_bg meta info!"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0); } if (err) { ext4_msg(sb, KERN_ERR, "insufficient memory"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); sbi->s_max_writeback_mb_bump = 128; /* * set up enough so that it can read an inode */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) sb->s_op = &ext4_sops; else sb->s_op = &ext4_nojournal_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext4_qctl_operations; sb->dq_op = &ext4_quota_operations; #endif INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); mutex_init(&sbi->s_resize_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { ext4_msg(sb, KERN_ERR, "required journal recovery " "suppressed and not mounted read-only"); goto failed_mount4; } else { clear_opt(sbi->s_mount_opt, DATA_FLAGS); set_opt(sbi->s_mount_opt, WRITEBACK_DATA); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (ext4_blocks_count(es) > 0xffffffffULL && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature"); goto failed_mount4; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sbi->s_mount_opt, ORDERED_DATA); else set_opt(sbi->s_mount_opt, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { ext4_msg(sb, KERN_ERR, "Journal does not support " "requested data journaling mode"); goto failed_mount4; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); no_journal: if (test_opt(sb, NOBH)) { if (!(test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)) { ext4_msg(sb, KERN_WARNING, "Ignoring nobh option - " "its supported only with writeback mode"); clear_opt(sbi->s_mount_opt, NOBH); } } EXT4_SB(sb)->dio_unwritten_wq = create_workqueue("ext4-dio-unwritten"); if (!EXT4_SB(sb)->dio_unwritten_wq) { printk(KERN_ERR "EXT4-fs: failed to create DIO workqueue\n"); goto failed_mount_wq; } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { ext4_msg(sb, KERN_ERR, "get root inode failed"); ret = PTR_ERR(root); goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck"); goto failed_mount4; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { ext4_msg(sb, KERN_ERR, "get root dentry failed"); iput(root); ret = -ENOMEM; goto failed_mount4; } ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY); /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, "required extra inode space not" "available"); } if (test_opt(sb, DELALLOC) && (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) { ext4_msg(sb, KERN_WARNING, "Ignoring delalloc option - " "requested data journaling mode"); clear_opt(sbi->s_mount_opt, DELALLOC); } err = ext4_setup_system_zone(sb); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize system " "zone (%d)\n", err); goto failed_mount4; } ext4_ext_init(sb); err = ext4_mb_init(sb, needs_recovery); if (err) { ext4_msg(sb, KERN_ERR, "failed to initalize mballoc (%d)", err); goto failed_mount4; } sbi->s_kobj.kset = ext4_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL, "%s", sb->s_id); if (err) { ext4_mb_release(sb); ext4_ext_release(sb); goto failed_mount4; }; EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { ext4_msg(sb, KERN_INFO, "recovery complete"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = " journalled data mode"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = " ordered data mode"; else descr = " writeback data mode"; } else descr = "out journal"; ext4_msg(sb, KERN_INFO, "mounted filesystem with%s", descr); lock_kernel(); return 0; cantfind_ext4: if (!silent) ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem"); goto failed_mount; failed_mount4: ext4_msg(sb, KERN_ERR, "mount failed"); destroy_workqueue(EXT4_SB(sb)->dio_unwritten_wq); failed_mount_wq: ext4_release_system_zone(sb); if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: if (sbi->s_flex_groups) { if (is_vmalloc_addr(sbi->s_flex_groups)) vfree(sbi->s_flex_groups); else kfree(sbi->s_flex_groups); } percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyblocks_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: if (sbi->s_proc) { remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); lock_kernel(); return ret; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
__releases(kernel_lock) __acquires(kernel_lock) { struct buffer_head *bh; struct ext4_super_block *es = NULL; struct ext4_sb_info *sbi; ext4_fsblk_t block; ext4_fsblk_t sb_block = get_sb_block(&data); ext4_fsblk_t logical_sb_block; unsigned long offset = 0; unsigned long journal_devnum = 0; unsigned long def_mount_opts; struct inode *root; char *cp; const char *descr; int ret = -EINVAL; int blocksize; unsigned int db_count; unsigned int i; int needs_recovery, has_huge_files; __u64 blocks_count; int err; unsigned int journal_ioprio = DEFAULT_JOURNAL_IOPRIO; sbi = kzalloc(sizeof(*sbi), GFP_KERNEL); if (!sbi) return -ENOMEM; sbi->s_blockgroup_lock = kzalloc(sizeof(struct blockgroup_lock), GFP_KERNEL); if (!sbi->s_blockgroup_lock) { kfree(sbi); return -ENOMEM; } sb->s_fs_info = sbi; sbi->s_mount_opt = 0; sbi->s_resuid = EXT4_DEF_RESUID; sbi->s_resgid = EXT4_DEF_RESGID; sbi->s_inode_readahead_blks = EXT4_DEF_INODE_READAHEAD_BLKS; sbi->s_sb_block = sb_block; sbi->s_sectors_written_start = part_stat_read(sb->s_bdev->bd_part, sectors[1]); unlock_kernel(); /* Cleanup superblock name */ for (cp = sb->s_id; (cp = strchr(cp, '/'));) *cp = '!'; blocksize = sb_min_blocksize(sb, EXT4_MIN_BLOCK_SIZE); if (!blocksize) { ext4_msg(sb, KERN_ERR, "unable to set blocksize"); goto out_fail; } /* * The ext4 superblock will not be buffer aligned for other than 1kB * block sizes. We need to calculate the offset from buffer start. */ if (blocksize != EXT4_MIN_BLOCK_SIZE) { logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); } else { logical_sb_block = sb_block; } if (!(bh = sb_bread(sb, logical_sb_block))) { ext4_msg(sb, KERN_ERR, "unable to read superblock"); goto out_fail; } /* * Note: s_es must be initialized as soon as possible because * some ext4 macro-instructions depend on its value */ es = (struct ext4_super_block *) (((char *)bh->b_data) + offset); sbi->s_es = es; sb->s_magic = le16_to_cpu(es->s_magic); if (sb->s_magic != EXT4_SUPER_MAGIC) goto cantfind_ext4; sbi->s_kbytes_written = le64_to_cpu(es->s_kbytes_written); /* Set defaults before we parse the mount options */ def_mount_opts = le32_to_cpu(es->s_default_mount_opts); if (def_mount_opts & EXT4_DEFM_DEBUG) set_opt(sbi->s_mount_opt, DEBUG); if (def_mount_opts & EXT4_DEFM_BSDGROUPS) { ext4_msg(sb, KERN_WARNING, deprecated_msg, "bsdgroups", "2.6.38"); set_opt(sbi->s_mount_opt, GRPID); } if (def_mount_opts & EXT4_DEFM_UID16) set_opt(sbi->s_mount_opt, NO_UID32); #ifdef CONFIG_EXT4_FS_XATTR if (def_mount_opts & EXT4_DEFM_XATTR_USER) set_opt(sbi->s_mount_opt, XATTR_USER); #endif #ifdef CONFIG_EXT4_FS_POSIX_ACL if (def_mount_opts & EXT4_DEFM_ACL) set_opt(sbi->s_mount_opt, POSIX_ACL); #endif if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_DATA) set_opt(sbi->s_mount_opt, JOURNAL_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_ORDERED) set_opt(sbi->s_mount_opt, ORDERED_DATA); else if ((def_mount_opts & EXT4_DEFM_JMODE) == EXT4_DEFM_JMODE_WBACK) set_opt(sbi->s_mount_opt, WRITEBACK_DATA); if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_PANIC) set_opt(sbi->s_mount_opt, ERRORS_PANIC); else if (le16_to_cpu(sbi->s_es->s_errors) == EXT4_ERRORS_CONTINUE) set_opt(sbi->s_mount_opt, ERRORS_CONT); else set_opt(sbi->s_mount_opt, ERRORS_RO); sbi->s_resuid = le16_to_cpu(es->s_def_resuid); sbi->s_resgid = le16_to_cpu(es->s_def_resgid); sbi->s_commit_interval = JBD2_DEFAULT_MAX_COMMIT_AGE * HZ; sbi->s_min_batch_time = EXT4_DEF_MIN_BATCH_TIME; sbi->s_max_batch_time = EXT4_DEF_MAX_BATCH_TIME; set_opt(sbi->s_mount_opt, BARRIER); /* * enable delayed allocation by default * Use -o nodelalloc to turn it off */ set_opt(sbi->s_mount_opt, DELALLOC); if (!parse_options((char *) data, sb, &journal_devnum, &journal_ioprio, NULL, 0)) goto failed_mount; sb->s_flags = (sb->s_flags & ~MS_POSIXACL) | (test_opt(sb, POSIX_ACL) ? MS_POSIXACL : 0); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV && (EXT4_HAS_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_RO_COMPAT_FEATURE(sb, ~0U) || EXT4_HAS_INCOMPAT_FEATURE(sb, ~0U))) ext4_msg(sb, KERN_WARNING, "feature flags set on rev 0 fs, " "running e2fsck is recommended"); /* * Check feature flags regardless of the revision level, since we * previously didn't change the revision level when setting the flags, * so there is a chance incompat flags are set on a rev 0 filesystem. */ if (!ext4_feature_set_ok(sb, (sb->s_flags & MS_RDONLY))) goto failed_mount; blocksize = BLOCK_SIZE << le32_to_cpu(es->s_log_block_size); if (blocksize < EXT4_MIN_BLOCK_SIZE || blocksize > EXT4_MAX_BLOCK_SIZE) { ext4_msg(sb, KERN_ERR, "Unsupported filesystem blocksize %d", blocksize); goto failed_mount; } if (sb->s_blocksize != blocksize) { /* Validate the filesystem blocksize */ if (!sb_set_blocksize(sb, blocksize)) { ext4_msg(sb, KERN_ERR, "bad block size %d", blocksize); goto failed_mount; } brelse(bh); logical_sb_block = sb_block * EXT4_MIN_BLOCK_SIZE; offset = do_div(logical_sb_block, blocksize); bh = sb_bread(sb, logical_sb_block); if (!bh) { ext4_msg(sb, KERN_ERR, "Can't read superblock on 2nd try"); goto failed_mount; } es = (struct ext4_super_block *)(((char *)bh->b_data) + offset); sbi->s_es = es; if (es->s_magic != cpu_to_le16(EXT4_SUPER_MAGIC)) { ext4_msg(sb, KERN_ERR, "Magic mismatch, very weird!"); goto failed_mount; } } has_huge_files = EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE); sbi->s_bitmap_maxbytes = ext4_max_bitmap_size(sb->s_blocksize_bits, has_huge_files); sb->s_maxbytes = ext4_max_size(sb->s_blocksize_bits, has_huge_files); if (le32_to_cpu(es->s_rev_level) == EXT4_GOOD_OLD_REV) { sbi->s_inode_size = EXT4_GOOD_OLD_INODE_SIZE; sbi->s_first_ino = EXT4_GOOD_OLD_FIRST_INO; } else { sbi->s_inode_size = le16_to_cpu(es->s_inode_size); sbi->s_first_ino = le32_to_cpu(es->s_first_ino); if ((sbi->s_inode_size < EXT4_GOOD_OLD_INODE_SIZE) || (!is_power_of_2(sbi->s_inode_size)) || (sbi->s_inode_size > blocksize)) { ext4_msg(sb, KERN_ERR, "unsupported inode size: %d", sbi->s_inode_size); goto failed_mount; } if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) sb->s_time_gran = 1 << (EXT4_EPOCH_BITS - 2); } sbi->s_desc_size = le16_to_cpu(es->s_desc_size); if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT)) { if (sbi->s_desc_size < EXT4_MIN_DESC_SIZE_64BIT || sbi->s_desc_size > EXT4_MAX_DESC_SIZE || !is_power_of_2(sbi->s_desc_size)) { ext4_msg(sb, KERN_ERR, "unsupported descriptor size %lu", sbi->s_desc_size); goto failed_mount; } } else sbi->s_desc_size = EXT4_MIN_DESC_SIZE; sbi->s_blocks_per_group = le32_to_cpu(es->s_blocks_per_group); sbi->s_inodes_per_group = le32_to_cpu(es->s_inodes_per_group); if (EXT4_INODE_SIZE(sb) == 0 || EXT4_INODES_PER_GROUP(sb) == 0) goto cantfind_ext4; sbi->s_inodes_per_block = blocksize / EXT4_INODE_SIZE(sb); if (sbi->s_inodes_per_block == 0) goto cantfind_ext4; sbi->s_itb_per_group = sbi->s_inodes_per_group / sbi->s_inodes_per_block; sbi->s_desc_per_block = blocksize / EXT4_DESC_SIZE(sb); sbi->s_sbh = bh; sbi->s_mount_state = le16_to_cpu(es->s_state); sbi->s_addr_per_block_bits = ilog2(EXT4_ADDR_PER_BLOCK(sb)); sbi->s_desc_per_block_bits = ilog2(EXT4_DESC_PER_BLOCK(sb)); for (i = 0; i < 4; i++) sbi->s_hash_seed[i] = le32_to_cpu(es->s_hash_seed[i]); sbi->s_def_hash_version = es->s_def_hash_version; i = le32_to_cpu(es->s_flags); if (i & EXT2_FLAGS_UNSIGNED_HASH) sbi->s_hash_unsigned = 3; else if ((i & EXT2_FLAGS_SIGNED_HASH) == 0) { #ifdef __CHAR_UNSIGNED__ es->s_flags |= cpu_to_le32(EXT2_FLAGS_UNSIGNED_HASH); sbi->s_hash_unsigned = 3; #else es->s_flags |= cpu_to_le32(EXT2_FLAGS_SIGNED_HASH); #endif sb->s_dirt = 1; } if (sbi->s_blocks_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#blocks per group too big: %lu", sbi->s_blocks_per_group); goto failed_mount; } if (sbi->s_inodes_per_group > blocksize * 8) { ext4_msg(sb, KERN_ERR, "#inodes per group too big: %lu", sbi->s_inodes_per_group); goto failed_mount; } /* * Test whether we have more sectors than will fit in sector_t, * and whether the max offset is addressable by the page cache. */ if ((ext4_blocks_count(es) > (sector_t)(~0ULL) >> (sb->s_blocksize_bits - 9)) || (ext4_blocks_count(es) > (pgoff_t)(~0ULL) >> (PAGE_CACHE_SHIFT - sb->s_blocksize_bits))) { ext4_msg(sb, KERN_ERR, "filesystem" " too large to mount safely on this system"); if (sizeof(sector_t) < 8) ext4_msg(sb, KERN_WARNING, "CONFIG_LBDAF not enabled"); ret = -EFBIG; goto failed_mount; } if (EXT4_BLOCKS_PER_GROUP(sb) == 0) goto cantfind_ext4; /* check blocks count against device size */ blocks_count = sb->s_bdev->bd_inode->i_size >> sb->s_blocksize_bits; if (blocks_count && ext4_blocks_count(es) > blocks_count) { ext4_msg(sb, KERN_WARNING, "bad geometry: block count %llu " "exceeds size of device (%llu blocks)", ext4_blocks_count(es), blocks_count); goto failed_mount; } /* * It makes no sense for the first data block to be beyond the end * of the filesystem. */ if (le32_to_cpu(es->s_first_data_block) >= ext4_blocks_count(es)) { ext4_msg(sb, KERN_WARNING, "bad geometry: first data" "block %u is beyond end of filesystem (%llu)", le32_to_cpu(es->s_first_data_block), ext4_blocks_count(es)); goto failed_mount; } blocks_count = (ext4_blocks_count(es) - le32_to_cpu(es->s_first_data_block) + EXT4_BLOCKS_PER_GROUP(sb) - 1); do_div(blocks_count, EXT4_BLOCKS_PER_GROUP(sb)); if (blocks_count > ((uint64_t)1<<32) - EXT4_DESC_PER_BLOCK(sb)) { ext4_msg(sb, KERN_WARNING, "groups count too large: %u " "(block count %llu, first data block %u, " "blocks per group %lu)", sbi->s_groups_count, ext4_blocks_count(es), le32_to_cpu(es->s_first_data_block), EXT4_BLOCKS_PER_GROUP(sb)); goto failed_mount; } sbi->s_groups_count = blocks_count; sbi->s_blockfile_groups = min_t(ext4_group_t, sbi->s_groups_count, (EXT4_MAX_BLOCK_FILE_PHYS / EXT4_BLOCKS_PER_GROUP(sb))); db_count = (sbi->s_groups_count + EXT4_DESC_PER_BLOCK(sb) - 1) / EXT4_DESC_PER_BLOCK(sb); sbi->s_group_desc = kmalloc(db_count * sizeof(struct buffer_head *), GFP_KERNEL); if (sbi->s_group_desc == NULL) { ext4_msg(sb, KERN_ERR, "not enough memory"); goto failed_mount; } #ifdef CONFIG_PROC_FS if (ext4_proc_root) sbi->s_proc = proc_mkdir(sb->s_id, ext4_proc_root); #endif bgl_lock_init(sbi->s_blockgroup_lock); for (i = 0; i < db_count; i++) { block = descriptor_loc(sb, logical_sb_block, i); sbi->s_group_desc[i] = sb_bread(sb, block); if (!sbi->s_group_desc[i]) { ext4_msg(sb, KERN_ERR, "can't read group descriptor %d", i); db_count = i; goto failed_mount2; } } if (!ext4_check_descriptors(sb)) { ext4_msg(sb, KERN_ERR, "group descriptors corrupted!"); goto failed_mount2; } if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_FLEX_BG)) if (!ext4_fill_flex_info(sb)) { ext4_msg(sb, KERN_ERR, "unable to initialize " "flex_bg meta info!"); goto failed_mount2; } sbi->s_gdb_count = db_count; get_random_bytes(&sbi->s_next_generation, sizeof(u32)); spin_lock_init(&sbi->s_next_gen_lock); err = percpu_counter_init(&sbi->s_freeblocks_counter, ext4_count_free_blocks(sb)); if (!err) { err = percpu_counter_init(&sbi->s_freeinodes_counter, ext4_count_free_inodes(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirs_counter, ext4_count_dirs(sb)); } if (!err) { err = percpu_counter_init(&sbi->s_dirtyblocks_counter, 0); } if (err) { ext4_msg(sb, KERN_ERR, "insufficient memory"); goto failed_mount3; } sbi->s_stripe = ext4_get_stripe_size(sbi); sbi->s_max_writeback_mb_bump = 128; /* * set up enough so that it can read an inode */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) sb->s_op = &ext4_sops; else sb->s_op = &ext4_nojournal_sops; sb->s_export_op = &ext4_export_ops; sb->s_xattr = ext4_xattr_handlers; #ifdef CONFIG_QUOTA sb->s_qcop = &ext4_qctl_operations; sb->dq_op = &ext4_quota_operations; #endif INIT_LIST_HEAD(&sbi->s_orphan); /* unlinked but open files */ mutex_init(&sbi->s_orphan_lock); mutex_init(&sbi->s_resize_lock); sb->s_root = NULL; needs_recovery = (es->s_last_orphan != 0 || EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)); /* * The first inode we look at is the journal inode. Don't try * root first: it may be modified in the journal! */ if (!test_opt(sb, NOLOAD) && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_HAS_JOURNAL)) { if (ext4_load_journal(sb, es, journal_devnum)) goto failed_mount3; } else if (test_opt(sb, NOLOAD) && !(sb->s_flags & MS_RDONLY) && EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_RECOVER)) { ext4_msg(sb, KERN_ERR, "required journal recovery " "suppressed and not mounted read-only"); goto failed_mount_wq; } else { clear_opt(sbi->s_mount_opt, DATA_FLAGS); set_opt(sbi->s_mount_opt, WRITEBACK_DATA); sbi->s_journal = NULL; needs_recovery = 0; goto no_journal; } if (ext4_blocks_count(es) > 0xffffffffULL && !jbd2_journal_set_features(EXT4_SB(sb)->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_64BIT)) { ext4_msg(sb, KERN_ERR, "Failed to set 64-bit journal feature"); goto failed_mount_wq; } if (test_opt(sb, JOURNAL_ASYNC_COMMIT)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else if (test_opt(sb, JOURNAL_CHECKSUM)) { jbd2_journal_set_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, 0); jbd2_journal_clear_features(sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } else { jbd2_journal_clear_features(sbi->s_journal, JBD2_FEATURE_COMPAT_CHECKSUM, 0, JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT); } /* We have now updated the journal if required, so we can * validate the data journaling mode. */ switch (test_opt(sb, DATA_FLAGS)) { case 0: /* No mode set, assume a default based on the journal * capabilities: ORDERED_DATA if the journal can * cope, else JOURNAL_DATA */ if (jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) set_opt(sbi->s_mount_opt, ORDERED_DATA); else set_opt(sbi->s_mount_opt, JOURNAL_DATA); break; case EXT4_MOUNT_ORDERED_DATA: case EXT4_MOUNT_WRITEBACK_DATA: if (!jbd2_journal_check_available_features (sbi->s_journal, 0, 0, JBD2_FEATURE_INCOMPAT_REVOKE)) { ext4_msg(sb, KERN_ERR, "Journal does not support " "requested data journaling mode"); goto failed_mount_wq; } default: break; } set_task_ioprio(sbi->s_journal->j_task, journal_ioprio); no_journal: if (test_opt(sb, NOBH)) { if (!(test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_WRITEBACK_DATA)) { ext4_msg(sb, KERN_WARNING, "Ignoring nobh option - " "its supported only with writeback mode"); clear_opt(sbi->s_mount_opt, NOBH); } if (test_opt(sb, DIOREAD_NOLOCK)) { ext4_msg(sb, KERN_WARNING, "dioread_nolock option is " "not supported with nobh mode"); goto failed_mount_wq; } } EXT4_SB(sb)->dio_unwritten_wq = create_workqueue("ext4-dio-unwritten"); if (!EXT4_SB(sb)->dio_unwritten_wq) { printk(KERN_ERR "EXT4-fs: failed to create DIO workqueue\n"); goto failed_mount_wq; } /* * The jbd2_journal_load will have done any necessary log recovery, * so we can safely mount the rest of the filesystem now. */ root = ext4_iget(sb, EXT4_ROOT_INO); if (IS_ERR(root)) { ext4_msg(sb, KERN_ERR, "get root inode failed"); ret = PTR_ERR(root); goto failed_mount4; } if (!S_ISDIR(root->i_mode) || !root->i_blocks || !root->i_size) { iput(root); ext4_msg(sb, KERN_ERR, "corrupt root inode, run e2fsck"); goto failed_mount4; } sb->s_root = d_alloc_root(root); if (!sb->s_root) { ext4_msg(sb, KERN_ERR, "get root dentry failed"); iput(root); ret = -ENOMEM; goto failed_mount4; } ext4_setup_super(sb, es, sb->s_flags & MS_RDONLY); /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, "required extra inode space not" "available"); } if (test_opt(sb, DELALLOC) && (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA)) { ext4_msg(sb, KERN_WARNING, "Ignoring delalloc option - " "requested data journaling mode"); clear_opt(sbi->s_mount_opt, DELALLOC); } if (test_opt(sb, DIOREAD_NOLOCK)) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) { ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock " "option - requested data journaling mode"); clear_opt(sbi->s_mount_opt, DIOREAD_NOLOCK); } if (sb->s_blocksize < PAGE_SIZE) { ext4_msg(sb, KERN_WARNING, "Ignoring dioread_nolock " "option - block size is too small"); clear_opt(sbi->s_mount_opt, DIOREAD_NOLOCK); } } err = ext4_setup_system_zone(sb); if (err) { ext4_msg(sb, KERN_ERR, "failed to initialize system " "zone (%d)\n", err); goto failed_mount4; } ext4_ext_init(sb); err = ext4_mb_init(sb, needs_recovery); if (err) { ext4_msg(sb, KERN_ERR, "failed to initalize mballoc (%d)", err); goto failed_mount4; } sbi->s_kobj.kset = ext4_kset; init_completion(&sbi->s_kobj_unregister); err = kobject_init_and_add(&sbi->s_kobj, &ext4_ktype, NULL, "%s", sb->s_id); if (err) { ext4_mb_release(sb); ext4_ext_release(sb); goto failed_mount4; }; EXT4_SB(sb)->s_mount_state |= EXT4_ORPHAN_FS; ext4_orphan_cleanup(sb, es); EXT4_SB(sb)->s_mount_state &= ~EXT4_ORPHAN_FS; if (needs_recovery) { ext4_msg(sb, KERN_INFO, "recovery complete"); ext4_mark_recovery_complete(sb, es); } if (EXT4_SB(sb)->s_journal) { if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA) descr = " journalled data mode"; else if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_ORDERED_DATA) descr = " ordered data mode"; else descr = " writeback data mode"; } else descr = "out journal"; ext4_msg(sb, KERN_INFO, "mounted filesystem with%s", descr); lock_kernel(); return 0; cantfind_ext4: if (!silent) ext4_msg(sb, KERN_ERR, "VFS: Can't find ext4 filesystem"); goto failed_mount; failed_mount4: ext4_msg(sb, KERN_ERR, "mount failed"); destroy_workqueue(EXT4_SB(sb)->dio_unwritten_wq); failed_mount_wq: ext4_release_system_zone(sb); if (sbi->s_journal) { jbd2_journal_destroy(sbi->s_journal); sbi->s_journal = NULL; } failed_mount3: if (sbi->s_flex_groups) { if (is_vmalloc_addr(sbi->s_flex_groups)) vfree(sbi->s_flex_groups); else kfree(sbi->s_flex_groups); } percpu_counter_destroy(&sbi->s_freeblocks_counter); percpu_counter_destroy(&sbi->s_freeinodes_counter); percpu_counter_destroy(&sbi->s_dirs_counter); percpu_counter_destroy(&sbi->s_dirtyblocks_counter); failed_mount2: for (i = 0; i < db_count; i++) brelse(sbi->s_group_desc[i]); kfree(sbi->s_group_desc); failed_mount: if (sbi->s_proc) { remove_proc_entry(sb->s_id, ext4_proc_root); } #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif ext4_blkdev_remove(sbi); brelse(bh); out_fail: sb->s_fs_info = NULL; kfree(sbi->s_blockgroup_lock); kfree(sbi); lock_kernel(); return ret; }
167,553
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define GetBit(a,i) (((a) >> (i)) & 1L) Image *image; int byte; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; ssize_t y; unsigned char bit, info, depth; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ info=(unsigned char) ReadBlobByte(image); if (GetBit(info,4) == 0) { image->columns=(size_t) ReadBlobByte(image); image->rows=(size_t) ReadBlobByte(image); } else { image->columns=(size_t) ReadBlobMSBShort(image); image->rows=(size_t) ReadBlobMSBShort(image); } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); depth=(unsigned char) ReadBlobByte(image); if (depth != 1) ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported"); if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) { byte=ReadBlobByte(image); if (byte == EOF) ThrowReaderException(CorruptImageError,"CorruptImage"); } SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 0x00 : 0x01); bit++; if (bit == 8) bit=0; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define GetBit(a,i) (((a) >> (i)) & 1L) Image *image; int byte; MagickBooleanType status; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; ssize_t y; unsigned char bit, info, depth; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Initialize image structure. */ info=(unsigned char) ReadBlobByte(image); if (GetBit(info,4) == 0) { image->columns=(size_t) ReadBlobByte(image); image->rows=(size_t) ReadBlobByte(image); } else { image->columns=(size_t) ReadBlobMSBShort(image); image->rows=(size_t) ReadBlobMSBShort(image); } if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); depth=(unsigned char) ReadBlobByte(image); if (depth != 1) ThrowReaderException(CoderError,"OnlyLevelZerofilesSupported"); if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Convert bi-level image to pixel packets. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) { byte=ReadBlobByte(image); if (byte == EOF) ThrowReaderException(CorruptImageError,"CorruptImage"); } SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? 0x00 : 0x01); bit++; if (bit == 8) bit=0; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; transliterator_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Add a few more confusable map entries 1. Map Malaylam U+0D1F to 's'. 2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase letters. The characters in new confusable map entries are replaced by their Latin "look-alike" characters before the skeleton is calculated to compare with top domain names. Bug: 784761,773930 Test: components_unittests --gtest_filter=*IDNToUni* Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee Reviewed-on: https://chromium-review.googlesource.com/805214 Reviewed-by: Peter Kasting <[email protected]> Commit-Queue: Jungshik Shin <[email protected]> Cr-Commit-Position: refs/heads/master@{#521648} CWE ID: CWE-20
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); // removal; NFC". UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); // Supplement the Unicode confusable list by the following mapping. // - U+04CF (ӏ) => l // - {U+043A (к), U+0138(ĸ), U+03BA(κ)} => k // - U+043F(п) => n // - {U+0185 (ƅ), U+044C (ь)} => b // - U+0432 (в) => b // - U+043C (м) => m // - U+043D (н) => h // - U+0442 (т) => t // - {U+0448 (ш), U+0449 (щ)} => w // - U+0D1F (ട) => s extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString( "ӏ > l; [кĸκ] > k; п > n; [ƅь] > b; в > b; м > m; н > h; " "т > t; [шщ] > w; ട > s;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
172,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Track::Info::Copy(Info& dst) const { if (&dst == this) return 0; dst.type = type; dst.number = number; dst.defaultDuration = defaultDuration; dst.codecDelay = codecDelay; dst.seekPreRoll = seekPreRoll; dst.uid = uid; dst.lacing = lacing; dst.settings = settings; if (int status = CopyStr(&Info::nameAsUTF8, dst)) return status; if (int status = CopyStr(&Info::language, dst)) return status; if (int status = CopyStr(&Info::codecId, dst)) return status; if (int status = CopyStr(&Info::codecNameAsUTF8, dst)) return status; if (codecPrivateSize > 0) { if (codecPrivate == NULL) return -1; if (dst.codecPrivate) return -1; if (dst.codecPrivateSize != 0) return -1; dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize]; if (dst.codecPrivate == NULL) return -1; memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize); dst.codecPrivateSize = codecPrivateSize; } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
int Track::Info::Copy(Info& dst) const { if (&dst == this) return 0; dst.type = type; dst.number = number; dst.defaultDuration = defaultDuration; dst.codecDelay = codecDelay; dst.seekPreRoll = seekPreRoll; dst.uid = uid; dst.lacing = lacing; dst.settings = settings; if (int status = CopyStr(&Info::nameAsUTF8, dst)) return status; if (int status = CopyStr(&Info::language, dst)) return status; if (int status = CopyStr(&Info::codecId, dst)) return status; if (int status = CopyStr(&Info::codecNameAsUTF8, dst)) return status; if (codecPrivateSize > 0) { if (codecPrivate == NULL) return -1; if (dst.codecPrivate) return -1; if (dst.codecPrivateSize != 0) return -1; dst.codecPrivate = SafeArrayAlloc<unsigned char>(1, codecPrivateSize); if (dst.codecPrivate == NULL) return -1; memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize); dst.codecPrivateSize = codecPrivateSize; } return 0; }
173,802
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps) { mutex_lock(&kvm->arch.vpit->pit_state.lock); memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state)); kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; } Commit Message: KVM: x86: Reload pit counters for all channels when restoring state Currently if userspace restores the pit counters with a count of 0 on channels 1 or 2 and the guest attempts to read the count on those channels, then KVM will perform a mod of 0 and crash. This will ensure that 0 values are converted to 65536 as per the spec. This is CVE-2015-7513. Signed-off-by: Andy Honig <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID:
static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps) { int i; mutex_lock(&kvm->arch.vpit->pit_state.lock); memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state)); for (i = 0; i < 3; i++) kvm_pit_load_count(kvm, i, ps->channels[i].count, 0); mutex_unlock(&kvm->arch.vpit->pit_state.lock); return 0; }
167,560
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::HasBlockEntries( const Segment* pSegment, long long off, // relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); // relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; // absolute if ((total >= 0) && (pos >= total)) return 0; // we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; // interpreted later to mean "unknown size" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id != 0x0F43B675) // weird: not cluster ID return -1; // generic error pos += len; // consume Cluster ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); if (size == 0) return 0; // cluster does not have entries pos += len; // consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) return 0; // cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; // no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id == 0x0F43B675) // Cluster ID return 0; // no entries found if (id == 0x0C53BB6B) // Cues ID return 0; // no entries found pos += len; // consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; // not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) // BlockGroup ID return 1; // have at least one entry if (id == 0x23) // SimpleBlock ID return 1; // have at least one entry pos += size; // consume payload assert((cluster_stop < 0) || (pos <= cluster_stop)); } } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Cluster::HasBlockEntries( const Segment* pSegment, long long off, // relative to start of segment payload long long& pos, long& len) { assert(pSegment); assert(off >= 0); // relative to segment IMkvReader* const pReader = pSegment->m_pReader; long long total, avail; long status = pReader->Length(&total, &avail); if (status < 0) // error return status; assert((total < 0) || (avail <= total)); pos = pSegment->m_start + off; // absolute if ((total >= 0) && (pos >= total)) return 0; // we don't even have a complete cluster const long long segment_stop = (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; long long cluster_stop = -1; // interpreted later to mean "unknown size" { if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id != 0x0F43B675) // weird: not cluster ID return -1; // generic error pos += len; // consume Cluster ID field if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // weird return E_BUFFER_NOT_FULL; if ((segment_stop >= 0) && ((pos + len) > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + len) > total)) return 0; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); if (size == 0) return 0; // cluster does not have entries pos += len; // consume size field const long long unknown_size = (1LL << (7 * len)) - 1; if (size != unknown_size) { cluster_stop = pos + size; assert(cluster_stop >= 0); if ((segment_stop >= 0) && (cluster_stop > segment_stop)) return E_FILE_FORMAT_INVALID; if ((total >= 0) && (cluster_stop > total)) return 0; // cluster does not have any entries } } for (;;) { if ((cluster_stop >= 0) && (pos >= cluster_stop)) return 0; // no entries detected if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // need more data return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return static_cast<long>(id); if (id == 0x0F43B675) // Cluster ID return 0; // no entries found if (id == 0x0C53BB6B) // Cues ID return 0; // no entries found pos += len; // consume id field if ((cluster_stop >= 0) && (pos >= cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + 1) > avail) { len = 1; return E_BUFFER_NOT_FULL; } result = GetUIntLength(pReader, pos, len); if (result < 0) // error return static_cast<long>(result); if (result > 0) // underflow return E_BUFFER_NOT_FULL; if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) return E_FILE_FORMAT_INVALID; if ((pos + len) > avail) return E_BUFFER_NOT_FULL; const long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return static_cast<long>(size); pos += len; // consume size field if ((cluster_stop >= 0) && (pos > cluster_stop)) return E_FILE_FORMAT_INVALID; if (size == 0) // weird continue; const long long unknown_size = (1LL << (7 * len)) - 1; if (size == unknown_size) return E_FILE_FORMAT_INVALID; // not supported inside cluster if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) return E_FILE_FORMAT_INVALID; if (id == 0x20) // BlockGroup ID return 1; // have at least one entry if (id == 0x23) // SimpleBlock ID return 1; // have at least one entry pos += size; // consume payload if (cluster_stop >= 0 && pos > cluster_stop) return E_FILE_FORMAT_INVALID; } }
173,826
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int iscsi_decode_text_input( u8 phase, u8 sender, char *textbuf, u32 length, struct iscsi_conn *conn) { struct iscsi_param_list *param_list = conn->param_list; char *tmpbuf, *start = NULL, *end = NULL; tmpbuf = kzalloc(length + 1, GFP_KERNEL); if (!tmpbuf) { pr_err("Unable to allocate memory for tmpbuf.\n"); return -1; } memcpy(tmpbuf, textbuf, length); tmpbuf[length] = '\0'; start = tmpbuf; end = (start + length); while (start < end) { char *key, *value; struct iscsi_param *param; if (iscsi_extract_key_value(start, &key, &value) < 0) { kfree(tmpbuf); return -1; } pr_debug("Got key: %s=%s\n", key, value); if (phase & PHASE_SECURITY) { if (iscsi_check_for_auth_key(key) > 0) { char *tmpptr = key + strlen(key); *tmpptr = '='; kfree(tmpbuf); return 1; } } param = iscsi_check_key(key, phase, sender, param_list); if (!param) { if (iscsi_add_notunderstood_response(key, value, param_list) < 0) { kfree(tmpbuf); return -1; } start += strlen(key) + strlen(value) + 2; continue; } if (iscsi_check_value(param, value) < 0) { kfree(tmpbuf); return -1; } start += strlen(key) + strlen(value) + 2; if (IS_PSTATE_PROPOSER(param)) { if (iscsi_check_proposer_state(param, value) < 0) { kfree(tmpbuf); return -1; } SET_PSTATE_RESPONSE_GOT(param); } else { if (iscsi_check_acceptor_state(param, value, conn) < 0) { kfree(tmpbuf); return -1; } SET_PSTATE_ACCEPTOR(param); } } kfree(tmpbuf); return 0; } Commit Message: iscsi-target: fix heap buffer overflow on error If a key was larger than 64 bytes, as checked by iscsi_check_key(), the error response packet, generated by iscsi_add_notunderstood_response(), would still attempt to copy the entire key into the packet, overflowing the structure on the heap. Remote preauthentication kernel memory corruption was possible if a target was configured and listening on the network. CVE-2013-2850 Signed-off-by: Kees Cook <[email protected]> Cc: [email protected] Signed-off-by: Nicholas Bellinger <[email protected]> CWE ID: CWE-119
int iscsi_decode_text_input( u8 phase, u8 sender, char *textbuf, u32 length, struct iscsi_conn *conn) { struct iscsi_param_list *param_list = conn->param_list; char *tmpbuf, *start = NULL, *end = NULL; tmpbuf = kzalloc(length + 1, GFP_KERNEL); if (!tmpbuf) { pr_err("Unable to allocate memory for tmpbuf.\n"); return -1; } memcpy(tmpbuf, textbuf, length); tmpbuf[length] = '\0'; start = tmpbuf; end = (start + length); while (start < end) { char *key, *value; struct iscsi_param *param; if (iscsi_extract_key_value(start, &key, &value) < 0) { kfree(tmpbuf); return -1; } pr_debug("Got key: %s=%s\n", key, value); if (phase & PHASE_SECURITY) { if (iscsi_check_for_auth_key(key) > 0) { kfree(tmpbuf); return 1; } } param = iscsi_check_key(key, phase, sender, param_list); if (!param) { if (iscsi_add_notunderstood_response(key, value, param_list) < 0) { kfree(tmpbuf); return -1; } start += strlen(key) + strlen(value) + 2; continue; } if (iscsi_check_value(param, value) < 0) { kfree(tmpbuf); return -1; } start += strlen(key) + strlen(value) + 2; if (IS_PSTATE_PROPOSER(param)) { if (iscsi_check_proposer_state(param, value) < 0) { kfree(tmpbuf); return -1; } SET_PSTATE_RESPONSE_GOT(param); } else { if (iscsi_check_acceptor_state(param, value, conn) < 0) { kfree(tmpbuf); return -1; } SET_PSTATE_ACCEPTOR(param); } } kfree(tmpbuf); return 0; }
166,051