instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void test_show_object(struct object *object, struct strbuf *path, const char *last, void *data) { struct bitmap_test_data *tdata = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) die("Object not in bitmap: %s\n", oid_to_hex(&object->oid)); bitmap_set(tdata->base, bitmap_pos); display_progress(tdata->prg, ++tdata->seen); } Commit Message: list-objects: pass full pathname to callbacks When we find a blob at "a/b/c", we currently pass this to our show_object_fn callbacks as two components: "a/b/" and "c". Callbacks which want the full value then call path_name(), which concatenates the two. But this is an inefficient interface; the path is a strbuf, and we could simply append "c" to it temporarily, then roll back the length, without creating a new copy. So we could improve this by teaching the callsites of path_name() this trick (and there are only 3). But we can also notice that no callback actually cares about the broken-down representation, and simply pass each callback the full path "a/b/c" as a string. The callback code becomes even simpler, then, as we do not have to worry about freeing an allocated buffer, nor rolling back our modification to the strbuf. This is theoretically less efficient, as some callbacks would not bother to format the final path component. But in practice this is not measurable. Since we use the same strbuf over and over, our work to grow it is amortized, and we really only pay to memcpy a few bytes. Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]> CWE ID: CWE-119
static void test_show_object(struct object *object, static void test_show_object(struct object *object, const char *name, void *data) { struct bitmap_test_data *tdata = data; int bitmap_pos; bitmap_pos = bitmap_position(object->oid.hash); if (bitmap_pos < 0) die("Object not in bitmap: %s\n", oid_to_hex(&object->oid)); bitmap_set(tdata->base, bitmap_pos); display_progress(tdata->prg, ++tdata->seen); }
167,423
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SerializerMarkupAccumulator::appendElement(StringBuilder& result, Element* element, Namespaces* namespaces) { if (!shouldIgnoreElement(element)) MarkupAccumulator::appendElement(result, element, namespaces); result.appendLiteral("<meta charset=\""); result.append(m_document->charset()); if (m_document->isXHTMLDocument()) result.appendLiteral("\" />"); else result.appendLiteral("\">"); } } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void SerializerMarkupAccumulator::appendElement(StringBuilder& result, Element* element, Namespaces* namespaces) void SerializerMarkupAccumulator::appendElement(StringBuilder& out, Element* element, Namespaces* namespaces) { if (!shouldIgnoreElement(element)) MarkupAccumulator::appendElement(out, element, namespaces); out.append("<meta charset=\""); out.append(m_document->charset()); out.append("\">"); } }
171,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) { mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { PixelInfo mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetPixelInfo(image,&mean_pixel); GetPixelInfoPixel(image,p,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; PixelInfo sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetPixelInfo(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelInfo pixel; status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.alpha+=pixel.alpha; count++; } } } } gamma=1.0/count; mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.alpha=gamma*sum_pixel.alpha; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); p+=GetPixelChannels(image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1552 CWE ID: CWE-369
MagickExport Image *MeanShiftImage(const Image *image,const size_t width, const size_t height,const double color_distance,ExceptionInfo *exception) { #define MaxMeanShiftIterations 100 #define MeanShiftImageTag "MeanShift/Image" CacheView *image_view, *mean_view, *pixel_view; Image *mean_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) { mean_image=DestroyImage(mean_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); pixel_view=AcquireVirtualCacheView(image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status,progress) \ magick_number_threads(mean_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { PixelInfo mean_pixel, previous_pixel; PointInfo mean_location, previous_location; register ssize_t i; GetPixelInfo(image,&mean_pixel); GetPixelInfoPixel(image,p,&mean_pixel); mean_location.x=(double) x; mean_location.y=(double) y; for (i=0; i < MaxMeanShiftIterations; i++) { double distance, gamma; PixelInfo sum_pixel; PointInfo sum_location; ssize_t count, v; sum_location.x=0.0; sum_location.y=0.0; GetPixelInfo(image,&sum_pixel); previous_location=mean_location; previous_pixel=mean_pixel; count=0; for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) { ssize_t u; for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) { if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) { PixelInfo pixel; status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) MagickRound(mean_location.x+u),(ssize_t) MagickRound( mean_location.y+v),&pixel,exception); distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); if (distance <= (color_distance*color_distance)) { sum_location.x+=mean_location.x+u; sum_location.y+=mean_location.y+v; sum_pixel.red+=pixel.red; sum_pixel.green+=pixel.green; sum_pixel.blue+=pixel.blue; sum_pixel.alpha+=pixel.alpha; count++; } } } } gamma=PerceptibleReciprocal(count); mean_location.x=gamma*sum_location.x; mean_location.y=gamma*sum_location.y; mean_pixel.red=gamma*sum_pixel.red; mean_pixel.green=gamma*sum_pixel.green; mean_pixel.blue=gamma*sum_pixel.blue; mean_pixel.alpha=gamma*sum_pixel.alpha; distance=(mean_location.x-previous_location.x)* (mean_location.x-previous_location.x)+ (mean_location.y-previous_location.y)* (mean_location.y-previous_location.y)+ 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); if (distance <= 3.0) break; } SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); p+=GetPixelChannels(image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } mean_view=DestroyCacheView(mean_view); pixel_view=DestroyCacheView(pixel_view); image_view=DestroyCacheView(image_view); return(mean_image); }
170,189
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SchedulerObject::_continue(std::string key, std::string &/*reason*/, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true); return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::_continue(std::string key, std::string &/*reason*/, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true); return true; }
164,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CSSDefaultStyleSheets::loadFullDefaultStyle() { if (simpleDefaultStyleSheet) { ASSERT(defaultStyle); ASSERT(defaultPrintStyle == defaultStyle); delete defaultStyle; simpleDefaultStyleSheet->deref(); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = RuleSet::create().leakPtr(); simpleDefaultStyleSheet = 0; } else { ASSERT(!defaultStyle); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = RuleSet::create().leakPtr(); defaultQuirksStyle = RuleSet::create().leakPtr(); } String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet(); defaultStyleSheet = parseUASheet(defaultRules); defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval()); defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval()); defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval()); String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet(); quirksStyleSheet = parseUASheet(quirksRules); defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval()); } Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun. We've been bitten by the Simple Default Stylesheet being out of sync with the real html.css twice this week. The Simple Default Stylesheet was invented years ago for Mac: http://trac.webkit.org/changeset/36135 It nicely handles the case where you just want to create a single WebView and parse some simple HTML either without styling said HTML, or only to display a small string, etc. Note that this optimization/complexity *only* helps for the very first document, since the default stylesheets are all static (process-global) variables. Since any real page on the internet uses a tag not covered by the simple default stylesheet, not real load benefits from this optimization. Only uses of WebView which were just rendering small bits of text might have benefited from this. about:blank would also have used this sheet. This was a common application for some uses of WebView back in those days. These days, even with WebView on Android, there are likely much larger overheads than parsing the html.css stylesheet, so making it required seems like the right tradeoff of code-simplicity for this case. BUG=319556 Review URL: https://codereview.chromium.org/73723005 git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void CSSDefaultStyleSheets::loadFullDefaultStyle() void CSSDefaultStyleSheets::loadDefaultStyle() { ASSERT(!defaultStyle); defaultStyle = RuleSet::create().leakPtr(); defaultPrintStyle = RuleSet::create().leakPtr(); defaultQuirksStyle = RuleSet::create().leakPtr(); String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet(); defaultStyleSheet = parseUASheet(defaultRules); defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval()); defaultStyle->addRulesFromSheet(parseUASheet(ViewportStyle::viewportStyleSheet()), screenEval()); defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval()); String quirksRules = String(quirksUserAgentStyleSheet, sizeof(quirksUserAgentStyleSheet)) + RenderTheme::theme().extraQuirksStyleSheet(); quirksStyleSheet = parseUASheet(quirksRules); defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval()); }
171,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mkvparser::IMkvReader::~IMkvReader() { //// Disable MSVC warnings that suggest making code non-portable. } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
mkvparser::IMkvReader::~IMkvReader() #ifdef _MSC_VER //// Disable MSVC warnings that suggest making code non-portable. #pragma warning(disable : 4996) #endif mkvparser::IMkvReader::~IMkvReader() {} void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) { major = 1; minor = 0; build = 0; revision = 28; }
174,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( const PrintHostMsg_DidPreviewDocument_Params& params) { StopWorker(params.document_cookie); if (params.expected_pages_count <= 0) { NOTREACHED(); return; } PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); if (!data_bytes || !data_bytes->size()) return; print_preview_ui->SetPrintPreviewDataForIndex(COMPLETE_PREVIEW_DOCUMENT_INDEX, std::move(data_bytes)); print_preview_ui->OnPreviewDataIsAvailable( params.expected_pages_count, params.preview_request_id); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
void PrintPreviewMessageHandler::OnMetafileReadyForPrinting( const PrintHostMsg_DidPreviewDocument_Params& params) { StopWorker(params.document_cookie); if (params.expected_pages_count <= 0) { NOTREACHED(); return; } PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; if (IsOopifEnabled() && print_preview_ui->source_is_modifiable()) { auto* client = PrintCompositeClient::FromWebContents(web_contents()); DCHECK(client); client->DoComposite( params.metafile_data_handle, params.data_size, base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfDocumentDone, weak_ptr_factory_.GetWeakPtr(), params.expected_pages_count, params.preview_request_id)); } else { NotifyUIPreviewDocumentReady( params.expected_pages_count, params.preview_request_id, GetDataFromHandle(params.metafile_data_handle, params.data_size)); } }
171,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool get_build_id( Backtrace* backtrace, uintptr_t base_addr, uint8_t* e_ident, std::string* build_id) { HdrType hdr; memcpy(&hdr.e_ident[0], e_ident, EI_NIDENT); if (backtrace->Read(base_addr + EI_NIDENT, reinterpret_cast<uint8_t*>(&hdr) + EI_NIDENT, sizeof(HdrType) - EI_NIDENT) != sizeof(HdrType) - EI_NIDENT) { return false; } for (size_t i = 0; i < hdr.e_phnum; i++) { PhdrType phdr; if (backtrace->Read(base_addr + hdr.e_phoff + i * hdr.e_phentsize, reinterpret_cast<uint8_t*>(&phdr), sizeof(phdr)) != sizeof(phdr)) { return false; } if (phdr.p_type == PT_NOTE) { size_t hdr_size = phdr.p_filesz; uintptr_t addr = base_addr + phdr.p_offset; while (hdr_size >= sizeof(NhdrType)) { NhdrType nhdr; if (backtrace->Read(addr, reinterpret_cast<uint8_t*>(&nhdr), sizeof(nhdr)) != sizeof(nhdr)) { return false; } addr += sizeof(nhdr); if (nhdr.n_type == NT_GNU_BUILD_ID) { addr += NOTE_ALIGN(nhdr.n_namesz); uint8_t build_id_data[128]; if (nhdr.n_namesz > sizeof(build_id_data)) { ALOGE("Possible corrupted note, name size value is too large: %u", nhdr.n_namesz); return false; } if (backtrace->Read(addr, build_id_data, nhdr.n_descsz) != nhdr.n_descsz) { return false; } build_id->clear(); for (size_t bytes = 0; bytes < nhdr.n_descsz; bytes++) { *build_id += android::base::StringPrintf("%02x", build_id_data[bytes]); } return true; } else { hdr_size -= sizeof(nhdr); size_t skip_bytes = NOTE_ALIGN(nhdr.n_namesz) + NOTE_ALIGN(nhdr.n_descsz); addr += skip_bytes; if (hdr_size < skip_bytes) { break; } hdr_size -= skip_bytes; } } } } return false; } Commit Message: Fix incorrect check of descsz value. Bug: 25187394 (cherry picked from commit 1fa55234d6773e09e3bb934419b5b6cc0df981c9) Change-Id: Idbc9071e8b2b25a062c4e94118808d6e19d443d9 CWE ID: CWE-264
static bool get_build_id( Backtrace* backtrace, uintptr_t base_addr, uint8_t* e_ident, std::string* build_id) { HdrType hdr; memcpy(&hdr.e_ident[0], e_ident, EI_NIDENT); if (backtrace->Read(base_addr + EI_NIDENT, reinterpret_cast<uint8_t*>(&hdr) + EI_NIDENT, sizeof(HdrType) - EI_NIDENT) != sizeof(HdrType) - EI_NIDENT) { return false; } for (size_t i = 0; i < hdr.e_phnum; i++) { PhdrType phdr; if (backtrace->Read(base_addr + hdr.e_phoff + i * hdr.e_phentsize, reinterpret_cast<uint8_t*>(&phdr), sizeof(phdr)) != sizeof(phdr)) { return false; } if (phdr.p_type == PT_NOTE) { size_t hdr_size = phdr.p_filesz; uintptr_t addr = base_addr + phdr.p_offset; while (hdr_size >= sizeof(NhdrType)) { NhdrType nhdr; if (backtrace->Read(addr, reinterpret_cast<uint8_t*>(&nhdr), sizeof(nhdr)) != sizeof(nhdr)) { return false; } addr += sizeof(nhdr); if (nhdr.n_type == NT_GNU_BUILD_ID) { addr += NOTE_ALIGN(nhdr.n_namesz); uint8_t build_id_data[160]; if (nhdr.n_descsz > sizeof(build_id_data)) { ALOGE("Possible corrupted note, desc size value is too large: %u", nhdr.n_descsz); return false; } if (backtrace->Read(addr, build_id_data, nhdr.n_descsz) != nhdr.n_descsz) { return false; } build_id->clear(); for (size_t bytes = 0; bytes < nhdr.n_descsz; bytes++) { *build_id += android::base::StringPrintf("%02x", build_id_data[bytes]); } return true; } else { hdr_size -= sizeof(nhdr); size_t skip_bytes = NOTE_ALIGN(nhdr.n_namesz) + NOTE_ALIGN(nhdr.n_descsz); addr += skip_bytes; if (hdr_size < skip_bytes) { break; } hdr_size -= skip_bytes; } } } } return false; }
173,968
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { return snprintf(dest, destlen, "%s.hcache", path); } Commit Message: sanitise cache paths Co-authored-by: JerikoOne <[email protected]> CWE ID: CWE-22
static int nntp_hcache_namer(const char *path, char *dest, size_t destlen) { int count = snprintf(dest, destlen, "%s.hcache", path); /* Strip out any directories in the path */ char *first = strchr(dest, '/'); char *last = strrchr(dest, '/'); if (first && last && (last > first)) { memmove(first, last, strlen(last) + 1); count -= (last - first); } return count; }
169,119
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void command_port_read_callback(struct urb *urb) { struct usb_serial_port *command_port = urb->context; struct whiteheat_command_private *command_info; int status = urb->status; unsigned char *data = urb->transfer_buffer; int result; command_info = usb_get_serial_port_data(command_port); if (!command_info) { dev_dbg(&urb->dev->dev, "%s - command_info is NULL, exiting.\n", __func__); return; } if (status) { dev_dbg(&urb->dev->dev, "%s - nonzero urb status: %d\n", __func__, status); if (status != -ENOENT) command_info->command_finished = WHITEHEAT_CMD_FAILURE; wake_up(&command_info->wait_command); return; } usb_serial_debug_data(&command_port->dev, __func__, urb->actual_length, data); if (data[0] == WHITEHEAT_CMD_COMPLETE) { command_info->command_finished = WHITEHEAT_CMD_COMPLETE; wake_up(&command_info->wait_command); } else if (data[0] == WHITEHEAT_CMD_FAILURE) { command_info->command_finished = WHITEHEAT_CMD_FAILURE; wake_up(&command_info->wait_command); } else if (data[0] == WHITEHEAT_EVENT) { /* These are unsolicited reports from the firmware, hence no waiting command to wakeup */ dev_dbg(&urb->dev->dev, "%s - event received\n", __func__); } else if (data[0] == WHITEHEAT_GET_DTR_RTS) { memcpy(command_info->result_buffer, &data[1], urb->actual_length - 1); command_info->command_finished = WHITEHEAT_CMD_COMPLETE; wake_up(&command_info->wait_command); } else dev_dbg(&urb->dev->dev, "%s - bad reply from firmware\n", __func__); /* Continue trying to always read */ result = usb_submit_urb(command_port->read_urb, GFP_ATOMIC); if (result) dev_dbg(&urb->dev->dev, "%s - failed resubmitting read urb, error %d\n", __func__, result); } Commit Message: USB: whiteheat: Added bounds checking for bulk command response This patch fixes a potential security issue in the whiteheat USB driver which might allow a local attacker to cause kernel memory corrpution. This is due to an unchecked memcpy into a fixed size buffer (of 64 bytes). On EHCI and XHCI busses it's possible to craft responses greater than 64 bytes leading a buffer overflow. Signed-off-by: James Forshaw <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
static void command_port_read_callback(struct urb *urb) { struct usb_serial_port *command_port = urb->context; struct whiteheat_command_private *command_info; int status = urb->status; unsigned char *data = urb->transfer_buffer; int result; command_info = usb_get_serial_port_data(command_port); if (!command_info) { dev_dbg(&urb->dev->dev, "%s - command_info is NULL, exiting.\n", __func__); return; } if (!urb->actual_length) { dev_dbg(&urb->dev->dev, "%s - empty response, exiting.\n", __func__); return; } if (status) { dev_dbg(&urb->dev->dev, "%s - nonzero urb status: %d\n", __func__, status); if (status != -ENOENT) command_info->command_finished = WHITEHEAT_CMD_FAILURE; wake_up(&command_info->wait_command); return; } usb_serial_debug_data(&command_port->dev, __func__, urb->actual_length, data); if (data[0] == WHITEHEAT_CMD_COMPLETE) { command_info->command_finished = WHITEHEAT_CMD_COMPLETE; wake_up(&command_info->wait_command); } else if (data[0] == WHITEHEAT_CMD_FAILURE) { command_info->command_finished = WHITEHEAT_CMD_FAILURE; wake_up(&command_info->wait_command); } else if (data[0] == WHITEHEAT_EVENT) { /* These are unsolicited reports from the firmware, hence no waiting command to wakeup */ dev_dbg(&urb->dev->dev, "%s - event received\n", __func__); } else if ((data[0] == WHITEHEAT_GET_DTR_RTS) && (urb->actual_length - 1 <= sizeof(command_info->result_buffer))) { memcpy(command_info->result_buffer, &data[1], urb->actual_length - 1); command_info->command_finished = WHITEHEAT_CMD_COMPLETE; wake_up(&command_info->wait_command); } else dev_dbg(&urb->dev->dev, "%s - bad reply from firmware\n", __func__); /* Continue trying to always read */ result = usb_submit_urb(command_port->read_urb, GFP_ATOMIC); if (result) dev_dbg(&urb->dev->dev, "%s - failed resubmitting read urb, error %d\n", __func__, result); }
166,369
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: flatpak_proxy_client_init (FlatpakProxyClient *client) { init_side (client, &client->client_side); init_side (client, &client->bus_side); client->auth_end_offset = AUTH_END_INIT_OFFSET; client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref); client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free); client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); } Commit Message: Fix vulnerability in dbus proxy During the authentication all client data is directly forwarded to the dbus daemon as is, until we detect the BEGIN command after which we start filtering the binary dbus protocol. Unfortunately the detection of the BEGIN command in the proxy did not exactly match the detection in the dbus daemon. A BEGIN followed by a space or tab was considered ok in the daemon but not by the proxy. This could be exploited to send arbitrary dbus messages to the host, which can be used to break out of the sandbox. This was noticed by Gabriel Campana of The Google Security Team. This fix makes the detection of the authentication phase end match the dbus code. In addition we duplicate the authentication line validation from dbus, which includes ensuring all data is ASCII, and limiting the size of a line to 16k. In fact, we add some extra stringent checks, disallowing ASCII control chars and requiring that auth lines start with a capital letter. CWE ID: CWE-436
flatpak_proxy_client_init (FlatpakProxyClient *client) { init_side (client, &client->client_side); init_side (client, &client->bus_side); client->auth_buffer = g_byte_array_new (); client->rewrite_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref); client->get_owner_reply = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_free); client->unique_id_policy = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL); }
169,342
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XFixesFetchRegionAndBounds (Display *dpy, XserverRegion region, int *nrectanglesRet, XRectangle *bounds) { XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy); xXFixesFetchRegionReq *req; xXFixesFetchRegionReply rep; XRectangle *rects; int nrects; long nbytes; long nread; XFixesCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (XFixesFetchRegion, req); req->reqType = info->codes->major_opcode; req->xfixesReqType = X_XFixesFetchRegion; req->region = region; *nrectanglesRet = 0; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; } bounds->x = rep.x; bounds->y = rep.y; bounds->y = rep.y; bounds->width = rep.width; bounds->height = rep.height; nbytes = (long) rep.length << 2; nrects = rep.length >> 1; rects = Xmalloc (nrects * sizeof (XRectangle)); if (!rects) { _XEatDataWords(dpy, rep.length); _XEatData (dpy, (unsigned long) (nbytes - nread)); } UnlockDisplay (dpy); SyncHandle(); *nrectanglesRet = nrects; return rects; } Commit Message: CWE ID: CWE-190
XFixesFetchRegionAndBounds (Display *dpy, XserverRegion region, int *nrectanglesRet, XRectangle *bounds) { XFixesExtDisplayInfo *info = XFixesFindDisplay (dpy); xXFixesFetchRegionReq *req; xXFixesFetchRegionReply rep; XRectangle *rects; int nrects; long nbytes; long nread; XFixesCheckExtension (dpy, info, NULL); LockDisplay (dpy); GetReq (XFixesFetchRegion, req); req->reqType = info->codes->major_opcode; req->xfixesReqType = X_XFixesFetchRegion; req->region = region; *nrectanglesRet = 0; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return NULL; } bounds->x = rep.x; bounds->y = rep.y; bounds->y = rep.y; bounds->width = rep.width; bounds->height = rep.height; if (rep.length < (INT_MAX >> 2)) { nbytes = (long) rep.length << 2; nrects = rep.length >> 1; rects = Xmalloc (nrects * sizeof (XRectangle)); } else { nbytes = 0; nrects = 0; rects = NULL; } if (!rects) { _XEatDataWords(dpy, rep.length); _XEatData (dpy, (unsigned long) (nbytes - nread)); } UnlockDisplay (dpy); SyncHandle(); *nrectanglesRet = nrects; return rects; }
164,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2) { pdf_xref_entry *table; pdf_xref_entry *table; int i, n; if (i0 < 0 || i1 < 0 || i0 > INT_MAX - i1) fz_throw(ctx, FZ_ERROR_GENERIC, "negative xref stream entry index"); table = pdf_xref_find_subsection(ctx, doc, i0, i1); for (i = i0; i < i0 + i1; i++) for (i = i0; i < i0 + i1; i++) { pdf_xref_entry *entry = &table[i-i0]; int a = 0; int64_t b = 0; int c = 0; if (fz_is_eof(ctx, stm)) fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream"); for (n = 0; n < w0; n++) a = (a << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w1; n++) b = (b << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w2; n++) c = (c << 8) + fz_read_byte(ctx, stm); if (!entry->type) { int t = w0 ? a : 1; entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0; entry->ofs = w1 ? b : 0; entry->gen = w2 ? c : 0; entry->num = i; } } doc->has_xref_streams = 1; } Commit Message: CWE ID: CWE-119
pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, int64_t i0, int i1, int w0, int w1, int w2) { pdf_xref_entry *table; pdf_xref_entry *table; int i, n; if (i0 < 0 || i0 > PDF_MAX_OBJECT_NUMBER || i1 < 0 || i1 > PDF_MAX_OBJECT_NUMBER || i0 + i1 - 1 > PDF_MAX_OBJECT_NUMBER) fz_throw(ctx, FZ_ERROR_GENERIC, "xref subsection object numbers are out of range"); table = pdf_xref_find_subsection(ctx, doc, i0, i1); for (i = i0; i < i0 + i1; i++) for (i = i0; i < i0 + i1; i++) { pdf_xref_entry *entry = &table[i-i0]; int a = 0; int64_t b = 0; int c = 0; if (fz_is_eof(ctx, stm)) fz_throw(ctx, FZ_ERROR_GENERIC, "truncated xref stream"); for (n = 0; n < w0; n++) a = (a << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w1; n++) b = (b << 8) + fz_read_byte(ctx, stm); for (n = 0; n < w2; n++) c = (c << 8) + fz_read_byte(ctx, stm); if (!entry->type) { int t = w0 ? a : 1; entry->type = t == 0 ? 'f' : t == 1 ? 'n' : t == 2 ? 'o' : 0; entry->ofs = w1 ? b : 0; entry->gen = w2 ? c : 0; entry->num = i; } } doc->has_xref_streams = 1; }
165,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FT_Bitmap_Embolden( FT_Library library, FT_Bitmap* bitmap, FT_Pos xStrength, FT_Pos yStrength ) { FT_Error error; unsigned char* p; FT_Int i, x, y, pitch; FT_Int xstr, ystr; return FT_THROW( Invalid_Library_Handle ); if ( !bitmap || !bitmap->buffer ) return FT_THROW( Invalid_Argument ); if ( ( ( FT_PIX_ROUND( xStrength ) >> 6 ) > FT_INT_MAX ) || ( ( FT_PIX_ROUND( yStrength ) >> 6 ) > FT_INT_MAX ) ) return FT_THROW( Invalid_Argument ); xstr = (FT_Int)FT_PIX_ROUND( xStrength ) >> 6; ystr = (FT_Int)FT_PIX_ROUND( yStrength ) >> 6; if ( xstr == 0 && ystr == 0 ) return FT_Err_Ok; else if ( xstr < 0 || ystr < 0 ) return FT_THROW( Invalid_Argument ); switch ( bitmap->pixel_mode ) { case FT_PIXEL_MODE_GRAY2: case FT_PIXEL_MODE_GRAY4: { FT_Bitmap tmp; /* convert to 8bpp */ FT_Bitmap_New( &tmp ); error = FT_Bitmap_Convert( library, bitmap, &tmp, 1 ); if ( error ) return error; FT_Bitmap_Done( library, bitmap ); *bitmap = tmp; } break; case FT_PIXEL_MODE_MONO: if ( xstr > 8 ) xstr = 8; break; case FT_PIXEL_MODE_LCD: xstr *= 3; break; case FT_PIXEL_MODE_LCD_V: ystr *= 3; break; case FT_PIXEL_MODE_BGRA: /* We don't embolden color glyphs. */ return FT_Err_Ok; } error = ft_bitmap_assure_buffer( library->memory, bitmap, xstr, ystr ); if ( error ) return error; /* take care of bitmap flow */ pitch = bitmap->pitch; if ( pitch > 0 ) p = bitmap->buffer + pitch * ystr; else { pitch = -pitch; p = bitmap->buffer + pitch * ( bitmap->rows - 1 ); } /* for each row */ for ( y = 0; y < bitmap->rows ; y++ ) { /* * Horizontally: * * From the last pixel on, make each pixel or'ed with the * `xstr' pixels before it. */ for ( x = pitch - 1; x >= 0; x-- ) { unsigned char tmp; tmp = p[x]; for ( i = 1; i <= xstr; i++ ) { if ( bitmap->pixel_mode == FT_PIXEL_MODE_MONO ) { p[x] |= tmp >> i; /* the maximum value of 8 for `xstr' comes from here */ if ( x > 0 ) p[x] |= p[x - 1] << ( 8 - i ); #if 0 if ( p[x] == 0xff ) break; #endif } else { if ( x - i >= 0 ) { if ( p[x] + p[x - i] > bitmap->num_grays - 1 ) { p[x] = (unsigned char)( bitmap->num_grays - 1 ); break; } else { p[x] = (unsigned char)( p[x] + p[x - i] ); if ( p[x] == bitmap->num_grays - 1 ) break; } } else break; } } } /* * Vertically: * * Make the above `ystr' rows or'ed with it. */ for ( x = 1; x <= ystr; x++ ) { unsigned char* q; q = p - bitmap->pitch * x; for ( i = 0; i < pitch; i++ ) q[i] |= p[i]; } p += bitmap->pitch; } bitmap->width += xstr; bitmap->rows += ystr; return FT_Err_Ok; } Commit Message: CWE ID: CWE-119
FT_Bitmap_Embolden( FT_Library library, FT_Bitmap* bitmap, FT_Pos xStrength, FT_Pos yStrength ) { FT_Error error; unsigned char* p; FT_Int i, x, pitch; FT_UInt y; FT_Int xstr, ystr; return FT_THROW( Invalid_Library_Handle ); if ( !bitmap || !bitmap->buffer ) return FT_THROW( Invalid_Argument ); if ( ( ( FT_PIX_ROUND( xStrength ) >> 6 ) > FT_INT_MAX ) || ( ( FT_PIX_ROUND( yStrength ) >> 6 ) > FT_INT_MAX ) ) return FT_THROW( Invalid_Argument ); xstr = (FT_Int)FT_PIX_ROUND( xStrength ) >> 6; ystr = (FT_Int)FT_PIX_ROUND( yStrength ) >> 6; if ( xstr == 0 && ystr == 0 ) return FT_Err_Ok; else if ( xstr < 0 || ystr < 0 ) return FT_THROW( Invalid_Argument ); switch ( bitmap->pixel_mode ) { case FT_PIXEL_MODE_GRAY2: case FT_PIXEL_MODE_GRAY4: { FT_Bitmap tmp; /* convert to 8bpp */ FT_Bitmap_New( &tmp ); error = FT_Bitmap_Convert( library, bitmap, &tmp, 1 ); if ( error ) return error; FT_Bitmap_Done( library, bitmap ); *bitmap = tmp; } break; case FT_PIXEL_MODE_MONO: if ( xstr > 8 ) xstr = 8; break; case FT_PIXEL_MODE_LCD: xstr *= 3; break; case FT_PIXEL_MODE_LCD_V: ystr *= 3; break; case FT_PIXEL_MODE_BGRA: /* We don't embolden color glyphs. */ return FT_Err_Ok; } error = ft_bitmap_assure_buffer( library->memory, bitmap, xstr, ystr ); if ( error ) return error; /* take care of bitmap flow */ pitch = bitmap->pitch; if ( pitch > 0 ) p = bitmap->buffer + pitch * ystr; else { pitch = -pitch; p = bitmap->buffer + pitch * ( bitmap->rows - 1 ); } /* for each row */ for ( y = 0; y < bitmap->rows ; y++ ) { /* * Horizontally: * * From the last pixel on, make each pixel or'ed with the * `xstr' pixels before it. */ for ( x = pitch - 1; x >= 0; x-- ) { unsigned char tmp; tmp = p[x]; for ( i = 1; i <= xstr; i++ ) { if ( bitmap->pixel_mode == FT_PIXEL_MODE_MONO ) { p[x] |= tmp >> i; /* the maximum value of 8 for `xstr' comes from here */ if ( x > 0 ) p[x] |= p[x - 1] << ( 8 - i ); #if 0 if ( p[x] == 0xff ) break; #endif } else { if ( x - i >= 0 ) { if ( p[x] + p[x - i] > bitmap->num_grays - 1 ) { p[x] = (unsigned char)( bitmap->num_grays - 1 ); break; } else { p[x] = (unsigned char)( p[x] + p[x - i] ); if ( p[x] == bitmap->num_grays - 1 ) break; } } else break; } } } /* * Vertically: * * Make the above `ystr' rows or'ed with it. */ for ( x = 1; x <= ystr; x++ ) { unsigned char* q; q = p - bitmap->pitch * x; for ( i = 0; i < pitch; i++ ) q[i] |= p[i]; } p += bitmap->pitch; } bitmap->width += xstr; bitmap->rows += ystr; return FT_Err_Ok; }
164,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = splitbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int m; int hstartcol; /* Get a buffer. */ if (bufsize > QMFB_SPLITBUFSIZE) { if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide in this case. */ abort(); } } if (numrows >= 2) { hstartcol = (numrows + 1 - parity) >> 1; m = numrows - hstartcol; /* Save the samples destined for the highpass channel. */ n = m; dstptr = buf; srcptr = &a[(1 - parity) * stride]; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += JPC_QMFB_COLGRPSIZE; srcptr += stride << 1; } /* Copy the appropriate samples into the lowpass channel. */ dstptr = &a[(1 - parity) * stride]; srcptr = &a[(2 - parity) * stride]; n = numrows - m - (!parity); while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += stride << 1; } /* Copy the saved samples into the highpass channel. */ dstptr = &a[hstartcol * stride]; srcptr = buf; n = m; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += JPC_QMFB_COLGRPSIZE; } } /* If the split buffer was allocated on the heap, free this memory. */ if (buf != splitbuf) { jas_free(buf); } } Commit Message: Fixed a buffer overrun problem in the QMFB code in the JPC codec that was caused by a buffer being allocated with a size that was too small in some cases. Added a new regression test case. CWE ID: CWE-119
void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) { int bufsize = JPC_CEILDIVPOW2(numrows, 1); jpc_fix_t splitbuf[QMFB_SPLITBUFSIZE * JPC_QMFB_COLGRPSIZE]; jpc_fix_t *buf = splitbuf; jpc_fix_t *srcptr; jpc_fix_t *dstptr; register jpc_fix_t *srcptr2; register jpc_fix_t *dstptr2; register int n; register int i; int m; int hstartrow; /* Get a buffer. */ if (bufsize > QMFB_SPLITBUFSIZE) { if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) { /* We have no choice but to commit suicide in this case. */ abort(); } } if (numrows >= 2) { hstartrow = (numrows + 1 - parity) >> 1; // ORIGINAL (WRONG): m = (parity) ? hstartrow : (numrows - hstartrow); m = numrows - hstartrow; /* Save the samples destined for the highpass channel. */ n = m; dstptr = buf; srcptr = &a[(1 - parity) * stride]; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += JPC_QMFB_COLGRPSIZE; srcptr += stride << 1; } /* Copy the appropriate samples into the lowpass channel. */ dstptr = &a[(1 - parity) * stride]; srcptr = &a[(2 - parity) * stride]; n = numrows - m - (!parity); while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += stride << 1; } /* Copy the saved samples into the highpass channel. */ dstptr = &a[hstartrow * stride]; srcptr = buf; n = m; while (n-- > 0) { dstptr2 = dstptr; srcptr2 = srcptr; for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { *dstptr2 = *srcptr2; ++dstptr2; ++srcptr2; } dstptr += stride; srcptr += JPC_QMFB_COLGRPSIZE; } } /* If the split buffer was allocated on the heap, free this memory. */ if (buf != splitbuf) { jas_free(buf); } }
169,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_tp_trap(struct pt_regs *regs, unsigned int instr) { int reg = (instr >> 12) & 15; if (reg == 15) return 1; regs->uregs[reg] = current_thread_info()->tp_value; regs->ARM_pc += 4; return 0; } Commit Message: ARM: 7735/2: Preserve the user r/w register TPIDRURW on context switch and fork Since commit 6a1c53124aa1 the user writeable TLS register was zeroed to prevent it from being used as a covert channel between two tasks. There are more and more applications coming to Windows RT, Wine could support them, but mostly they expect to have the thread environment block (TEB) in TPIDRURW. This patch preserves that register per thread instead of clearing it. Unlike the TPIDRURO, which is already switched, the TPIDRURW can be updated from userspace so needs careful treatment in the case that we modify TPIDRURW and call fork(). To avoid this we must always read TPIDRURW in copy_thread. Signed-off-by: André Hentschel <[email protected]> Signed-off-by: Will Deacon <[email protected]> Signed-off-by: Jonathan Austin <[email protected]> Signed-off-by: Russell King <[email protected]> CWE ID: CWE-264
static int get_tp_trap(struct pt_regs *regs, unsigned int instr) { int reg = (instr >> 12) & 15; if (reg == 15) return 1; regs->uregs[reg] = current_thread_info()->tp_value[0]; regs->ARM_pc += 4; return 0; }
167,582
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len, compat_ulong_t, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, flags) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; nodemask_t bm; nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(nodes_addr(bm), nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, nodes_addr(bm), alloc_size); } if (err) return -EFAULT; return sys_mbind(start, len, mode, nm, nr_bits+1, flags); } Commit Message: mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-388
COMPAT_SYSCALL_DEFINE6(mbind, compat_ulong_t, start, compat_ulong_t, len, compat_ulong_t, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode, compat_ulong_t, flags) { unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; nodemask_t bm; nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { if (compat_get_bitmap(nodes_addr(bm), nmask, nr_bits)) return -EFAULT; nm = compat_alloc_user_space(alloc_size); if (copy_to_user(nm, nodes_addr(bm), alloc_size)) return -EFAULT; } return sys_mbind(start, len, mode, nm, nr_bits+1, flags); }
168,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev1_cr_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CR))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CR))); return NULL; }
167,790
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams( int version, size_t start, size_t end, const std::string& selection, const std::string& content, const std::string& base_page_url, const std::string& encoding, int now_on_tap_version) : version(version), start(start), end(end), selection(selection), content(content), base_page_url(base_page_url), encoding(encoding), now_on_tap_version(now_on_tap_version) {} Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID:
TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams( int version, size_t start, size_t end, const std::string& selection, const std::string& content, const std::string& base_page_url, const std::string& encoding, int contextual_cards_version) : version(version), start(start), end(end), selection(selection), content(content), base_page_url(base_page_url), encoding(encoding),
171,647
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p, const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile) { /* i_ctx_p is NULL running arg (@) files. * lib_path and mem are never NULL */ bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file; bool search_with_no_combine = false; bool search_with_combine = false; char fmode[2] = { 'r', 0}; gx_io_device *iodev = iodev_default(mem); gs_main_instance *minst = get_minst_from_memory(mem); int code; /* when starting arg files (@ files) iodev_default is not yet set */ if (iodev == 0) iodev = (gx_io_device *)gx_io_device_table[0]; search_with_combine = false; } else { search_with_no_combine = starting_arg_file; search_with_combine = true; } Commit Message: CWE ID: CWE-200
lib_file_open(gs_file_path_ptr lib_path, const gs_memory_t *mem, i_ctx_t *i_ctx_p, const char *fname, uint flen, char *buffer, int blen, uint *pclen, ref *pfile) { /* i_ctx_p is NULL running arg (@) files. * lib_path and mem are never NULL */ bool starting_arg_file = (i_ctx_p == NULL) ? true : i_ctx_p->starting_arg_file; bool search_with_no_combine = false; bool search_with_combine = false; char fmode[2] = { 'r', 0}; gx_io_device *iodev = iodev_default(mem); gs_main_instance *minst = get_minst_from_memory(mem); int code; if (i_ctx_p && starting_arg_file) i_ctx_p->starting_arg_file = false; /* when starting arg files (@ files) iodev_default is not yet set */ if (iodev == 0) iodev = (gx_io_device *)gx_io_device_table[0]; search_with_combine = false; } else { search_with_no_combine = starting_arg_file; search_with_combine = true; }
165,264
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void printResources() { printf("Printing resources (%zu resources in total)\n", m_resources.size()); for (size_t i = 0; i < m_resources.size(); ++i) { printf("%zu. '%s', '%s'\n", i, m_resources[i].url.string().utf8().data(), m_resources[i].mimeType.utf8().data()); } } Commit Message: Revert 162155 "This review merges the two existing page serializ..." Change r162155 broke the world even though it was landed using the CQ. > This review merges the two existing page serializers, WebPageSerializerImpl and > PageSerializer, into one, PageSerializer. In addition to this it moves all > the old tests from WebPageNewSerializerTest and WebPageSerializerTest to the > PageSerializerTest structure and splits out one test for MHTML into a new > MHTMLTest file. > > Saving as 'Webpage, Complete', 'Webpage, HTML Only' and as MHTML when the > 'Save Page as MHTML' flag is enabled now uses the same code, and should thus > have the same feature set. Meaning that both modes now should be a bit better. > > Detailed list of changes: > > - PageSerializerTest: Prepare for more DTD test > - PageSerializerTest: Remove now unneccesary input image test > - PageSerializerTest: Remove unused WebPageSerializer/Impl code > - PageSerializerTest: Move data URI morph test > - PageSerializerTest: Move data URI test > - PageSerializerTest: Move namespace test > - PageSerializerTest: Move SVG Image test > - MHTMLTest: Move MHTML specific test to own test file > - PageSerializerTest: Delete duplicate XML header test > - PageSerializerTest: Move blank frame test > - PageSerializerTest: Move CSS test > - PageSerializerTest: Add frameset/frame test > - PageSerializerTest: Move old iframe test > - PageSerializerTest: Move old elements test > - Use PageSerizer for saving web pages > - PageSerializerTest: Test for rewriting links > - PageSerializer: Add rewrite link accumulator > - PageSerializer: Serialize images in iframes/frames src > - PageSerializer: XHTML fix for meta tags > - PageSerializer: Add presentation CSS > - PageSerializer: Rename out parameter > > BUG= > [email protected] > > Review URL: https://codereview.chromium.org/68613003 [email protected] Review URL: https://codereview.chromium.org/73673003 git-svn-id: svn://svn.chromium.org/blink/trunk@162156 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
void printResources()
171,572
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags) { struct mem_cgroup *memcg; struct page *page; spinlock_t *ptl; pte_t entry; pte_unmap(page_table); /* Check if we need to add a guard page to the stack */ if (check_stack_guard_page(vma, address) < 0) return VM_FAULT_SIGSEGV; /* Use the zero-page for reads */ if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm)) { entry = pte_mkspecial(pfn_pte(my_zero_pfn(address), vma->vm_page_prot)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto unlock; goto setpte; } /* Allocate our own private page. */ if (unlikely(anon_vma_prepare(vma))) goto oom; page = alloc_zeroed_user_highpage_movable(vma, address); if (!page) goto oom; if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) goto oom_free_page; /* * The memory barrier inside __SetPageUptodate makes sure that * preceeding stores to the page contents become visible before * the set_pte_at() write. */ __SetPageUptodate(page); entry = mk_pte(page, vma->vm_page_prot); if (vma->vm_flags & VM_WRITE) entry = pte_mkwrite(pte_mkdirty(entry)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto release; inc_mm_counter_fast(mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); mem_cgroup_commit_charge(page, memcg, false); lru_cache_add_active_or_unevictable(page, vma); setpte: set_pte_at(mm, address, page_table, entry); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); return 0; release: mem_cgroup_cancel_charge(page, memcg); page_cache_release(page); goto unlock; oom_free_page: page_cache_release(page); oom: return VM_FAULT_OOM; } Commit Message: mm: avoid setting up anonymous pages into file mapping Reading page fault handler code I've noticed that under right circumstances kernel would map anonymous pages into file mappings: if the VMA doesn't have vm_ops->fault() and the VMA wasn't fully populated on ->mmap(), kernel would handle page fault to not populated pte with do_anonymous_page(). Let's change page fault handler to use do_anonymous_page() only on anonymous VMA (->vm_ops == NULL) and make sure that the VMA is not shared. For file mappings without vm_ops->fault() or shred VMA without vm_ops, page fault on pte_none() entry would lead to SIGBUS. Signed-off-by: Kirill A. Shutemov <[email protected]> Acked-by: Oleg Nesterov <[email protected]> Cc: Andrew Morton <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-20
static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, pte_t *page_table, pmd_t *pmd, unsigned int flags) { struct mem_cgroup *memcg; struct page *page; spinlock_t *ptl; pte_t entry; pte_unmap(page_table); /* File mapping without ->vm_ops ? */ if (vma->vm_flags & VM_SHARED) return VM_FAULT_SIGBUS; /* Check if we need to add a guard page to the stack */ if (check_stack_guard_page(vma, address) < 0) return VM_FAULT_SIGSEGV; /* Use the zero-page for reads */ if (!(flags & FAULT_FLAG_WRITE) && !mm_forbids_zeropage(mm)) { entry = pte_mkspecial(pfn_pte(my_zero_pfn(address), vma->vm_page_prot)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto unlock; goto setpte; } /* Allocate our own private page. */ if (unlikely(anon_vma_prepare(vma))) goto oom; page = alloc_zeroed_user_highpage_movable(vma, address); if (!page) goto oom; if (mem_cgroup_try_charge(page, mm, GFP_KERNEL, &memcg)) goto oom_free_page; /* * The memory barrier inside __SetPageUptodate makes sure that * preceeding stores to the page contents become visible before * the set_pte_at() write. */ __SetPageUptodate(page); entry = mk_pte(page, vma->vm_page_prot); if (vma->vm_flags & VM_WRITE) entry = pte_mkwrite(pte_mkdirty(entry)); page_table = pte_offset_map_lock(mm, pmd, address, &ptl); if (!pte_none(*page_table)) goto release; inc_mm_counter_fast(mm, MM_ANONPAGES); page_add_new_anon_rmap(page, vma, address); mem_cgroup_commit_charge(page, memcg, false); lru_cache_add_active_or_unevictable(page, vma); setpte: set_pte_at(mm, address, page_table, entry); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, address, page_table); unlock: pte_unmap_unlock(page_table, ptl); return 0; release: mem_cgroup_cancel_charge(page, memcg); page_cache_release(page); goto unlock; oom_free_page: page_cache_release(page); oom: return VM_FAULT_OOM; }
167,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void *hashtable_get(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash % num_buckets(hashtable)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return pair->value; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
void *hashtable_get(hashtable_t *hashtable, const char *key) { pair_t *pair; size_t hash; bucket_t *bucket; hash = hash_str(key); bucket = &hashtable->buckets[hash & hashmask(hashtable->order)]; pair = hashtable_find_pair(hashtable, bucket, key, hash); if(!pair) return NULL; return pair->value; }
166,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: do_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax) { #ifdef USE_AMD64_ASM return _gcry_aes_amd64_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT); #elif defined(USE_ARM_ASM) return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT); #else return do_encrypt_fn (ctx, bx, ax); #endif /* !USE_ARM_ASM && !USE_AMD64_ASM*/ } Commit Message: AES: move look-up tables to .data section and unshare between processes * cipher/rijndael-internal.h (ATTR_ALIGNED_64): New. * cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure. (enc_tables): New structure for encryption table with counters before and after. (encT): New macro. (dec_tables): Add counters before and after encryption table; Move from .rodata to .data section. (do_encrypt): Change 'encT' to 'enc_tables.T'. (do_decrypt): Change '&dec_tables' to 'dec_tables.T'. * cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input with length not multiple of 256. (prefetch_enc, prefetch_dec): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna <[email protected]> CWE ID: CWE-310
do_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax) { #ifdef USE_AMD64_ASM return _gcry_aes_amd64_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, enc_tables.T); #elif defined(USE_ARM_ASM) return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, enc_tables.T); #else return do_encrypt_fn (ctx, bx, ax); #endif /* !USE_ARM_ASM && !USE_AMD64_ASM*/ }
170,212
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Element* siblingWithAriaRole(String role, Node* node) { Node* parent = node->parentNode(); if (!parent) return 0; for (Element* sibling = ElementTraversal::firstChild(*parent); sibling; sibling = ElementTraversal::nextSibling(*sibling)) { const AtomicString& siblingAriaRole = AccessibleNode::getProperty(sibling, AOMStringProperty::kRole); if (equalIgnoringCase(siblingAriaRole, role)) return sibling; } return 0; } 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
static Element* siblingWithAriaRole(String role, Node* node) { Node* parent = node->parentNode(); if (!parent) return 0; for (Element* sibling = ElementTraversal::firstChild(*parent); sibling; sibling = ElementTraversal::nextSibling(*sibling)) { const AtomicString& siblingAriaRole = AccessibleNode::getProperty(sibling, AOMStringProperty::kRole); if (equalIgnoringASCIICase(siblingAriaRole, role)) return sibling; } return 0; }
171,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MediaInterfaceProxy::GetMediaInterfaceFactory() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); if (!interface_factory_ptr_) ConnectToService(); DCHECK(interface_factory_ptr_); return interface_factory_ptr_.get(); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
MediaInterfaceProxy::GetMediaInterfaceFactory() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); if (!interface_factory_ptr_) ConnectToMediaService(); DCHECK(interface_factory_ptr_); return interface_factory_ptr_.get(); }
171,937
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseStartTag(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *attname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int nbatts = 0; int maxatts = ctxt->maxatts; int i; if (RAW != '<') return(NULL); NEXT1; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStartTag: invalid element name\n"); return(NULL); } /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; while ((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; attname = xmlParseAttribute(ctxt, &attvalue); if ((attname != NULL) && (attvalue != NULL)) { /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. */ for (i = 0; i < nbatts;i += 2) { if (xmlStrEqual(atts[i], attname)) { xmlErrAttributeDup(ctxt, NULL, attname); xmlFree(attvalue); goto failed; } } /* * Add the pair to atts */ if (atts == NULL) { maxatts = 22; /* allow for 10 attrs by default */ atts = (const xmlChar **) xmlMalloc(maxatts * sizeof(xmlChar *)); if (atts == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } ctxt->atts = atts; ctxt->maxatts = maxatts; } else if (nbatts + 4 > maxatts) { const xmlChar **n; maxatts *= 2; n = (const xmlChar **) xmlRealloc((void *) atts, maxatts * sizeof(const xmlChar *)); if (n == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } atts = n; ctxt->atts = atts; ctxt->maxatts = maxatts; } atts[nbatts++] = attname; atts[nbatts++] = attvalue; atts[nbatts] = NULL; atts[nbatts + 1] = NULL; } else { if (attvalue != NULL) xmlFree(attvalue); } failed: GROW if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } SHRINK; GROW; } /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) && (!ctxt->disableSAX)) { if (nbatts > 0) ctxt->sax->startElement(ctxt->userData, name, atts); else ctxt->sax->startElement(ctxt->userData, name, NULL); } if (atts != NULL) { /* Free only the content strings */ for (i = 1;i < nbatts;i+=2) if (atts[i] != NULL) xmlFree((xmlChar *) atts[i]); } return(name); } 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
xmlParseStartTag(xmlParserCtxtPtr ctxt) { const xmlChar *name; const xmlChar *attname; xmlChar *attvalue; const xmlChar **atts = ctxt->atts; int nbatts = 0; int maxatts = ctxt->maxatts; int i; if (RAW != '<') return(NULL); NEXT1; name = xmlParseName(ctxt); if (name == NULL) { xmlFatalErrMsg(ctxt, XML_ERR_NAME_REQUIRED, "xmlParseStartTag: invalid element name\n"); return(NULL); } /* * Now parse the attributes, it ends up with the ending * * (S Attribute)* S? */ SKIP_BLANKS; GROW; while (((RAW != '>') && ((RAW != '/') || (NXT(1) != '>')) && (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { const xmlChar *q = CUR_PTR; unsigned int cons = ctxt->input->consumed; attname = xmlParseAttribute(ctxt, &attvalue); if ((attname != NULL) && (attvalue != NULL)) { /* * [ WFC: Unique Att Spec ] * No attribute name may appear more than once in the same * start-tag or empty-element tag. */ for (i = 0; i < nbatts;i += 2) { if (xmlStrEqual(atts[i], attname)) { xmlErrAttributeDup(ctxt, NULL, attname); xmlFree(attvalue); goto failed; } } /* * Add the pair to atts */ if (atts == NULL) { maxatts = 22; /* allow for 10 attrs by default */ atts = (const xmlChar **) xmlMalloc(maxatts * sizeof(xmlChar *)); if (atts == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } ctxt->atts = atts; ctxt->maxatts = maxatts; } else if (nbatts + 4 > maxatts) { const xmlChar **n; maxatts *= 2; n = (const xmlChar **) xmlRealloc((void *) atts, maxatts * sizeof(const xmlChar *)); if (n == NULL) { xmlErrMemory(ctxt, NULL); if (attvalue != NULL) xmlFree(attvalue); goto failed; } atts = n; ctxt->atts = atts; ctxt->maxatts = maxatts; } atts[nbatts++] = attname; atts[nbatts++] = attvalue; atts[nbatts] = NULL; atts[nbatts + 1] = NULL; } else { if (attvalue != NULL) xmlFree(attvalue); } failed: GROW if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) break; if (!IS_BLANK_CH(RAW)) { xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, "attributes construct error\n"); } SKIP_BLANKS; if ((cons == ctxt->input->consumed) && (q == CUR_PTR) && (attname == NULL) && (attvalue == NULL)) { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "xmlParseStartTag: problem parsing attributes\n"); break; } SHRINK; GROW; } /* * SAX: Start of Element ! */ if ((ctxt->sax != NULL) && (ctxt->sax->startElement != NULL) && (!ctxt->disableSAX)) { if (nbatts > 0) ctxt->sax->startElement(ctxt->userData, name, atts); else ctxt->sax->startElement(ctxt->userData, name, NULL); } if (atts != NULL) { /* Free only the content strings */ for (i = 1;i < nbatts;i+=2) if (atts[i] != NULL) xmlFree((xmlChar *) atts[i]); } return(name); }
171,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AudioOutputDevice::ShutDownOnIOThread() { DCHECK(message_loop()->BelongsToCurrentThread()); if (stream_id_) { is_started_ = false; if (ipc_) { ipc_->CloseStream(stream_id_); ipc_->RemoveDelegate(stream_id_); } stream_id_ = 0; } base::AutoLock auto_lock_(audio_thread_lock_); if (!audio_thread_.get()) return; base::ThreadRestrictions::ScopedAllowIO allow_io; audio_thread_->Stop(NULL); audio_thread_.reset(); audio_callback_.reset(); } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void AudioOutputDevice::ShutDownOnIOThread() { DCHECK(message_loop()->BelongsToCurrentThread()); if (stream_id_) { is_started_ = false; if (ipc_) { ipc_->CloseStream(stream_id_); ipc_->RemoveDelegate(stream_id_); } stream_id_ = 0; } base::ThreadRestrictions::ScopedAllowIO allow_io; audio_thread_.Stop(NULL); audio_callback_.reset(); }
170,706
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GDataEntry* GDataDirectory::FromDocumentEntry( GDataDirectory* parent, DocumentEntry* doc, GDataDirectoryService* directory_service) { DCHECK(doc->is_folder()); GDataDirectory* dir = new GDataDirectory(parent, directory_service); dir->title_ = UTF16ToUTF8(doc->title()); dir->SetBaseNameFromTitle(); dir->file_info_.last_modified = doc->updated_time(); dir->file_info_.last_accessed = doc->updated_time(); dir->file_info_.creation_time = doc->published_time(); dir->resource_id_ = doc->resource_id(); dir->content_url_ = doc->content_url(); dir->deleted_ = doc->deleted(); const Link* edit_link = doc->GetLinkByType(Link::EDIT); DCHECK(edit_link) << "No edit link for dir " << dir->title_; if (edit_link) dir->edit_url_ = edit_link->href(); const Link* parent_link = doc->GetLinkByType(Link::PARENT); if (parent_link) dir->parent_resource_id_ = ExtractResourceId(parent_link->href()); const Link* upload_link = doc->GetLinkByType(Link::RESUMABLE_CREATE_MEDIA); if (upload_link) dir->upload_url_ = upload_link->href(); return dir; } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
GDataEntry* GDataDirectory::FromDocumentEntry( void GDataDirectory::InitFromDocumentEntry(DocumentEntry* doc) { GDataEntry::InitFromDocumentEntry(doc); const Link* upload_link = doc->GetLinkByType(Link::RESUMABLE_CREATE_MEDIA); if (upload_link) upload_url_ = upload_link->href(); }
171,486
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb) { struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp; struct sk_buff *opt_skb = NULL; /* Imagine: socket is IPv6. IPv4 packet arrives, goes to IPv4 receive handler and backlogged. From backlog it always goes here. Kerboom... Fortunately, tcp_rcv_established and rcv_established handle them correctly, but it is not case with tcp_v6_hnd_req and tcp_v6_send_reset(). --ANK */ if (skb->protocol == htons(ETH_P_IP)) return tcp_v4_do_rcv(sk, skb); if (sk_filter(sk, skb)) goto discard; /* * socket locking is here for SMP purposes as backlog rcv * is currently called with bh processing disabled. */ /* Do Stevens' IPV6_PKTOPTIONS. Yes, guys, it is the only place in our code, where we may make it not affecting IPv4. The rest of code is protocol independent, and I do not like idea to uglify IPv4. Actually, all the idea behind IPV6_PKTOPTIONS looks not very well thought. For now we latch options, received in the last packet, enqueued by tcp. Feel free to propose better solution. --ANK (980728) */ if (np->rxopt.all) opt_skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC)); if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */ struct dst_entry *dst = sk->sk_rx_dst; sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); if (dst) { if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif || dst->ops->check(dst, np->rx_dst_cookie) == NULL) { dst_release(dst); sk->sk_rx_dst = NULL; } } tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len); if (opt_skb) goto ipv6_pktoptions; return 0; } if (tcp_checksum_complete(skb)) goto csum_err; if (sk->sk_state == TCP_LISTEN) { struct sock *nsk = tcp_v6_cookie_check(sk, skb); if (!nsk) goto discard; if (nsk != sk) { sock_rps_save_rxhash(nsk, skb); sk_mark_napi_id(nsk, skb); if (tcp_child_process(sk, nsk, skb)) goto reset; if (opt_skb) __kfree_skb(opt_skb); return 0; } } else sock_rps_save_rxhash(sk, skb); if (tcp_rcv_state_process(sk, skb)) goto reset; if (opt_skb) goto ipv6_pktoptions; return 0; reset: tcp_v6_send_reset(sk, skb); discard: if (opt_skb) __kfree_skb(opt_skb); kfree_skb(skb); return 0; csum_err: TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); goto discard; ipv6_pktoptions: /* Do you ask, what is it? 1. skb was enqueued by tcp. 2. skb is added to tail of read queue, rather than out of order. 3. socket is not in passive state. 4. Finally, it really contains options, which user wants to receive. */ tp = tcp_sk(sk); if (TCP_SKB_CB(opt_skb)->end_seq == tp->rcv_nxt && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { if (np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo) np->mcast_oif = tcp_v6_iif(opt_skb); if (np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) np->mcast_hops = ipv6_hdr(opt_skb)->hop_limit; if (np->rxopt.bits.rxflow || np->rxopt.bits.rxtclass) np->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(opt_skb)); if (np->repflow) np->flow_label = ip6_flowlabel(ipv6_hdr(opt_skb)); if (ipv6_opt_accepted(sk, opt_skb, &TCP_SKB_CB(opt_skb)->header.h6)) { skb_set_owner_r(opt_skb, sk); tcp_v6_restore_cb(opt_skb); opt_skb = xchg(&np->pktoptions, opt_skb); } else { __kfree_skb(opt_skb); opt_skb = xchg(&np->pktoptions, NULL); } } kfree_skb(opt_skb); return 0; } Commit Message: tcp: take care of truncations done by sk_filter() With syzkaller help, Marco Grassi found a bug in TCP stack, crashing in tcp_collapse() Root cause is that sk_filter() can truncate the incoming skb, but TCP stack was not really expecting this to happen. It probably was expecting a simple DROP or ACCEPT behavior. We first need to make sure no part of TCP header could be removed. Then we need to adjust TCP_SKB_CB(skb)->end_seq Many thanks to syzkaller team and Marco for giving us a reproducer. Signed-off-by: Eric Dumazet <[email protected]> Reported-by: Marco Grassi <[email protected]> Reported-by: Vladis Dronov <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-284
static int tcp_v6_do_rcv(struct sock *sk, struct sk_buff *skb) { struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp; struct sk_buff *opt_skb = NULL; /* Imagine: socket is IPv6. IPv4 packet arrives, goes to IPv4 receive handler and backlogged. From backlog it always goes here. Kerboom... Fortunately, tcp_rcv_established and rcv_established handle them correctly, but it is not case with tcp_v6_hnd_req and tcp_v6_send_reset(). --ANK */ if (skb->protocol == htons(ETH_P_IP)) return tcp_v4_do_rcv(sk, skb); if (tcp_filter(sk, skb)) goto discard; /* * socket locking is here for SMP purposes as backlog rcv * is currently called with bh processing disabled. */ /* Do Stevens' IPV6_PKTOPTIONS. Yes, guys, it is the only place in our code, where we may make it not affecting IPv4. The rest of code is protocol independent, and I do not like idea to uglify IPv4. Actually, all the idea behind IPV6_PKTOPTIONS looks not very well thought. For now we latch options, received in the last packet, enqueued by tcp. Feel free to propose better solution. --ANK (980728) */ if (np->rxopt.all) opt_skb = skb_clone(skb, sk_gfp_mask(sk, GFP_ATOMIC)); if (sk->sk_state == TCP_ESTABLISHED) { /* Fast path */ struct dst_entry *dst = sk->sk_rx_dst; sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); if (dst) { if (inet_sk(sk)->rx_dst_ifindex != skb->skb_iif || dst->ops->check(dst, np->rx_dst_cookie) == NULL) { dst_release(dst); sk->sk_rx_dst = NULL; } } tcp_rcv_established(sk, skb, tcp_hdr(skb), skb->len); if (opt_skb) goto ipv6_pktoptions; return 0; } if (tcp_checksum_complete(skb)) goto csum_err; if (sk->sk_state == TCP_LISTEN) { struct sock *nsk = tcp_v6_cookie_check(sk, skb); if (!nsk) goto discard; if (nsk != sk) { sock_rps_save_rxhash(nsk, skb); sk_mark_napi_id(nsk, skb); if (tcp_child_process(sk, nsk, skb)) goto reset; if (opt_skb) __kfree_skb(opt_skb); return 0; } } else sock_rps_save_rxhash(sk, skb); if (tcp_rcv_state_process(sk, skb)) goto reset; if (opt_skb) goto ipv6_pktoptions; return 0; reset: tcp_v6_send_reset(sk, skb); discard: if (opt_skb) __kfree_skb(opt_skb); kfree_skb(skb); return 0; csum_err: TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); goto discard; ipv6_pktoptions: /* Do you ask, what is it? 1. skb was enqueued by tcp. 2. skb is added to tail of read queue, rather than out of order. 3. socket is not in passive state. 4. Finally, it really contains options, which user wants to receive. */ tp = tcp_sk(sk); if (TCP_SKB_CB(opt_skb)->end_seq == tp->rcv_nxt && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { if (np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo) np->mcast_oif = tcp_v6_iif(opt_skb); if (np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) np->mcast_hops = ipv6_hdr(opt_skb)->hop_limit; if (np->rxopt.bits.rxflow || np->rxopt.bits.rxtclass) np->rcv_flowinfo = ip6_flowinfo(ipv6_hdr(opt_skb)); if (np->repflow) np->flow_label = ip6_flowlabel(ipv6_hdr(opt_skb)); if (ipv6_opt_accepted(sk, opt_skb, &TCP_SKB_CB(opt_skb)->header.h6)) { skb_set_owner_r(opt_skb, sk); tcp_v6_restore_cb(opt_skb); opt_skb = xchg(&np->pktoptions, opt_skb); } else { __kfree_skb(opt_skb); opt_skb = xchg(&np->pktoptions, NULL); } } kfree_skb(opt_skb); return 0; }
166,914
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutofillManager::OnLoadedAutofillHeuristics( const std::string& heuristic_xml) { UploadRequired upload_required; FormStructure::ParseQueryResponse(heuristic_xml, form_structures_.get(), &upload_required, *metric_logger_); } Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses BUG=84693 TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest Review URL: http://codereview.chromium.org/6969090 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutofillManager::OnLoadedAutofillHeuristics( const std::string& heuristic_xml) { FormStructure::ParseQueryResponse(heuristic_xml, form_structures_.get(), *metric_logger_); }
170,447
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CrosLibrary::TestApi::SetSpeechSynthesisLibrary( SpeechSynthesisLibrary* library, bool own) { library_->speech_synthesis_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::SetSpeechSynthesisLibrary(
170,645
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GURL DecorateFrontendURL(const GURL& base_url) { std::string frontend_url = base_url.spec(); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&") + "dockSide=undocked"); // TODO(dgozman): remove this support in M38. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevToolsExperiments)) url_string += "&experiments=true"; if (command_line->HasSwitch(switches::kDevToolsFlags)) { std::string flags = command_line->GetSwitchValueASCII( switches::kDevToolsFlags); flags = net::EscapeQueryParamValue(flags, false); url_string += "&flags=" + flags; } #if defined(DEBUG_DEVTOOLS) url_string += "&debugFrontend=true"; #endif // defined(DEBUG_DEVTOOLS) return GURL(url_string); } Commit Message: [DevTools] Move sanitize url to devtools_ui.cc. Compatibility script is not reliable enough. BUG=653134 Review-Url: https://codereview.chromium.org/2403633002 Cr-Commit-Position: refs/heads/master@{#425814} CWE ID: CWE-200
GURL DecorateFrontendURL(const GURL& base_url) { std::string frontend_url = base_url.spec(); std::string url_string( frontend_url + ((frontend_url.find("?") == std::string::npos) ? "?" : "&") + "dockSide=undocked"); // TODO(dgozman): remove this support in M38. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kEnableDevToolsExperiments)) url_string += "&experiments=true"; if (command_line->HasSwitch(switches::kDevToolsFlags)) { url_string += "&" + command_line->GetSwitchValueASCII( switches::kDevToolsFlags); } #if defined(DEBUG_DEVTOOLS) url_string += "&debugFrontend=true"; #endif // defined(DEBUG_DEVTOOLS) return GURL(url_string); }
172,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SyncManager::MaybeSetSyncTabsInNigoriNode( ModelTypeSet enabled_types) { DCHECK(thread_checker_.CalledOnValidThread()); data_->MaybeSetSyncTabsInNigoriNode(enabled_types); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncManager::MaybeSetSyncTabsInNigoriNode(
170,794
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; int buffer_size = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; int nbchars = 0; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); } Commit Message: Pull entity fix from upstream. BUG=107128 Review URL: http://codereview.chromium.org/9072008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@116175 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, int what, xmlChar end, xmlChar end2, xmlChar end3) { xmlChar *buffer = NULL; int buffer_size = 0; xmlChar *current = NULL; xmlChar *rep = NULL; const xmlChar *last; xmlEntityPtr ent; int c,l; int nbchars = 0; if ((ctxt == NULL) || (str == NULL) || (len < 0)) return(NULL); last = str + len; if (((ctxt->depth > 40) && ((ctxt->options & XML_PARSE_HUGE) == 0)) || (ctxt->depth > 1024)) { xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); return(NULL); } /* * allocate a translation buffer. */ buffer_size = XML_PARSER_BIG_BUFFER_SIZE; buffer = (xmlChar *) xmlMallocAtomic(buffer_size * sizeof(xmlChar)); if (buffer == NULL) goto mem_error; /* * OK loop until we reach one of the ending char or a size limit. * we are operating on already parsed values. */ if (str < last) c = CUR_SCHAR(str, l); else c = 0; while ((c != 0) && (c != end) && /* non input consuming loop */ (c != end2) && (c != end3)) { if (c == 0) break; if ((c == '&') && (str[1] == '#')) { int val = xmlParseStringCharRef(ctxt, &str); if (val != 0) { COPY_BUF(0,buffer,nbchars,val); } if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding Entity Reference: %.30s\n", str); ent = xmlParseStringEntityRef(ctxt, &str); if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if ((ent != NULL) && (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { if (ent->content != NULL) { COPY_BUF(0,buffer,nbchars,ent->content[0]); if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } else { xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, "predefined entity has no content\n"); } } else if ((ent != NULL) && (ent->content != NULL)) { ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } else if (ent != NULL) { int i = xmlStrlen(ent->name); const xmlChar *cur = ent->name; buffer[nbchars++] = '&'; if (nbchars > buffer_size - i - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); } for (;i > 0;i--) buffer[nbchars++] = *cur++; buffer[nbchars++] = ';'; } } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "String decoding PE Reference: %.30s\n", str); ent = xmlParseStringPEReference(ctxt, &str); if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) goto int_error; if (ent != NULL) ctxt->nbentities += ent->checked; if (ent != NULL) { if (ent->content == NULL) { xmlLoadEntityContent(ctxt, ent); } ctxt->depth++; rep = xmlStringDecodeEntities(ctxt, ent->content, what, 0, 0, 0); ctxt->depth--; if (rep != NULL) { current = rep; while (*current != 0) { /* non input consuming loop */ buffer[nbchars++] = *current++; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { if (xmlParserEntityCheck(ctxt, nbchars, ent)) goto int_error; growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } xmlFree(rep); rep = NULL; } } } else { COPY_BUF(l,buffer,nbchars,c); str += l; if (nbchars > buffer_size - XML_PARSER_BUFFER_SIZE) { growBuffer(buffer, XML_PARSER_BUFFER_SIZE); } } if (str < last) c = CUR_SCHAR(str, l); else c = 0; } buffer[nbchars] = 0; return(buffer); mem_error: xmlErrMemory(ctxt, NULL); int_error: if (rep != NULL) xmlFree(rep); if (buffer != NULL) xmlFree(buffer); return(NULL); }
170,977
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: on_register_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gchar *cfg_desc, gpointer user_data) { struct tcmur_handler *handler; struct dbus_info *info; char *bus_name; bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s", subtype); handler = g_new0(struct tcmur_handler, 1); handler->subtype = g_strdup(subtype); handler->cfg_desc = g_strdup(cfg_desc); handler->open = dbus_handler_open; handler->close = dbus_handler_close; handler->handle_cmd = dbus_handler_handle_cmd; info = g_new0(struct dbus_info, 1); info->register_invocation = invocation; info->watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM, bus_name, G_BUS_NAME_WATCHER_FLAGS_NONE, on_handler_appeared, on_handler_vanished, handler, NULL); g_free(bus_name); handler->opaque = info; return TRUE; } Commit Message: only allow dynamic UnregisterHandler for external handlers, thereby fixing DoS Trying to unregister an internal handler ended up in a SEGFAULT, because the tcmur_handler->opaque was NULL. Way to reproduce: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:qcow we use a newly introduced boolean in struct tcmur_handler for keeping track of external handlers. As suggested by mikechristie adjusting the public data structure is acceptable. CWE ID: CWE-476
on_register_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gchar *cfg_desc, gpointer user_data) { struct tcmur_handler *handler; struct dbus_info *info; char *bus_name; bus_name = g_strdup_printf("org.kernel.TCMUService1.HandlerManager1.%s", subtype); handler = g_new0(struct tcmur_handler, 1); handler->subtype = g_strdup(subtype); handler->cfg_desc = g_strdup(cfg_desc); handler->open = dbus_handler_open; handler->close = dbus_handler_close; handler->handle_cmd = dbus_handler_handle_cmd; info = g_new0(struct dbus_info, 1); handler->opaque = info; handler->_is_dbus_handler = 1; info->register_invocation = invocation; info->watcher_id = g_bus_watch_name(G_BUS_TYPE_SYSTEM, bus_name, G_BUS_NAME_WATCHER_FLAGS_NONE, on_handler_appeared, on_handler_vanished, handler, NULL); g_free(bus_name); handler->opaque = info; return TRUE; }
167,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long VideoTrack::Parse( Segment* pSegment, const Info& info, long long element_start, long long element_size, VideoTrack*& pResult) { if (pResult) return -1; if (info.type != Track::kVideo) return -1; long long width = 0; long long height = 0; double rate = 0.0; IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; while (pos < stop) { long long id, size; const long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x30) //pixel width { width = UnserializeUInt(pReader, pos, size); if (width <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x3A) //pixel height { height = UnserializeUInt(pReader, pos, size); if (height <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0383E3) //frame rate { const long status = UnserializeFloat( pReader, pos, size, rate); if (status < 0) return status; if (rate <= 0) return E_FILE_FORMAT_INVALID; } pos += size; //consume payload assert(pos <= stop); } assert(pos == stop); VideoTrack* const pTrack = new (std::nothrow) VideoTrack(pSegment, element_start, element_size); if (pTrack == NULL) return -1; //generic error const int status = info.Copy(pTrack->m_info); if (status) // error { delete pTrack; return status; } pTrack->m_width = width; pTrack->m_height = height; pTrack->m_rate = rate; pResult = pTrack; return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long VideoTrack::Parse( IMkvReader* const pReader = pSegment->m_pReader; const Settings& s = info.settings; assert(s.start >= 0); assert(s.size >= 0); long long pos = s.start; assert(pos >= 0); const long long stop = pos + s.size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x30) { // pixel width width = UnserializeUInt(pReader, pos, size); if (width <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x3A) { // pixel height height = UnserializeUInt(pReader, pos, size); if (height <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0383E3) { // frame rate const long status = UnserializeFloat(pReader, pos, size, rate);
174,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char **argv) { int i, n_valid, do_write, do_scrub; char *c, *dname, *name; DIR *dir; FILE *fp; pdf_t *pdf; pdf_flag_t flags; if (argc < 2) usage(); /* Args */ do_write = do_scrub = flags = 0; name = NULL; for (i=1; i<argc; i++) { if (strncmp(argv[i], "-w", 2) == 0) do_write = 1; else if (strncmp(argv[i], "-i", 2) == 0) flags |= PDF_FLAG_DISP_CREATOR; else if (strncmp(argv[i], "-q", 2) == 0) flags |= PDF_FLAG_QUIET; else if (strncmp(argv[i], "-s", 2) == 0) do_scrub = 1; else if (argv[i][0] != '-') name = argv[i]; else if (argv[i][0] == '-') usage(); } if (!name) usage(); if (!(fp = fopen(name, "r"))) { ERR("Could not open file '%s'\n", argv[1]); return -1; } else if (!pdf_is_pdf(fp)) { ERR("'%s' specified is not a valid PDF\n", name); fclose(fp); return -1; } /* Load PDF */ if (!(pdf = init_pdf(fp, name))) { fclose(fp); return -1; } /* Count valid xrefs */ for (i=0, n_valid=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) ++n_valid; /* Bail if we only have 1 valid */ if (n_valid < 2) { if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR))) printf("%s: There is only one version of this PDF\n", pdf->name); if (do_write) { fclose(fp); pdf_delete(pdf); return 0; } } dname = NULL; if (do_write) { /* Create directory to place the various versions in */ if ((c = strrchr(name, '/'))) name = c + 1; if ((c = strrchr(name, '.'))) *c = '\0'; dname = malloc(strlen(name) + 16); sprintf(dname, "%s-versions", name); if (!(dir = opendir(dname))) mkdir(dname, S_IRWXU); else { ERR("This directory already exists, PDF version extraction will " "not occur.\n"); fclose(fp); closedir(dir); free(dname); pdf_delete(pdf); return -1; } /* Write the pdf as a pervious version */ for (i=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) write_version(fp, name, dname, &pdf->xrefs[i]); } /* Generate a per-object summary */ pdf_summarize(fp, pdf, dname, flags); /* Have we been summoned to scrub history from this PDF */ if (do_scrub) scrub_document(fp, pdf); /* Display extra information */ if (flags & PDF_FLAG_DISP_CREATOR) display_creator(fp, pdf); fclose(fp); free(dname); pdf_delete(pdf); return 0; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
int main(int argc, char **argv) { int i, n_valid, do_write, do_scrub; char *c, *dname, *name; DIR *dir; FILE *fp; pdf_t *pdf; pdf_flag_t flags; if (argc < 2) usage(); /* Args */ do_write = do_scrub = flags = 0; name = NULL; for (i=1; i<argc; i++) { if (strncmp(argv[i], "-w", 2) == 0) do_write = 1; else if (strncmp(argv[i], "-i", 2) == 0) flags |= PDF_FLAG_DISP_CREATOR; else if (strncmp(argv[i], "-q", 2) == 0) flags |= PDF_FLAG_QUIET; else if (strncmp(argv[i], "-s", 2) == 0) do_scrub = 1; else if (argv[i][0] != '-') name = argv[i]; else if (argv[i][0] == '-') usage(); } if (!name) usage(); if (!(fp = fopen(name, "r"))) { ERR("Could not open file '%s'\n", argv[1]); return -1; } else if (!pdf_is_pdf(fp)) { ERR("'%s' specified is not a valid PDF\n", name); fclose(fp); return -1; } /* Load PDF */ if (!(pdf = init_pdf(fp, name))) { fclose(fp); return -1; } /* Count valid xrefs */ for (i=0, n_valid=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) ++n_valid; /* Bail if we only have 1 valid */ if (n_valid < 2) { if (!(flags & (PDF_FLAG_QUIET | PDF_FLAG_DISP_CREATOR))) printf("%s: There is only one version of this PDF\n", pdf->name); if (do_write) { fclose(fp); pdf_delete(pdf); return 0; } } dname = NULL; if (do_write) { /* Create directory to place the various versions in */ if ((c = strrchr(name, '/'))) name = c + 1; if ((c = strrchr(name, '.'))) *c = '\0'; dname = safe_calloc(strlen(name) + 16); sprintf(dname, "%s-versions", name); if (!(dir = opendir(dname))) mkdir(dname, S_IRWXU); else { ERR("This directory already exists, PDF version extraction will " "not occur.\n"); fclose(fp); closedir(dir); free(dname); pdf_delete(pdf); return -1; } /* Write the pdf as a pervious version */ for (i=0; i<pdf->n_xrefs; i++) if (pdf->xrefs[i].version) write_version(fp, name, dname, &pdf->xrefs[i]); } /* Generate a per-object summary */ pdf_summarize(fp, pdf, dname, flags); /* Have we been summoned to scrub history from this PDF */ if (do_scrub) scrub_document(fp, pdf); /* Display extra information */ if (flags & PDF_FLAG_DISP_CREATOR) display_creator(fp, pdf); fclose(fp); free(dname); pdf_delete(pdf); return 0; }
169,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); }
167,031
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = EVP_CIPHER_CTX_iv_length(c); gctx->iv = EVP_CIPHER_CTX_iv_noconst(c); gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; /* Allocate memory for IV if needed */ if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) { if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c)) OPENSSL_free(gctx->iv); gctx->iv = OPENSSL_malloc(arg); if (gctx->iv == NULL) return 0; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c) || gctx->taglen < 0) return 0; memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); if (EVP_CIPHER_CTX_encrypting(c) && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: if (gctx->iv_gen == 0 || gctx->key_set == 0 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->tls_aad_len = arg; { unsigned int len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) len -= EVP_GCM_TLS_TAG_LEN; EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out); if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) return 0; gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c)) gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out); else { gctx_out->iv = OPENSSL_malloc(gctx->ivlen); if (gctx_out->iv == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } } Commit Message: crypto/evp: harden AEAD ciphers. Originally a crash in 32-bit build was reported CHACHA20-POLY1305 cipher. The crash is triggered by truncated packet and is result of excessive hashing to the edge of accessible memory. Since hash operation is read-only it is not considered to be exploitable beyond a DoS condition. Other ciphers were hardened. Thanks to Robert Święcki for report. CVE-2017-3731 Reviewed-by: Rich Salz <[email protected]> CWE ID: CWE-125
static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr) { EVP_AES_GCM_CTX *gctx = EVP_C_DATA(EVP_AES_GCM_CTX,c); switch (type) { case EVP_CTRL_INIT: gctx->key_set = 0; gctx->iv_set = 0; gctx->ivlen = EVP_CIPHER_CTX_iv_length(c); gctx->iv = EVP_CIPHER_CTX_iv_noconst(c); gctx->taglen = -1; gctx->iv_gen = 0; gctx->tls_aad_len = -1; return 1; case EVP_CTRL_AEAD_SET_IVLEN: if (arg <= 0) return 0; /* Allocate memory for IV if needed */ if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) { if (gctx->iv != EVP_CIPHER_CTX_iv_noconst(c)) OPENSSL_free(gctx->iv); gctx->iv = OPENSSL_malloc(arg); if (gctx->iv == NULL) return 0; } gctx->ivlen = arg; return 1; case EVP_CTRL_AEAD_SET_TAG: if (arg <= 0 || arg > 16 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->taglen = arg; return 1; case EVP_CTRL_AEAD_GET_TAG: if (arg <= 0 || arg > 16 || !EVP_CIPHER_CTX_encrypting(c) || gctx->taglen < 0) return 0; memcpy(ptr, EVP_CIPHER_CTX_buf_noconst(c), arg); return 1; case EVP_CTRL_GCM_SET_IV_FIXED: /* Special case: -1 length restores whole IV */ if (arg == -1) { memcpy(gctx->iv, ptr, gctx->ivlen); gctx->iv_gen = 1; return 1; } /* * Fixed field must be at least 4 bytes and invocation field at least * 8. */ if ((arg < 4) || (gctx->ivlen - arg) < 8) return 0; if (arg) memcpy(gctx->iv, ptr, arg); if (EVP_CIPHER_CTX_encrypting(c) && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0) return 0; gctx->iv_gen = 1; return 1; case EVP_CTRL_GCM_IV_GEN: if (gctx->iv_gen == 0 || gctx->key_set == 0) return 0; CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); if (arg <= 0 || arg > gctx->ivlen) arg = gctx->ivlen; memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg); /* * Invocation field will be at least 8 bytes in size and so no need * to check wrap around or increment more than last 8 bytes. */ ctr64_inc(gctx->iv + gctx->ivlen - 8); gctx->iv_set = 1; return 1; case EVP_CTRL_GCM_SET_IV_INV: if (gctx->iv_gen == 0 || gctx->key_set == 0 || EVP_CIPHER_CTX_encrypting(c)) return 0; memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg); CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen); gctx->iv_set = 1; return 1; case EVP_CTRL_AEAD_TLS1_AAD: /* Save the AAD for later use */ if (arg != EVP_AEAD_TLS1_AAD_LEN) return 0; memcpy(EVP_CIPHER_CTX_buf_noconst(c), ptr, arg); gctx->tls_aad_len = arg; { unsigned int len = EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] << 8 | EVP_CIPHER_CTX_buf_noconst(c)[arg - 1]; /* Correct length for explicit IV */ if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN) return 0; len -= EVP_GCM_TLS_EXPLICIT_IV_LEN; /* If decrypting correct for tag too */ if (!EVP_CIPHER_CTX_encrypting(c)) { if (len < EVP_GCM_TLS_TAG_LEN) return 0; len -= EVP_GCM_TLS_TAG_LEN; } EVP_CIPHER_CTX_buf_noconst(c)[arg - 2] = len >> 8; EVP_CIPHER_CTX_buf_noconst(c)[arg - 1] = len & 0xff; } /* Extra padding: tag appended to record */ return EVP_GCM_TLS_TAG_LEN; case EVP_CTRL_COPY: { EVP_CIPHER_CTX *out = ptr; EVP_AES_GCM_CTX *gctx_out = EVP_C_DATA(EVP_AES_GCM_CTX,out); if (gctx->gcm.key) { if (gctx->gcm.key != &gctx->ks) return 0; gctx_out->gcm.key = &gctx_out->ks; } if (gctx->iv == EVP_CIPHER_CTX_iv_noconst(c)) gctx_out->iv = EVP_CIPHER_CTX_iv_noconst(out); else { gctx_out->iv = OPENSSL_malloc(gctx->ivlen); if (gctx_out->iv == NULL) return 0; memcpy(gctx_out->iv, gctx->iv, gctx->ivlen); } return 1; } default: return -1; } }
168,431
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), node_(this), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), did_first_set_visible_(false), is_being_destroyed_(false), is_notifying_observers_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new device::GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), bluetooth_connected_device_count_(0), virtual_keyboard_requested_(false), #if !defined(OS_ANDROID) page_scale_factor_is_one_(true), #endif // !defined(OS_ANDROID) mouse_lock_widget_(nullptr), is_overlay_content_(false), showing_context_menu_(false), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif #if BUILDFLAG(ENABLE_PLUGINS) pepper_playback_observer_.reset(new PepperPlaybackObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); #if !defined(OS_ANDROID) host_zoom_map_observer_.reset(new HostZoomMapObserver(this)); #endif // !defined(OS_ANDROID) } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), node_(this), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), interstitial_page_(nullptr), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), did_first_set_visible_(false), is_being_destroyed_(false), is_notifying_observers_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new device::GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), bluetooth_connected_device_count_(0), virtual_keyboard_requested_(false), #if !defined(OS_ANDROID) page_scale_factor_is_one_(true), #endif // !defined(OS_ANDROID) mouse_lock_widget_(nullptr), is_overlay_content_(false), showing_context_menu_(false), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif #if BUILDFLAG(ENABLE_PLUGINS) pepper_playback_observer_.reset(new PepperPlaybackObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); #if !defined(OS_ANDROID) host_zoom_map_observer_.reset(new HostZoomMapObserver(this)); #endif // !defined(OS_ANDROID) }
172,335
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_be_3byte (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3) { psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_3byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_3byte (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_3byte */
170,048
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static PassRefPtr<Uint8Array> copySkImageData(SkImage* input, const SkImageInfo& info) { size_t width = static_cast<size_t>(input->width()); RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel()); if (!dstBuffer) return nullptr; RefPtr<Uint8Array> dstPixels = Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); input->readPixels(info, dstPixels->data(), width * info.bytesPerPixel(), 0, 0); return dstPixels; } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} CWE ID: CWE-787
static PassRefPtr<Uint8Array> copySkImageData(SkImage* input, const SkImageInfo& info) { // width * height * bytesPerPixel will never overflow unsigned. unsigned width = static_cast<unsigned>(input->width()); RefPtr<ArrayBuffer> dstBuffer = ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel()); if (!dstBuffer) return nullptr; RefPtr<Uint8Array> dstPixels = Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); input->readPixels(info, dstPixels->data(), width * info.bytesPerPixel(), 0, 0); return dstPixels; }
172,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: elm_main(int argc, char *argv[]) { int args = 1; unsigned char quitOption = 0; Browser_Window *window; Ecore_Getopt_Value values[] = { ECORE_GETOPT_VALUE_STR(evas_engine_name), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(frame_flattening_enabled), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_NONE }; if (!ewk_init()) return EXIT_FAILURE; ewk_view_smart_class_set(miniBrowserViewSmartClass()); ecore_app_args_set(argc, (const char **) argv); args = ecore_getopt_parse(&options, values, argc, argv); if (args < 0) return quit(EINA_FALSE, "ERROR: could not parse options.\n"); if (quitOption) return quit(EINA_TRUE, NULL); if (evas_engine_name) elm_config_preferred_engine_set(evas_engine_name); #if defined(WTF_USE_ACCELERATED_COMPOSITING) && defined(HAVE_ECORE_X) else { evas_engine_name = "opengl_x11"; elm_config_preferred_engine_set(evas_engine_name); } #endif Ewk_Context *context = ewk_context_default_get(); ewk_context_favicon_database_directory_set(context, NULL); if (args < argc) { char *url = url_from_user_input(argv[args]); window = window_create(url); free(url); } else window = window_create(DEFAULT_URL); if (!window) return quit(EINA_FALSE, "ERROR: could not create browser window.\n"); windows = eina_list_append(windows, window); elm_run(); return quit(EINA_TRUE, NULL); } Commit Message: [EFL][WK2] Add --window-size command line option to EFL MiniBrowser https://bugs.webkit.org/show_bug.cgi?id=100942 Patch by Mikhail Pozdnyakov <[email protected]> on 2012-11-05 Reviewed by Kenneth Rohde Christiansen. Added window-size (-s) command line option to EFL MiniBrowser. * MiniBrowser/efl/main.c: (window_create): (parse_window_size): (elm_main): git-svn-id: svn://svn.chromium.org/blink/trunk@133450 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
elm_main(int argc, char *argv[]) { int args = 1; unsigned char quitOption = 0; Browser_Window *window; char *window_size_string = NULL; Ecore_Getopt_Value values[] = { ECORE_GETOPT_VALUE_STR(evas_engine_name), ECORE_GETOPT_VALUE_STR(window_size_string), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(frame_flattening_enabled), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_BOOL(quitOption), ECORE_GETOPT_VALUE_NONE }; if (!ewk_init()) return EXIT_FAILURE; ewk_view_smart_class_set(miniBrowserViewSmartClass()); ecore_app_args_set(argc, (const char **) argv); args = ecore_getopt_parse(&options, values, argc, argv); if (args < 0) return quit(EINA_FALSE, "ERROR: could not parse options.\n"); if (quitOption) return quit(EINA_TRUE, NULL); if (evas_engine_name) elm_config_preferred_engine_set(evas_engine_name); #if defined(WTF_USE_ACCELERATED_COMPOSITING) && defined(HAVE_ECORE_X) else { evas_engine_name = "opengl_x11"; elm_config_preferred_engine_set(evas_engine_name); } #endif Ewk_Context *context = ewk_context_default_get(); ewk_context_favicon_database_directory_set(context, NULL); if (window_size_string) parse_window_size(window_size_string, &window_width, &window_height); if (args < argc) { char *url = url_from_user_input(argv[args]); window = window_create(url); free(url); } else window = window_create(DEFAULT_URL); if (!window) return quit(EINA_FALSE, "ERROR: could not create browser window.\n"); windows = eina_list_append(windows, window); elm_run(); return quit(EINA_TRUE, NULL); }
170,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 1; int i, j, last; krb5_error_code err = 0; krb5_key_data *key_data; if (n_key_data <= 0) return NULL; /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data_in == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } /* Find the number of key versions */ for (i = 0; i < n_key_data - 1; i++) if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) { krb5_data *code; if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { ret[j] = k5alloc(sizeof(struct berval), &err); if (ret[j] == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &code); if (err) goto cleanup; /*CHECK_NULL(ret[j]); */ ret[j]->bv_len = code->length; ret[j]->bv_val = code->data; free(code); j++; last = i + 1; currkvno = key_data[i].key_data_kvno; } } ret[num_versions] = NULL; cleanup: free(key_data); if (err != 0) { if (ret != NULL) { for (i = 0; i <= num_versions; i++) if (ret[i] != NULL) free (ret[i]); free (ret); ret = NULL; } } return ret; } Commit Message: Fix LDAP key data segmentation [CVE-2014-4345] For principal entries having keys with multiple kvnos (due to use of -keepold), the LDAP KDB module makes an attempt to store all the keys having the same kvno into a single krbPrincipalKey attribute value. There is a fencepost error in the loop, causing currkvno to be set to the just-processed value instead of the next kvno. As a result, the second and all following groups of multiple keys by kvno are each stored in two krbPrincipalKey attribute values. Fix the loop to use the correct kvno value. CVE-2014-4345: In MIT krb5, when kadmind is configured to use LDAP for the KDC database, an authenticated remote attacker can cause it to perform an out-of-bounds write (buffer overrun) by performing multiple cpw -keepold operations. An off-by-one error while copying key information to the new database entry results in keys sharing a common kvno being written to different array buckets, in an array whose size is determined by the number of kvnos present. After sufficient iterations, the extra writes extend past the end of the (NULL-terminated) array. The NULL terminator is always written after the end of the loop, so no out-of-bounds data is read, it is only written. Historically, it has been possible to convert an out-of-bounds write into remote code execution in some cases, though the necessary exploits must be tailored to the individual application and are usually quite complicated. Depending on the allocated length of the array, an out-of-bounds write may also cause a segmentation fault and/or application crash. CVSSv2 Vector: AV:N/AC:M/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C [[email protected]: clarified commit message] [[email protected]: CVE summary, CVSSv2 vector] (cherry picked from commit 81c332e29f10887c6b9deb065f81ba259f4c7e03) ticket: 7980 version_fixed: 1.12.2 status: resolved CWE ID: CWE-189
krb5_encode_krbsecretkey(krb5_key_data *key_data_in, int n_key_data, krb5_kvno mkvno) { struct berval **ret = NULL; int currkvno; int num_versions = 1; int i, j, last; krb5_error_code err = 0; krb5_key_data *key_data; if (n_key_data <= 0) return NULL; /* Make a shallow copy of the key data so we can alter it. */ key_data = k5calloc(n_key_data, sizeof(*key_data), &err); if (key_data_in == NULL) goto cleanup; memcpy(key_data, key_data_in, n_key_data * sizeof(*key_data)); /* Unpatched krb5 1.11 and 1.12 cannot decode KrbKey sequences with no salt * field. For compatibility, always encode a salt field. */ for (i = 0; i < n_key_data; i++) { if (key_data[i].key_data_ver == 1) { key_data[i].key_data_ver = 2; key_data[i].key_data_type[1] = KRB5_KDB_SALTTYPE_NORMAL; key_data[i].key_data_length[1] = 0; key_data[i].key_data_contents[1] = NULL; } } /* Find the number of key versions */ for (i = 0; i < n_key_data - 1; i++) if (key_data[i].key_data_kvno != key_data[i + 1].key_data_kvno) num_versions++; ret = (struct berval **) calloc (num_versions + 1, sizeof (struct berval *)); if (ret == NULL) { err = ENOMEM; goto cleanup; } for (i = 0, last = 0, j = 0, currkvno = key_data[0].key_data_kvno; i < n_key_data; i++) { krb5_data *code; if (i == n_key_data - 1 || key_data[i + 1].key_data_kvno != currkvno) { ret[j] = k5alloc(sizeof(struct berval), &err); if (ret[j] == NULL) goto cleanup; err = asn1_encode_sequence_of_keys(key_data + last, (krb5_int16)i - last + 1, mkvno, &code); if (err) goto cleanup; /*CHECK_NULL(ret[j]); */ ret[j]->bv_len = code->length; ret[j]->bv_val = code->data; free(code); j++; last = i + 1; if (i < n_key_data - 1) currkvno = key_data[i + 1].key_data_kvno; } } ret[num_versions] = NULL; cleanup: free(key_data); if (err != 0) { if (ret != NULL) { for (i = 0; i <= num_versions; i++) if (ret[i] != NULL) free (ret[i]); free (ret); ret = NULL; } } return ret; }
166,309
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IceGenerateMagicCookie ( int len ) { char *auth; #ifndef HAVE_ARC4RANDOM_BUF long ldata[2]; int seed; int value; int i; #endif if ((auth = malloc (len + 1)) == NULL) return (NULL); #ifdef HAVE_ARC4RANDOM_BUF arc4random_buf(auth, len); #else #ifdef ITIMER_REAL { struct timeval now; int i; ldata[0] = now.tv_sec; ldata[1] = now.tv_usec; } #else { long time (); ldata[0] = time ((long *) 0); ldata[1] = getpid (); } #endif seed = (ldata[0]) + (ldata[1] << 16); srand (seed); for (i = 0; i < len; i++) ldata[1] = now.tv_usec; value = rand (); auth[i] = value & 0xff; } Commit Message: CWE ID: CWE-331
IceGenerateMagicCookie ( static void emulate_getrandom_buf ( char *auth, int len ) { long ldata[2]; int seed; int value; int i; #ifdef ITIMER_REAL { struct timeval now; int i; ldata[0] = now.tv_sec; ldata[1] = now.tv_usec; } #else /* ITIMER_REAL */ { long time (); ldata[0] = time ((long *) 0); ldata[1] = getpid (); } #endif /* ITIMER_REAL */ seed = (ldata[0]) + (ldata[1] << 16); srand (seed); for (i = 0; i < len; i++) ldata[1] = now.tv_usec; value = rand (); auth[i] = value & 0xff; }
165,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_interlace_type(int PNG_CONST interlace_type) { if (interlace_type != PNG_INTERLACE_NONE) { /* This is an internal error - --interlace tests should be skipped, not * attempted. */ fprintf(stderr, "pngvalid: no interlace support\n"); exit(99); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
check_interlace_type(int PNG_CONST interlace_type) check_interlace_type(int const interlace_type) { /* Prior to 1.7.0 libpng does not support the write of an interlaced image * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the * code here does the pixel interlace itself, so: */ if (interlace_type != PNG_INTERLACE_NONE) { /* This is an internal error - --interlace tests should be skipped, not * attempted. */ fprintf(stderr, "pngvalid: no interlace support\n"); exit(99); } }
173,605
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseDocument(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; xmlInitParser(); if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); GROW; /* * SAX: detecting the level. */ xmlDetectSAX2(ctxt); /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(&start[0], 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. * do not GROW here to avoid the detected encoder to decode more * than just the first line, unless the amount of data is really * too small to hold "<?xml version="1.0" encoding="foo" */ if ((ctxt->input->end - ctxt->input->cur) < 35) { GROW; } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } ctxt->standalone = ctxt->input->standalone; SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); /* * The Misc part of the Prolog */ GROW; xmlParseMisc(ctxt); /* * Then possibly doc type declaration(s) and more Misc * (doctypedecl Misc*)? */ GROW; if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; xmlParseInternalSubset(ctxt); } /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; xmlParseMisc(ctxt); } /* * Time to start parsing the tree itself */ GROW; if (RAW != '<') { xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, "Start tag expected, '<' not found\n"); } else { ctxt->instate = XML_PARSER_CONTENT; xmlParseElement(ctxt); ctxt->instate = XML_PARSER_EPILOG; /* * The Misc part at the end */ xmlParseMisc(ctxt); if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } ctxt->instate = XML_PARSER_EOF; } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); /* * Remove locally kept entity definitions if the tree was not built */ if ((ctxt->myDoc != NULL) && (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { ctxt->myDoc->properties |= XML_DOC_WELLFORMED; if (ctxt->valid) ctxt->myDoc->properties |= XML_DOC_DTDVALID; if (ctxt->nsWellFormed) ctxt->myDoc->properties |= XML_DOC_NSVALID; if (ctxt->options & XML_PARSE_OLD10) ctxt->myDoc->properties |= XML_DOC_OLD10; } if (! ctxt->wellFormed) { ctxt->valid = 0; return(-1); } return(0); } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseDocument(xmlParserCtxtPtr ctxt) { xmlChar start[4]; xmlCharEncoding enc; xmlInitParser(); if ((ctxt == NULL) || (ctxt->input == NULL)) return(-1); GROW; /* * SAX: detecting the level. */ xmlDetectSAX2(ctxt); /* * SAX: beginning of the document processing. */ if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); if (ctxt->instate == XML_PARSER_EOF) return(-1); if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && ((ctxt->input->end - ctxt->input->cur) >= 4)) { /* * Get the 4 first bytes and decode the charset * if enc != XML_CHAR_ENCODING_NONE * plug some encoding conversion routines. */ start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(&start[0], 4); if (enc != XML_CHAR_ENCODING_NONE) { xmlSwitchEncoding(ctxt, enc); } } if (CUR == 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); } /* * Check for the XMLDecl in the Prolog. * do not GROW here to avoid the detected encoder to decode more * than just the first line, unless the amount of data is really * too small to hold "<?xml version="1.0" encoding="foo" */ if ((ctxt->input->end - ctxt->input->cur) < 35) { GROW; } if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { /* * Note that we will switch encoding on the fly. */ xmlParseXMLDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ return(-1); } ctxt->standalone = ctxt->input->standalone; SKIP_BLANKS; } else { ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); } if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) ctxt->sax->startDocument(ctxt->userData); if (ctxt->instate == XML_PARSER_EOF) return(-1); /* * The Misc part of the Prolog */ GROW; xmlParseMisc(ctxt); /* * Then possibly doc type declaration(s) and more Misc * (doctypedecl Misc*)? */ GROW; if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { ctxt->inSubset = 1; xmlParseDocTypeDecl(ctxt); if (RAW == '[') { ctxt->instate = XML_PARSER_DTD; xmlParseInternalSubset(ctxt); if (ctxt->instate == XML_PARSER_EOF) return(-1); } /* * Create and update the external subset. */ ctxt->inSubset = 2; if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && (!ctxt->disableSAX)) ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, ctxt->extSubSystem, ctxt->extSubURI); if (ctxt->instate == XML_PARSER_EOF) return(-1); ctxt->inSubset = 0; xmlCleanSpecialAttr(ctxt); ctxt->instate = XML_PARSER_PROLOG; xmlParseMisc(ctxt); } /* * Time to start parsing the tree itself */ GROW; if (RAW != '<') { xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, "Start tag expected, '<' not found\n"); } else { ctxt->instate = XML_PARSER_CONTENT; xmlParseElement(ctxt); ctxt->instate = XML_PARSER_EPILOG; /* * The Misc part at the end */ xmlParseMisc(ctxt); if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); } ctxt->instate = XML_PARSER_EOF; } /* * SAX: end of the document processing. */ if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) ctxt->sax->endDocument(ctxt->userData); /* * Remove locally kept entity definitions if the tree was not built */ if ((ctxt->myDoc != NULL) && (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { ctxt->myDoc->properties |= XML_DOC_WELLFORMED; if (ctxt->valid) ctxt->myDoc->properties |= XML_DOC_DTDVALID; if (ctxt->nsWellFormed) ctxt->myDoc->properties |= XML_DOC_NSVALID; if (ctxt->options & XML_PARSE_OLD10) ctxt->myDoc->properties |= XML_DOC_OLD10; } if (! ctxt->wellFormed) { ctxt->valid = 0; return(-1); } return(0); }
171,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: psf_binheader_readf (SF_PRIVATE *psf, char const *format, ...) { va_list argptr ; sf_count_t *countptr, countdata ; unsigned char *ucptr, sixteen_bytes [16] ; unsigned int *intptr, intdata ; unsigned short *shortptr ; char *charptr ; float *floatptr ; double *doubleptr ; char c ; int byte_count = 0, count ; if (! format) return psf_ftell (psf) ; va_start (argptr, format) ; while ((c = *format++)) { switch (c) { case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 'm' : /* 4 byte marker value eg 'RIFF' */ intptr = va_arg (argptr, unsigned int*) ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; *intptr = GET_MARKER (ucptr) ; break ; case 'h' : intptr = va_arg (argptr, unsigned int*) ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, sixteen_bytes, sizeof (sixteen_bytes)) ; { int k ; intdata = 0 ; for (k = 0 ; k < 16 ; k++) intdata ^= sixteen_bytes [k] << k ; } *intptr = intdata ; break ; case '1' : charptr = va_arg (argptr, char*) ; *charptr = 0 ; byte_count += header_read (psf, charptr, sizeof (char)) ; break ; case '2' : /* 2 byte value with the current endian-ness */ shortptr = va_arg (argptr, unsigned short*) ; *shortptr = 0 ; ucptr = (unsigned char*) shortptr ; byte_count += header_read (psf, ucptr, sizeof (short)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *shortptr = GET_BE_SHORT (ucptr) ; else *shortptr = GET_LE_SHORT (ucptr) ; break ; case '3' : /* 3 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 3) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = GET_BE_3BYTE (sixteen_bytes) ; else *intptr = GET_LE_3BYTE (sixteen_bytes) ; break ; case '4' : /* 4 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = psf_get_be32 (ucptr, 0) ; else *intptr = psf_get_le32 (ucptr, 0) ; break ; case '8' : /* 8 byte value with the current endian-ness */ countptr = va_arg (argptr, sf_count_t *) ; *countptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 8) ; if (psf->rwf_endian == SF_ENDIAN_BIG) countdata = psf_get_be64 (sixteen_bytes, 0) ; else countdata = psf_get_le64 (sixteen_bytes, 0) ; *countptr = countdata ; break ; case 'f' : /* Float conversion */ floatptr = va_arg (argptr, float *) ; *floatptr = 0.0 ; byte_count += header_read (psf, floatptr, sizeof (float)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *floatptr = float32_be_read ((unsigned char*) floatptr) ; else *floatptr = float32_le_read ((unsigned char*) floatptr) ; break ; case 'd' : /* double conversion */ doubleptr = va_arg (argptr, double *) ; *doubleptr = 0.0 ; byte_count += header_read (psf, doubleptr, sizeof (double)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *doubleptr = double64_be_read ((unsigned char*) doubleptr) ; else *doubleptr = double64_le_read ((unsigned char*) doubleptr) ; break ; case 's' : psf_log_printf (psf, "Format conversion 's' not implemented yet.\n") ; /* strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; longdata = H2LE_32 (size) ; get_int (psf, longdata) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; */ break ; case 'b' : /* Raw bytes */ charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; if (count > 0) byte_count += header_read (psf, charptr, count) ; break ; case 'G' : charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; if (count > 0) byte_count += header_gets (psf, charptr, count) ; break ; case 'z' : psf_log_printf (psf, "Format conversion 'z' not implemented yet.\n") ; /* size = va_arg (argptr, size_t) ; while (size) { psf->header [psf->headindex] = 0 ; psf->headindex ++ ; size -- ; } ; */ break ; case 'p' : /* Get the seek position first. */ count = va_arg (argptr, size_t) ; header_seek (psf, count, SEEK_SET) ; byte_count = count ; break ; case 'j' : /* Get the seek position first. */ count = va_arg (argptr, size_t) ; if (count) { header_seek (psf, count, SEEK_CUR) ; byte_count += count ; } ; break ; default : psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return byte_count ; } /* psf_binheader_readf */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
psf_binheader_readf (SF_PRIVATE *psf, char const *format, ...) { va_list argptr ; sf_count_t *countptr, countdata ; unsigned char *ucptr, sixteen_bytes [16] ; unsigned int *intptr, intdata ; unsigned short *shortptr ; char *charptr ; float *floatptr ; double *doubleptr ; char c ; int byte_count = 0, count = 0 ; if (! format) return psf_ftell (psf) ; va_start (argptr, format) ; while ((c = *format++)) { if (psf->header.indx + 16 >= psf->header.len && psf_bump_header_allocation (psf, 16)) return count ; switch (c) { case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 'm' : /* 4 byte marker value eg 'RIFF' */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; *intptr = GET_MARKER (ucptr) ; break ; case 'h' : intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, sixteen_bytes, sizeof (sixteen_bytes)) ; { int k ; intdata = 0 ; for (k = 0 ; k < 16 ; k++) intdata ^= sixteen_bytes [k] << k ; } *intptr = intdata ; break ; case '1' : charptr = va_arg (argptr, char*) ; *charptr = 0 ; byte_count += header_read (psf, charptr, sizeof (char)) ; break ; case '2' : /* 2 byte value with the current endian-ness */ shortptr = va_arg (argptr, unsigned short*) ; *shortptr = 0 ; ucptr = (unsigned char*) shortptr ; byte_count += header_read (psf, ucptr, sizeof (short)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *shortptr = GET_BE_SHORT (ucptr) ; else *shortptr = GET_LE_SHORT (ucptr) ; break ; case '3' : /* 3 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 3) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = GET_BE_3BYTE (sixteen_bytes) ; else *intptr = GET_LE_3BYTE (sixteen_bytes) ; break ; case '4' : /* 4 byte value with the current endian-ness */ intptr = va_arg (argptr, unsigned int*) ; *intptr = 0 ; ucptr = (unsigned char*) intptr ; byte_count += header_read (psf, ucptr, sizeof (int)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *intptr = psf_get_be32 (ucptr, 0) ; else *intptr = psf_get_le32 (ucptr, 0) ; break ; case '8' : /* 8 byte value with the current endian-ness */ countptr = va_arg (argptr, sf_count_t *) ; *countptr = 0 ; byte_count += header_read (psf, sixteen_bytes, 8) ; if (psf->rwf_endian == SF_ENDIAN_BIG) countdata = psf_get_be64 (sixteen_bytes, 0) ; else countdata = psf_get_le64 (sixteen_bytes, 0) ; *countptr = countdata ; break ; case 'f' : /* Float conversion */ floatptr = va_arg (argptr, float *) ; *floatptr = 0.0 ; byte_count += header_read (psf, floatptr, sizeof (float)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *floatptr = float32_be_read ((unsigned char*) floatptr) ; else *floatptr = float32_le_read ((unsigned char*) floatptr) ; break ; case 'd' : /* double conversion */ doubleptr = va_arg (argptr, double *) ; *doubleptr = 0.0 ; byte_count += header_read (psf, doubleptr, sizeof (double)) ; if (psf->rwf_endian == SF_ENDIAN_BIG) *doubleptr = double64_be_read ((unsigned char*) doubleptr) ; else *doubleptr = double64_le_read ((unsigned char*) doubleptr) ; break ; case 's' : psf_log_printf (psf, "Format conversion 's' not implemented yet.\n") ; /* strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; longdata = H2LE_32 (size) ; get_int (psf, longdata) ; memcpy (&(psf->header.ptr [psf->header.indx]), strptr, size) ; psf->header.indx += size ; */ break ; case 'b' : /* Raw bytes */ charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; memset (charptr, 0, count) ; byte_count += header_read (psf, charptr, count) ; break ; case 'G' : charptr = va_arg (argptr, char*) ; count = va_arg (argptr, size_t) ; memset (charptr, 0, count) ; if (psf->header.indx + count >= psf->header.len && psf_bump_header_allocation (psf, count)) return 0 ; byte_count += header_gets (psf, charptr, count) ; break ; case 'z' : psf_log_printf (psf, "Format conversion 'z' not implemented yet.\n") ; /* size = va_arg (argptr, size_t) ; while (size) { psf->header.ptr [psf->header.indx] = 0 ; psf->header.indx ++ ; size -- ; } ; */ break ; case 'p' : /* Seek to position from start. */ count = va_arg (argptr, size_t) ; header_seek (psf, count, SEEK_SET) ; byte_count = count ; break ; case 'j' : /* Seek to position from current position. */ count = va_arg (argptr, size_t) ; header_seek (psf, count, SEEK_CUR) ; byte_count += count ; break ; default : psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return byte_count ; } /* psf_binheader_readf */
170,064
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RunInvAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED_ARRAY(16, int16_t, in, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, int16_t, coeff, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs); DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs); for (int i = 0; i < count_test_block; ++i) { double out_r[kNumCoeffs]; for (int j = 0; j < kNumCoeffs; ++j) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); in[j] = src[j] - dst[j]; } reference_16x16_dct_2d(in, out_r); for (int j = 0; j < kNumCoeffs; ++j) coeff[j] = round(out_r[j]); REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, 16)); for (int j = 0; j < kNumCoeffs; ++j) { const uint32_t diff = dst[j] - src[j]; const uint32_t error = diff * diff; EXPECT_GE(1u, error) << "Error: 16x16 IDCT has error " << error << " at index " << j; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void RunInvAccuracyCheck() { ACMRandom rnd(ACMRandom::DeterministicSeed()); const int count_test_block = 1000; DECLARE_ALIGNED(16, int16_t, in[kNumCoeffs]); DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]); #if CONFIG_VP9_HIGHBITDEPTH DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]); #endif // CONFIG_VP9_HIGHBITDEPTH for (int i = 0; i < count_test_block; ++i) { double out_r[kNumCoeffs]; for (int j = 0; j < kNumCoeffs; ++j) { if (bit_depth_ == VPX_BITS_8) { src[j] = rnd.Rand8(); dst[j] = rnd.Rand8(); in[j] = src[j] - dst[j]; #if CONFIG_VP9_HIGHBITDEPTH } else { src16[j] = rnd.Rand16() & mask_; dst16[j] = rnd.Rand16() & mask_; in[j] = src16[j] - dst16[j]; #endif // CONFIG_VP9_HIGHBITDEPTH } } reference_16x16_dct_2d(in, out_r); for (int j = 0; j < kNumCoeffs; ++j) coeff[j] = static_cast<tran_low_t>(round(out_r[j])); if (bit_depth_ == VPX_BITS_8) { ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, 16)); #if CONFIG_VP9_HIGHBITDEPTH } else { ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, CONVERT_TO_BYTEPTR(dst16), 16)); #endif // CONFIG_VP9_HIGHBITDEPTH } for (int j = 0; j < kNumCoeffs; ++j) { #if CONFIG_VP9_HIGHBITDEPTH const uint32_t diff = bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; #else const uint32_t diff = dst[j] - src[j]; #endif // CONFIG_VP9_HIGHBITDEPTH const uint32_t error = diff * diff; EXPECT_GE(1u, error) << "Error: 16x16 IDCT has error " << error << " at index " << j; } } }
174,523
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void write_s3row_data( const entity_stage3_row *r, unsigned orig_cp, enum entity_charset charset, zval *arr) { char key[9] = ""; /* two unicode code points in UTF-8 */ char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'}; size_t written_k1; written_k1 = write_octet_sequence(key, charset, orig_cp); if (!r->ambiguous) { size_t l = r->data.ent.entity_len; memcpy(&entity[1], r->data.ent.entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } else { unsigned i, num_entries; const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table; if (mcpr[0].leading_entry.default_entity != NULL) { size_t l = mcpr[0].leading_entry.default_entity_len; memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } num_entries = mcpr[0].leading_entry.size; for (i = 1; i <= num_entries; i++) { size_t l, written_k2; unsigned uni_cp, spe_cp; uni_cp = mcpr[i].normal_entry.second_cp; l = mcpr[i].normal_entry.entity_len; if (!CHARSET_UNICODE_COMPAT(charset)) { if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE) continue; /* non representable in this charset */ } else { spe_cp = uni_cp; } written_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp); memcpy(&entity[1], mcpr[i].normal_entry.entity, l); entity[l + 1] = ';'; entity[l + 1] = '\0'; add_assoc_stringl_ex(arr, key, written_k1 + written_k2 + 1, entity, l + 1, 1); } } } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static inline void write_s3row_data( const entity_stage3_row *r, unsigned orig_cp, enum entity_charset charset, zval *arr) { char key[9] = ""; /* two unicode code points in UTF-8 */ char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'}; size_t written_k1; written_k1 = write_octet_sequence(key, charset, orig_cp); if (!r->ambiguous) { size_t l = r->data.ent.entity_len; memcpy(&entity[1], r->data.ent.entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } else { unsigned i, num_entries; const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table; if (mcpr[0].leading_entry.default_entity != NULL) { size_t l = mcpr[0].leading_entry.default_entity_len; memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l); entity[l + 1] = ';'; add_assoc_stringl_ex(arr, key, written_k1 + 1, entity, l + 2, 1); } num_entries = mcpr[0].leading_entry.size; for (i = 1; i <= num_entries; i++) { size_t l, written_k2; unsigned uni_cp, spe_cp; uni_cp = mcpr[i].normal_entry.second_cp; l = mcpr[i].normal_entry.entity_len; if (!CHARSET_UNICODE_COMPAT(charset)) { if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE) continue; /* non representable in this charset */ } else { spe_cp = uni_cp; } written_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp); memcpy(&entity[1], mcpr[i].normal_entry.entity, l); entity[l + 1] = ';'; entity[l + 1] = '\0'; add_assoc_stringl_ex(arr, key, written_k1 + written_k2 + 1, entity, l + 1, 1); } } }
167,181
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; /* 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. */ image->storage_class=PseudoClass; if (image->columns == 0) image->columns=2592; if (image->rows == 0) image->rows=3508; image->depth=8; if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Monochrome colormap. */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=(Quantum) 0; image->colormap[1].green=(Quantum) 0; image->colormap[1].blue=(Quantum) 0; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=HuffmanDecodeImage(image); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadFAXImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType status; /* 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. */ image->storage_class=PseudoClass; if (image->columns == 0) image->columns=2592; if (image->rows == 0) image->rows=3508; image->depth=8; if (AcquireImageColormap(image,2) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Monochrome colormap. */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=(Quantum) 0; image->colormap[1].green=(Quantum) 0; image->colormap[1].blue=(Quantum) 0; 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)); } status=HuffmanDecodeImage(image); if (status == MagickFalse) ThrowReaderException(CorruptImageError,"UnableToReadImageData"); if (EOFBlob(image) != MagickFalse) ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); (void) CloseBlob(image); return(GetFirstImageInList(image)); }
168,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ieee80211_fragment(struct ieee80211_tx_data *tx, struct sk_buff *skb, int hdrlen, int frag_threshold) { struct ieee80211_local *local = tx->local; struct ieee80211_tx_info *info; struct sk_buff *tmp; int per_fragm = frag_threshold - hdrlen - FCS_LEN; int pos = hdrlen + per_fragm; int rem = skb->len - hdrlen - per_fragm; if (WARN_ON(rem < 0)) return -EINVAL; /* first fragment was already added to queue by caller */ while (rem) { int fraglen = per_fragm; if (fraglen > rem) fraglen = rem; rem -= fraglen; tmp = dev_alloc_skb(local->tx_headroom + frag_threshold + tx->sdata->encrypt_headroom + IEEE80211_ENCRYPT_TAILROOM); if (!tmp) return -ENOMEM; __skb_queue_tail(&tx->skbs, tmp); skb_reserve(tmp, local->tx_headroom + tx->sdata->encrypt_headroom); /* copy control information */ memcpy(tmp->cb, skb->cb, sizeof(tmp->cb)); info = IEEE80211_SKB_CB(tmp); info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_FIRST_FRAGMENT); if (rem) info->flags |= IEEE80211_TX_CTL_MORE_FRAMES; skb_copy_queue_mapping(tmp, skb); tmp->priority = skb->priority; tmp->dev = skb->dev; /* copy header and data */ memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen); memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen); pos += fraglen; } /* adjust first fragment's length */ skb->len = hdrlen + per_fragm; return 0; } Commit Message: mac80211: fix fragmentation code, particularly for encryption The "new" fragmentation code (since my rewrite almost 5 years ago) erroneously sets skb->len rather than using skb_trim() to adjust the length of the first fragment after copying out all the others. This leaves the skb tail pointer pointing to after where the data originally ended, and thus causes the encryption MIC to be written at that point, rather than where it belongs: immediately after the data. The impact of this is that if software encryption is done, then a) encryption doesn't work for the first fragment, the connection becomes unusable as the first fragment will never be properly verified at the receiver, the MIC is practically guaranteed to be wrong b) we leak up to 8 bytes of plaintext (!) of the packet out into the air This is only mitigated by the fact that many devices are capable of doing encryption in hardware, in which case this can't happen as the tail pointer is irrelevant in that case. Additionally, fragmentation is not used very frequently and would normally have to be configured manually. Fix this by using skb_trim() properly. Cc: [email protected] Fixes: 2de8e0d999b8 ("mac80211: rewrite fragmentation") Reported-by: Jouni Malinen <[email protected]> Signed-off-by: Johannes Berg <[email protected]> CWE ID: CWE-200
static int ieee80211_fragment(struct ieee80211_tx_data *tx, struct sk_buff *skb, int hdrlen, int frag_threshold) { struct ieee80211_local *local = tx->local; struct ieee80211_tx_info *info; struct sk_buff *tmp; int per_fragm = frag_threshold - hdrlen - FCS_LEN; int pos = hdrlen + per_fragm; int rem = skb->len - hdrlen - per_fragm; if (WARN_ON(rem < 0)) return -EINVAL; /* first fragment was already added to queue by caller */ while (rem) { int fraglen = per_fragm; if (fraglen > rem) fraglen = rem; rem -= fraglen; tmp = dev_alloc_skb(local->tx_headroom + frag_threshold + tx->sdata->encrypt_headroom + IEEE80211_ENCRYPT_TAILROOM); if (!tmp) return -ENOMEM; __skb_queue_tail(&tx->skbs, tmp); skb_reserve(tmp, local->tx_headroom + tx->sdata->encrypt_headroom); /* copy control information */ memcpy(tmp->cb, skb->cb, sizeof(tmp->cb)); info = IEEE80211_SKB_CB(tmp); info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_FIRST_FRAGMENT); if (rem) info->flags |= IEEE80211_TX_CTL_MORE_FRAMES; skb_copy_queue_mapping(tmp, skb); tmp->priority = skb->priority; tmp->dev = skb->dev; /* copy header and data */ memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen); memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen); pos += fraglen; } /* adjust first fragment's length */ skb_trim(skb, hdrlen + per_fragm); return 0; }
166,242
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ChildProcessTerminationInfo ChildProcessLauncherHelper::GetTerminationInfo( const ChildProcessLauncherHelper::Process& process, bool known_dead) { ChildProcessTerminationInfo info; if (!java_peer_avaiable_on_client_thread_) return info; Java_ChildProcessLauncherHelperImpl_getTerminationInfo( AttachCurrentThread(), java_peer_, reinterpret_cast<intptr_t>(&info)); base::android::ApplicationState app_state = base::android::ApplicationStatusListener::GetState(); bool app_foreground = app_state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES || app_state == base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES; if (app_foreground && (info.binding_state == base::android::ChildBindingState::MODERATE || info.binding_state == base::android::ChildBindingState::STRONG)) { info.status = base::TERMINATION_STATUS_OOM_PROTECTED; } else { info.status = base::TERMINATION_STATUS_NORMAL_TERMINATION; } return info; } Commit Message: android: Stop child process in GetTerminationInfo Android currently abuses TerminationStatus to pass whether process is "oom protected" rather than whether it has died or not. This confuses cross-platform code about the state process. Only TERMINATION_STATUS_STILL_RUNNING is treated as still running, which android never passes. Also it appears to be ok to kill the process in getTerminationInfo as it's only called when the child process is dead or dying. Also posix kills the process on some calls. Bug: 940245 Change-Id: Id165711848c279bbe77ef8a784c8cf0b14051877 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1516284 Reviewed-by: Robert Sesek <[email protected]> Reviewed-by: ssid <[email protected]> Commit-Queue: Bo <[email protected]> Cr-Commit-Position: refs/heads/master@{#639639} CWE ID: CWE-664
ChildProcessTerminationInfo ChildProcessLauncherHelper::GetTerminationInfo( const ChildProcessLauncherHelper::Process& process, bool known_dead) { ChildProcessTerminationInfo info; if (!java_peer_avaiable_on_client_thread_) return info; Java_ChildProcessLauncherHelperImpl_getTerminationInfoAndStop( AttachCurrentThread(), java_peer_, reinterpret_cast<intptr_t>(&info)); base::android::ApplicationState app_state = base::android::ApplicationStatusListener::GetState(); bool app_foreground = app_state == base::android::APPLICATION_STATE_HAS_RUNNING_ACTIVITIES || app_state == base::android::APPLICATION_STATE_HAS_PAUSED_ACTIVITIES; if (app_foreground && (info.binding_state == base::android::ChildBindingState::MODERATE || info.binding_state == base::android::ChildBindingState::STRONG)) { info.status = base::TERMINATION_STATUS_OOM_PROTECTED; } else { info.status = base::TERMINATION_STATUS_NORMAL_TERMINATION; } return info; }
173,016
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void skcipher_release(void *private) { crypto_free_skcipher(private); } Commit Message: crypto: algif_skcipher - Require setkey before accept(2) Some cipher implementations will crash if you try to use them without calling setkey first. This patch adds a check so that the accept(2) call will fail with -ENOKEY if setkey hasn't been done on the socket yet. Cc: [email protected] Reported-by: Dmitry Vyukov <[email protected]> Signed-off-by: Herbert Xu <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> CWE ID: CWE-476
static void skcipher_release(void *private) { struct skcipher_tfm *tfm = private; crypto_free_skcipher(tfm->skcipher); kfree(tfm); }
167,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmalloc (length * nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getRGBLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getRGBLine(in, out, length); break; } } Commit Message: CWE ID: CWE-189
void GfxImageColorMap::getRGBLine(Guchar *in, unsigned int *out, int length) { int i, j; Guchar *inp, *tmp_line; switch (colorSpace->getMode()) { case csIndexed: case csSeparation: tmp_line = (Guchar *) gmallocn (length, nComps2); for (i = 0; i < length; i++) { for (j = 0; j < nComps2; j++) { tmp_line[i * nComps2 + j] = byte_lookup[in[i] * nComps2 + j]; } } colorSpace2->getRGBLine(tmp_line, out, length); gfree (tmp_line); break; default: inp = in; for (j = 0; j < length; j++) for (i = 0; i < nComps; i++) { *inp = byte_lookup[*inp * nComps + i]; inp++; } colorSpace->getRGBLine(in, out, length); break; } }
164,611
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id) { l2cap_socket *sock; char drop_it = FALSE; /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */ pthread_mutex_lock(&state_lock); sock = btsock_l2cap_find_by_id_l(user_id); if (sock) { if ((flags & SOCK_THREAD_FD_RD) && !sock->server) { if (sock->connected) { int size = 0; if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (ioctl(sock->our_fd, FIONREAD, &size) == 0 && size)) { uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH); /* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to * the write complete callback, which call a free... wonder if this works on a * 64 bit platform? */ if (buffer != NULL) { /* The socket is created with SOCK_SEQPACKET, hence we read one message at * the time. The maximum size of a message is allocated to ensure data is * not lost. This is okay to do as Android uses virtual memory, hence even * if we only use a fraction of the memory it should not block for others * to use the memory. As the definition of ioctl(FIONREAD) do not clearly * define what value will be returned if multiple messages are written to * the socket before any message is read from the socket, we could * potentially risk to allocate way more memory than needed. One of the use * cases for this socket is obex where multiple 64kbyte messages are * typically written to the socket in a tight loop, hence we risk the ioctl * will return the total amount of data in the buffer, which could be * multiple 64kbyte chunks. * UPDATE: As bluedroid cannot handle 64kbyte buffers, the size is reduced * to around 8kbyte - and using malloc for buffer allocation here seems to * be wrong * UPDATE: Since we are responsible for freeing the buffer in the * write_complete_ind, it is OK to use malloc. */ int count = recv(fd, buffer, L2CAP_MAX_SDU_LENGTH, MSG_NOSIGNAL | MSG_DONTWAIT); APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket", count); if (sock->fixed_chan) { if(BTA_JvL2capWriteFixed(sock->channel, (BD_ADDR*)&sock->addr, (UINT32)buffer, btsock_l2cap_cbk, buffer, count, (void *)user_id) != BTA_JV_SUCCESS) { on_l2cap_write_fixed_done(buffer, user_id); } } else { if(BTA_JvL2capWrite(sock->handle, (UINT32)buffer, buffer, count, (void *)user_id) != BTA_JV_SUCCESS) { on_l2cap_write_done(buffer, user_id); } } } else { APPL_TRACE_ERROR("Unable to allocate memory for data packet from JAVA...") } } } else drop_it = TRUE; } if (flags & SOCK_THREAD_FD_WR) { if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected) btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id); } if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) { int size = 0; if (drop_it || ioctl(sock->our_fd, FIONREAD, &size) != 0 || size == 0) btsock_l2cap_free_l(sock); } } pthread_mutex_unlock(&state_lock); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
void btsock_l2cap_signaled(int fd, int flags, uint32_t user_id) { l2cap_socket *sock; char drop_it = FALSE; /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to hold the lock. */ pthread_mutex_lock(&state_lock); sock = btsock_l2cap_find_by_id_l(user_id); if (sock) { if ((flags & SOCK_THREAD_FD_RD) && !sock->server) { if (sock->connected) { int size = 0; if (!(flags & SOCK_THREAD_FD_EXCEPTION) || (TEMP_FAILURE_RETRY(ioctl(sock->our_fd, FIONREAD, &size)) == 0 && size)) { uint8_t *buffer = osi_malloc(L2CAP_MAX_SDU_LENGTH); /* Apparently we hijack the req_id (UINT32) to pass the pointer to the buffer to * the write complete callback, which call a free... wonder if this works on a * 64 bit platform? */ if (buffer != NULL) { /* The socket is created with SOCK_SEQPACKET, hence we read one message at * the time. The maximum size of a message is allocated to ensure data is * not lost. This is okay to do as Android uses virtual memory, hence even * if we only use a fraction of the memory it should not block for others * to use the memory. As the definition of ioctl(FIONREAD) do not clearly * define what value will be returned if multiple messages are written to * the socket before any message is read from the socket, we could * potentially risk to allocate way more memory than needed. One of the use * cases for this socket is obex where multiple 64kbyte messages are * typically written to the socket in a tight loop, hence we risk the ioctl * will return the total amount of data in the buffer, which could be * multiple 64kbyte chunks. * UPDATE: As bluedroid cannot handle 64kbyte buffers, the size is reduced * to around 8kbyte - and using malloc for buffer allocation here seems to * be wrong * UPDATE: Since we are responsible for freeing the buffer in the * write_complete_ind, it is OK to use malloc. */ int count = TEMP_FAILURE_RETRY(recv(fd, buffer, L2CAP_MAX_SDU_LENGTH, MSG_NOSIGNAL | MSG_DONTWAIT)); APPL_TRACE_DEBUG("btsock_l2cap_signaled - %d bytes received from socket", count); if (sock->fixed_chan) { if(BTA_JvL2capWriteFixed(sock->channel, (BD_ADDR*)&sock->addr, (UINT32)buffer, btsock_l2cap_cbk, buffer, count, (void *)user_id) != BTA_JV_SUCCESS) { on_l2cap_write_fixed_done(buffer, user_id); } } else { if(BTA_JvL2capWrite(sock->handle, (UINT32)buffer, buffer, count, (void *)user_id) != BTA_JV_SUCCESS) { on_l2cap_write_done(buffer, user_id); } } } else { APPL_TRACE_ERROR("Unable to allocate memory for data packet from JAVA...") } } } else drop_it = TRUE; } if (flags & SOCK_THREAD_FD_WR) { if (flush_incoming_que_on_wr_signal_l(sock) && sock->connected) btsock_thread_add_fd(pth, sock->our_fd, BTSOCK_L2CAP, SOCK_THREAD_FD_WR, sock->id); } if (drop_it || (flags & SOCK_THREAD_FD_EXCEPTION)) { int size = 0; if (drop_it || TEMP_FAILURE_RETRY(ioctl(sock->our_fd, FIONREAD, &size)) != 0 || size == 0) btsock_l2cap_free_l(sock); } } pthread_mutex_unlock(&state_lock); }
173,453
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: setv4key_principal_2_svc(setv4key_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setv4key_principal((void *)handle, arg->princ, arg->keyblock); } else { log_unauth("kadm5_setv4key_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setv4key_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
setv4key_principal_2_svc(setv4key_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_SETKEY, arg->princ, NULL)) { ret.code = kadm5_setv4key_principal((void *)handle, arg->princ, arg->keyblock); } else { log_unauth("kadm5_setv4key_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_SETKEY; } if(ret.code != KADM5_AUTH_SETKEY) { if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_setv4key_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateTrue( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_True; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateTrue( void )
167,280
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket, int newUid, uid_t callerUid) { ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__); const int fd = socket.get(); struct stat info; if (fstat(fd, &info)) { return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor"); } if (info.st_uid != callerUid) { return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls"); } if (S_ISSOCK(info.st_mode) == 0) { return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket"); } int optval; socklen_t optlen; netdutils::Status status = getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen); if (status != netdutils::status::ok) { return status; } if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) { return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set"); } if (fchown(fd, newUid, -1)) { return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor"); } return netdutils::status::ok; } Commit Message: Set optlen for UDP-encap check in XfrmController When setting the socket owner for an encap socket XfrmController will first attempt to verify that the socket has the UDP-encap socket option set. When doing so it would pass in an uninitialized optlen parameter which could cause the call to not modify the option value if the optlen happened to be too short. So for example if the stack happened to contain a zero where optlen was located the check would fail and the socket owner would not be changed. Fix this by setting optlen to the size of the option value parameter. Test: run cts -m CtsNetTestCases BUG: 111650288 Change-Id: I57b6e9dba09c1acda71e3ec2084652e961667bd9 (cherry picked from commit fc42a105147310bd680952d4b71fe32974bd8506) CWE ID: CWE-909
netdutils::Status XfrmController::ipSecSetEncapSocketOwner(const android::base::unique_fd& socket, int newUid, uid_t callerUid) { ALOGD("XfrmController:%s, line=%d", __FUNCTION__, __LINE__); const int fd = socket.get(); struct stat info; if (fstat(fd, &info)) { return netdutils::statusFromErrno(errno, "Failed to stat socket file descriptor"); } if (info.st_uid != callerUid) { return netdutils::statusFromErrno(EPERM, "fchown disabled for non-owner calls"); } if (S_ISSOCK(info.st_mode) == 0) { return netdutils::statusFromErrno(EINVAL, "File descriptor was not a socket"); } int optval; socklen_t optlen = sizeof(optval); netdutils::Status status = getSyscallInstance().getsockopt(Fd(socket), IPPROTO_UDP, UDP_ENCAP, &optval, &optlen); if (status != netdutils::status::ok) { return status; } if (optval != UDP_ENCAP_ESPINUDP && optval != UDP_ENCAP_ESPINUDP_NON_IKE) { return netdutils::statusFromErrno(EINVAL, "Socket did not have UDP-encap sockopt set"); } if (fchown(fd, newUid, -1)) { return netdutils::statusFromErrno(errno, "Failed to fchown socket file descriptor"); } return netdutils::status::ok; }
174,073
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList) { UINT32 i; UINT32 scopeCount; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, scopeCount); /* ScopeCount (4 bytes) */ scopeList->count = scopeCount; scopeList->array = (LICENSE_BLOB*) malloc(sizeof(LICENSE_BLOB) * scopeCount); /* ScopeArray */ for (i = 0; i < scopeCount; i++) { scopeList->array[i].type = BB_SCOPE_BLOB; if (!license_read_binary_blob(s, &scopeList->array[i])) return FALSE; } return TRUE; } Commit Message: Fix possible integer overflow in license_read_scope_list() CWE ID: CWE-189
BOOL license_read_scope_list(wStream* s, SCOPE_LIST* scopeList) { UINT32 i; UINT32 scopeCount; if (Stream_GetRemainingLength(s) < 4) return FALSE; Stream_Read_UINT32(s, scopeCount); /* ScopeCount (4 bytes) */ if (Stream_GetRemainingLength(s) / sizeof(LICENSE_BLOB) < scopeCount) return FALSE; /* Avoid overflow in malloc */ scopeList->count = scopeCount; scopeList->array = (LICENSE_BLOB*) malloc(sizeof(LICENSE_BLOB) * scopeCount); /* ScopeArray */ for (i = 0; i < scopeCount; i++) { scopeList->array[i].type = BB_SCOPE_BLOB; if (!license_read_binary_blob(s, &scopeList->array[i])) return FALSE; } return TRUE; }
166,440
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; if (a->type == szMAPI_UNICODE_STRING) { v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, "Invalid attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, "Undefined attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; } Commit Message: Use asserts on lengths to prevent invalid reads/writes. CWE ID: CWE-125
mapi_attr_read (size_t len, unsigned char *buf) { size_t idx = 0; uint32 i,j; assert(len > 4); uint32 num_properties = GETINT32(buf+idx); assert((num_properties+1) != 0); MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); idx += 4; if (!attrs) return NULL; for (i = 0; i < num_properties; i++) { MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); MAPI_Value* v = NULL; CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; /* handle special case of GUID prefixed properties */ if (a->name & GUID_EXISTS_FLAG) { /* copy GUID */ a->guid = CHECKED_XMALLOC(GUID, 1); copy_guid_from_buf(a->guid, buf+idx, len); idx += sizeof (GUID); CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; if (a->num_names > 0) { /* FIXME: do something useful here! */ size_t i; a->names = CHECKED_XCALLOC(VarLenData, a->num_names); for (i = 0; i < a->num_names; i++) { size_t j; CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; /* read the data into a buffer */ a->names[i].data = CHECKED_XMALLOC(unsigned char, a->names[i].len); assert((idx+(a->names[i].len*2)) <= len); for (j = 0; j < (a->names[i].len >> 1); j++) a->names[i].data[j] = (buf+idx)[j*2]; /* But what are we going to do with it? */ idx += pad_to_4byte(a->names[i].len); } } else { /* get the 'real' name */ CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; } } /* * Multi-value types and string/object/binary types have * multiple values */ if (a->type & MULTI_VALUE_FLAG || a->type == szMAPI_STRING || a->type == szMAPI_UNICODE_STRING || a->type == szMAPI_OBJECT || a->type == szMAPI_BINARY) { CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); idx += 4; } else { a->num_values = 1; } /* Amend the type in case of multi-value type */ if (a->type & MULTI_VALUE_FLAG) { a->type -= MULTI_VALUE_FLAG; } v = alloc_mapi_values (a); for (j = 0; j < a->num_values; j++) { switch (a->type) { case szMAPI_SHORT: /* 2 bytes */ v->len = 2; CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); idx += 4; /* assume padding of 2, advance by 4! */ break; case szMAPI_INT: /* 4 bytes */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += 4; v++; break; case szMAPI_FLOAT: /* 4 bytes */ case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ v->len = 4; CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); idx += v->len; break; case szMAPI_SYSTIME: /* 8 bytes */ v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += 8; v++; break; case szMAPI_DOUBLE: /* 8 bytes */ case szMAPI_APPTIME: case szMAPI_CURRENCY: case szMAPI_INT8BYTE: v->len = 8; CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); idx += v->len; break; case szMAPI_CLSID: v->len = sizeof (GUID); copy_guid_from_buf(&v->data.guid, buf+idx, len); idx += v->len; break; case szMAPI_STRING: case szMAPI_UNICODE_STRING: case szMAPI_OBJECT: case szMAPI_BINARY: CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; assert(v->len + idx <= len); if (a->type == szMAPI_UNICODE_STRING) { assert(v->len != 0); v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); } else { v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); memmove (v->data.buf, buf+idx, v->len); } idx += pad_to_4byte(v->len); v++; break; case szMAPI_NULL: /* illegal in input tnef streams */ case szMAPI_ERROR: case szMAPI_UNSPECIFIED: fprintf (stderr, "Invalid attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; default: /* should never get here */ fprintf (stderr, "Undefined attribute, input file may be corrupted\n"); if (!ENCODE_SKIP) exit (1); return NULL; } if (DEBUG_ON) mapi_attr_dump (attrs[i]); } } attrs[i] = NULL; return attrs; }
168,360
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool TabLifecycleUnitSource::TabLifecycleUnit::CanDiscard( DiscardReason reason, DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!tab_strip_model_) return false; const LifecycleUnitState target_state = reason == DiscardReason::kProactive && GetState() != LifecycleUnitState::FROZEN ? LifecycleUnitState::PENDING_DISCARD : LifecycleUnitState::DISCARDED; if (!IsValidStateChange(GetState(), target_state, DiscardReasonToStateChangeReason(reason))) { return false; } if (GetWebContents()->IsCrashed()) return false; if (!GetWebContents()->GetLastCommittedURL().is_valid() || GetWebContents()->GetLastCommittedURL().is_empty()) { return false; } if (discard_count_ > 0) { #if defined(OS_CHROMEOS) if (reason != DiscardReason::kUrgent) return false; #else return false; #endif // defined(OS_CHROMEOS) } #if defined(OS_CHROMEOS) if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #else if (tab_strip_model_->GetActiveWebContents() == GetWebContents()) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #endif // defined(OS_CHROMEOS) if (GetWebContents()->GetPageImportanceSignals().had_form_interaction) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_FORM_ENTRY); IsMediaTabImpl(decision_details); if (GetWebContents()->GetContentsMimeType() == "application/pdf") decision_details->AddReason(DecisionFailureReason::LIVE_STATE_IS_PDF); if (!IsAutoDiscardable()) { decision_details->AddReason( DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED); } if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); } 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:
bool TabLifecycleUnitSource::TabLifecycleUnit::CanDiscard( DiscardReason reason, DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!tab_strip_model_) return false; const LifecycleUnitState target_state = reason == DiscardReason::kProactive && GetState() != LifecycleUnitState::FROZEN ? LifecycleUnitState::PENDING_DISCARD : LifecycleUnitState::DISCARDED; if (!IsValidStateChange(GetState(), target_state, DiscardReasonToStateChangeReason(reason))) { return false; } if (GetWebContents()->IsCrashed()) return false; if (!GetWebContents()->GetLastCommittedURL().is_valid() || GetWebContents()->GetLastCommittedURL().is_empty()) { return false; } if (discard_count_ > 0) { #if defined(OS_CHROMEOS) if (reason != DiscardReason::kUrgent) return false; #else return false; #endif // defined(OS_CHROMEOS) } #if defined(OS_CHROMEOS) if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #else if (tab_strip_model_->GetActiveWebContents() == GetWebContents()) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #endif // defined(OS_CHROMEOS) if (GetWebContents()->GetPageImportanceSignals().had_form_interaction) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_FORM_ENTRY); IsMediaTabImpl(decision_details); if (GetWebContents()->GetContentsMimeType() == "application/pdf") decision_details->AddReason(DecisionFailureReason::LIVE_STATE_IS_PDF); if (!IsAutoDiscardable()) { decision_details->AddReason( DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED); } // Consult the local database to see if this tab could try to communicate with // the user while in background (don't check for the visibility here as // there's already a check for that above). if (reason != DiscardReason::kUrgent) { CheckIfTabCanCommunicateWithUserWhileInBackground(GetWebContents(), decision_details); } if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); }
172,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool MediaElementAudioSourceHandler::PassesCORSAccessCheck() { DCHECK(MediaElement()); return (MediaElement()->GetWebMediaPlayer() && MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) || passes_current_src_cors_access_check_; } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
bool MediaElementAudioSourceHandler::PassesCORSAccessCheck() {
173,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeDownloadDelegate::RequestHTTPGetDownload( const std::string& url, const std::string& user_agent, const std::string& content_disposition, const std::string& mime_type, const std::string& cookie, const std::string& referer, const base::string16& file_name, int64_t content_length, bool has_user_gesture, bool must_download) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jurl = ConvertUTF8ToJavaString(env, url); ScopedJavaLocalRef<jstring> juser_agent = ConvertUTF8ToJavaString(env, user_agent); ScopedJavaLocalRef<jstring> jcontent_disposition = ConvertUTF8ToJavaString(env, content_disposition); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); ScopedJavaLocalRef<jstring> jcookie = ConvertUTF8ToJavaString(env, cookie); ScopedJavaLocalRef<jstring> jreferer = ConvertUTF8ToJavaString(env, referer); ScopedJavaLocalRef<jstring> jfilename = base::android::ConvertUTF16ToJavaString(env, file_name); Java_ChromeDownloadDelegate_requestHttpGetDownload( env, java_ref_, jurl, juser_agent, jcontent_disposition, jmime_type, jcookie, jreferer, has_user_gesture, jfilename, content_length, must_download); } Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack The only exception is OMA DRM download. And it only applies to context menu download interception. Clean up the remaining unused code now. BUG=647755 Review-Url: https://codereview.chromium.org/2371773003 Cr-Commit-Position: refs/heads/master@{#421332} CWE ID: CWE-254
void ChromeDownloadDelegate::RequestHTTPGetDownload(
171,880
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CoordinatorImpl::RequestGlobalMemoryDump( MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail, const std::vector<std::string>& allocator_dump_names, const RequestGlobalMemoryDumpCallback& callback) { auto adapter = [](const RequestGlobalMemoryDumpCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names, false /* add_to_trace */, base::kNullProcessId); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); } Commit Message: memory-infra: split up memory-infra coordinator service into two This allows for heap profiler to use its own service with correct capabilities and all other instances to use the existing coordinator service. Bug: 792028 Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd Reviewed-on: https://chromium-review.googlesource.com/836896 Commit-Queue: Lalit Maganti <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: oysteine <[email protected]> Reviewed-by: Albert J. Wong <[email protected]> Reviewed-by: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#529059} CWE ID: CWE-269
void CoordinatorImpl::RequestGlobalMemoryDump( MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail, const std::vector<std::string>& allocator_dump_names, const RequestGlobalMemoryDumpCallback& callback) { // Don't allow arbitary processes to obtain VM regions. Only the heap profiler // is allowed to obtain them using the special method on the different // interface. if (level_of_detail == MemoryDumpLevelOfDetail::VM_REGIONS_ONLY_FOR_HEAP_PROFILER) { bindings_.ReportBadMessage( "Requested global memory dump using level of detail reserved for the " "heap profiler."); return; } auto adapter = [](const RequestGlobalMemoryDumpCallback& callback, bool success, uint64_t, mojom::GlobalMemoryDumpPtr global_memory_dump) { callback.Run(success, std::move(global_memory_dump)); }; QueuedRequest::Args args(dump_type, level_of_detail, allocator_dump_names, false /* add_to_trace */, base::kNullProcessId); RequestGlobalMemoryDumpInternal(args, base::BindRepeating(adapter, callback)); }
172,915
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: iakerb_gss_export_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 maj; iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; /* We don't currently support exporting partially established contexts. */ if (!ctx->established) return GSS_S_UNAVAILABLE; maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc, interprocess_token); if (ctx->gssc == GSS_C_NO_CONTEXT) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return maj; } Commit Message: Fix IAKERB context export/import [CVE-2015-2698] The patches for CVE-2015-2696 contained a regression in the newly added IAKERB iakerb_gss_export_sec_context() function, which could cause it to corrupt memory. Fix the regression by properly dereferencing the context_handle pointer before casting it. Also, the patches did not implement an IAKERB gss_import_sec_context() function, under the erroneous belief that an exported IAKERB context would be tagged as a krb5 context. Implement it now to allow IAKERB contexts to be successfully exported and imported after establishment. CVE-2015-2698: In any MIT krb5 release with the patches for CVE-2015-2696 applied, an application which calls gss_export_sec_context() may experience memory corruption if the context was established using the IAKERB mechanism. Historically, some vulnerabilities of this nature can be translated into remote code execution, though the necessary exploits must be tailored to the individual application and are usually quite complicated. CVSSv2 Vector: AV:N/AC:H/Au:S/C:C/I:C/A:C/E:POC/RL:OF/RC:C ticket: 8273 (new) target_version: 1.14 tags: pullup CWE ID: CWE-119
iakerb_gss_export_sec_context(OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_buffer_t interprocess_token) { OM_uint32 maj; iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle; /* We don't currently support exporting partially established contexts. */ if (!ctx->established) return GSS_S_UNAVAILABLE; maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc, interprocess_token); if (ctx->gssc == GSS_C_NO_CONTEXT) { iakerb_release_context(ctx); *context_handle = GSS_C_NO_CONTEXT; } return maj; }
166,640
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *frame) { AVFilterContext *ctx = inlink->dst; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); uint32_t plane_checksum[4] = {0}, checksum = 0; int i, plane, vsub = desc->log2_chroma_h; for (plane = 0; plane < 4 && frame->data[plane]; plane++) { int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane); uint8_t *data = frame->data[plane]; int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h; if (linesize < 0) return linesize; for (i = 0; i < h; i++) { plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize); checksum = av_adler32_update(checksum, data, linesize); data += frame->linesize[plane]; } } av_log(ctx, AV_LOG_INFO, "n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" " "fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c " "checksum:%08X plane_checksum:[%08X", inlink->frame_count, av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame), desc->name, frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den, frame->width, frame->height, !frame->interlaced_frame ? 'P' : /* Progressive */ frame->top_field_first ? 'T' : 'B', /* Top / Bottom */ frame->key_frame, av_get_picture_type_char(frame->pict_type), checksum, plane_checksum[0]); for (plane = 1; plane < 4 && frame->data[plane]; plane++) av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]); av_log(ctx, AV_LOG_INFO, "]\n"); return ff_filter_frame(inlink->dst->outputs[0], frame); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *frame) { AVFilterContext *ctx = inlink->dst; const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format); uint32_t plane_checksum[4] = {0}, checksum = 0; int i, plane, vsub = desc->log2_chroma_h; for (plane = 0; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) { int64_t linesize = av_image_get_linesize(frame->format, frame->width, plane); uint8_t *data = frame->data[plane]; int h = plane == 1 || plane == 2 ? FF_CEIL_RSHIFT(inlink->h, vsub) : inlink->h; if (linesize < 0) return linesize; for (i = 0; i < h; i++) { plane_checksum[plane] = av_adler32_update(plane_checksum[plane], data, linesize); checksum = av_adler32_update(checksum, data, linesize); data += frame->linesize[plane]; } } av_log(ctx, AV_LOG_INFO, "n:%"PRId64" pts:%s pts_time:%s pos:%"PRId64" " "fmt:%s sar:%d/%d s:%dx%d i:%c iskey:%d type:%c " "checksum:%08X plane_checksum:[%08X", inlink->frame_count, av_ts2str(frame->pts), av_ts2timestr(frame->pts, &inlink->time_base), av_frame_get_pkt_pos(frame), desc->name, frame->sample_aspect_ratio.num, frame->sample_aspect_ratio.den, frame->width, frame->height, !frame->interlaced_frame ? 'P' : /* Progressive */ frame->top_field_first ? 'T' : 'B', /* Top / Bottom */ frame->key_frame, av_get_picture_type_char(frame->pict_type), checksum, plane_checksum[0]); for (plane = 1; plane < 4 && frame->data[plane] && frame->linesize[plane]; plane++) av_log(ctx, AV_LOG_INFO, " %08X", plane_checksum[plane]); av_log(ctx, AV_LOG_INFO, "]\n"); return ff_filter_frame(inlink->dst->outputs[0], frame); }
166,007
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int set_register(pegasus_t *pegasus, __u16 indx, __u8 data) { int ret; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REG, PEGASUS_REQT_WRITE, data, indx, &data, 1, 1000); 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_register(pegasus_t *pegasus, __u16 indx, __u8 data) { u8 *buf; int ret; buf = kmemdup(&data, 1, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REG, PEGASUS_REQT_WRITE, data, indx, buf, 1, 1000); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); kfree(buf); return ret; }
168,217
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NTPResourceCache::CreateNewTabHTML() { DictionaryValue localized_strings; localized_strings.SetString("bookmarkbarattached", profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) ? "true" : "false"); localized_strings.SetString("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION) ? "true" : "false"); localized_strings.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); localized_strings.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); localized_strings.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); localized_strings.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); localized_strings.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); localized_strings.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); localized_strings.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); localized_strings.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); localized_strings.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); localized_strings.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); localized_strings.SetString("appuninstall", l10n_util::GetStringFUTF16( IDS_EXTENSIONS_UNINSTALL, l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME))); localized_strings.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); localized_strings.SetString("appdisablenotifications", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DISABLE_NOTIFICATIONS)); localized_strings.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); localized_strings.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); localized_strings.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); localized_strings.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); localized_strings.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); localized_strings.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); localized_strings.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); localized_strings.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); #if defined(OS_CHROMEOS) localized_strings.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &localized_strings); NTPLoginHandler::GetLocalizedValues(profile_, &localized_strings); if (profile_->GetProfileSyncService()) localized_strings.SetString("syncispresent", "true"); else localized_strings.SetString("syncispresent", "false"); ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings); std::string anim = ui::Animation::ShouldRenderRichAnimation() ? "true" : "false"; localized_strings.SetString("anim", anim); int alignment; ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); tp->GetDisplayProperty(ThemeService::NTP_BACKGROUND_ALIGNMENT, &alignment); localized_strings.SetString("themegravity", (alignment & ThemeService::ALIGN_RIGHT) ? "right" : ""); if (profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoStart) && profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoEnd)) { localized_strings.SetString("customlogo", InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoStart), profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoEnd)) ? "true" : "false"); } else { localized_strings.SetString("customlogo", "false"); } if (PromoResourceService::CanShowNotificationPromo(profile_)) { localized_strings.SetString("serverpromo", profile_->GetPrefs()->GetString(prefs::kNTPPromoLine)); } std::string full_html; base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); full_html = jstemplate_builder::GetI18nTemplateHtml(new_tab_html, &localized_strings); new_tab_html_ = base::RefCountedString::TakeString(&full_html); } Commit Message: [i18n-fixlet] Make strings branding specific in extension code. IDS_EXTENSIONS_UNINSTALL IDS_EXTENSIONS_INCOGNITO_WARNING IDS_EXTENSION_INSTALLED_HEADING IDS_EXTENSION_ALERT_ITEM_EXTERNAL And fix a $1 $1 bug. IDS_EXTENSION_INLINE_INSTALL_PROMPT_TITLE BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/9107061 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@118018 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void NTPResourceCache::CreateNewTabHTML() { DictionaryValue localized_strings; localized_strings.SetString("bookmarkbarattached", profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) ? "true" : "false"); localized_strings.SetString("hasattribution", ThemeServiceFactory::GetForProfile(profile_)->HasCustomImage( IDR_THEME_NTP_ATTRIBUTION) ? "true" : "false"); localized_strings.SetString("title", l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); localized_strings.SetString("mostvisited", l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)); localized_strings.SetString("restoreThumbnailsShort", l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_SHORT_LINK)); localized_strings.SetString("recentlyclosed", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); localized_strings.SetString("closedwindowsingle", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); localized_strings.SetString("closedwindowmultiple", l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); localized_strings.SetString("attributionintro", l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); localized_strings.SetString("thumbnailremovednotification", l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); localized_strings.SetString("undothumbnailremove", l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); localized_strings.SetString("removethumbnailtooltip", l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); localized_strings.SetString("appuninstall", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UNINSTALL)); localized_strings.SetString("appoptions", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); localized_strings.SetString("appdisablenotifications", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_DISABLE_NOTIFICATIONS)); localized_strings.SetString("appcreateshortcut", l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); localized_strings.SetString("appDefaultPageName", l10n_util::GetStringUTF16(IDS_APP_DEFAULT_PAGE_NAME)); localized_strings.SetString("applaunchtypepinned", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); localized_strings.SetString("applaunchtyperegular", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); localized_strings.SetString("applaunchtypewindow", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); localized_strings.SetString("applaunchtypefullscreen", l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); localized_strings.SetString("syncpromotext", l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); localized_strings.SetString("syncLinkText", l10n_util::GetStringUTF16(IDS_SYNC_ADVANCED_OPTIONS)); #if defined(OS_CHROMEOS) localized_strings.SetString("expandMenu", l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); #endif NewTabPageHandler::GetLocalizedValues(profile_, &localized_strings); NTPLoginHandler::GetLocalizedValues(profile_, &localized_strings); if (profile_->GetProfileSyncService()) localized_strings.SetString("syncispresent", "true"); else localized_strings.SetString("syncispresent", "false"); ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings); std::string anim = ui::Animation::ShouldRenderRichAnimation() ? "true" : "false"; localized_strings.SetString("anim", anim); int alignment; ui::ThemeProvider* tp = ThemeServiceFactory::GetForProfile(profile_); tp->GetDisplayProperty(ThemeService::NTP_BACKGROUND_ALIGNMENT, &alignment); localized_strings.SetString("themegravity", (alignment & ThemeService::ALIGN_RIGHT) ? "right" : ""); if (profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoStart) && profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoEnd)) { localized_strings.SetString("customlogo", InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoStart), profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoEnd)) ? "true" : "false"); } else { localized_strings.SetString("customlogo", "false"); } if (PromoResourceService::CanShowNotificationPromo(profile_)) { localized_strings.SetString("serverpromo", profile_->GetPrefs()->GetString(prefs::kNTPPromoLine)); } std::string full_html; base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). GetRawDataResource(IDR_NEW_TAB_4_HTML)); full_html = jstemplate_builder::GetI18nTemplateHtml(new_tab_html, &localized_strings); new_tab_html_ = base::RefCountedString::TakeString(&full_html); }
170,985
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rio_ioctl (struct net_device *dev, struct ifreq *rq, int cmd) { int phy_addr; struct netdev_private *np = netdev_priv(dev); struct mii_data *miidata = (struct mii_data *) &rq->ifr_ifru; struct netdev_desc *desc; int i; phy_addr = np->phy_addr; switch (cmd) { case SIOCDEVPRIVATE: break; case SIOCDEVPRIVATE + 1: miidata->out_value = mii_read (dev, phy_addr, miidata->reg_num); break; case SIOCDEVPRIVATE + 2: mii_write (dev, phy_addr, miidata->reg_num, miidata->in_value); break; case SIOCDEVPRIVATE + 3: break; case SIOCDEVPRIVATE + 4: break; case SIOCDEVPRIVATE + 5: netif_stop_queue (dev); break; case SIOCDEVPRIVATE + 6: netif_wake_queue (dev); break; case SIOCDEVPRIVATE + 7: printk ("tx_full=%x cur_tx=%lx old_tx=%lx cur_rx=%lx old_rx=%lx\n", netif_queue_stopped(dev), np->cur_tx, np->old_tx, np->cur_rx, np->old_rx); break; case SIOCDEVPRIVATE + 8: printk("TX ring:\n"); for (i = 0; i < TX_RING_SIZE; i++) { desc = &np->tx_ring[i]; printk ("%02x:cur:%08x next:%08x status:%08x frag1:%08x frag0:%08x", i, (u32) (np->tx_ring_dma + i * sizeof (*desc)), (u32)le64_to_cpu(desc->next_desc), (u32)le64_to_cpu(desc->status), (u32)(le64_to_cpu(desc->fraginfo) >> 32), (u32)le64_to_cpu(desc->fraginfo)); printk ("\n"); } printk ("\n"); break; default: return -EOPNOTSUPP; } return 0; } Commit Message: dl2k: Clean up rio_ioctl The dl2k driver's rio_ioctl call has a few issues: - No permissions checking - Implements SIOCGMIIREG and SIOCGMIIREG using the SIOCDEVPRIVATE numbers - Has a few ioctls that may have been used for debugging at one point but have no place in the kernel proper. This patch removes all but the MII ioctls, renumbers them to use the standard ones, and adds the proper permission check for SIOCSMIIREG. We can also get rid of the dl2k-specific struct mii_data in favor of the generic struct mii_ioctl_data. Since we have the phyid on hand, we can add the SIOCGMIIPHY ioctl too. Most of the MII code for the driver could probably be converted to use the generic MII library but I don't have a device to test the results. Reported-by: Stephan Mueller <[email protected]> Signed-off-by: Jeff Mahoney <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
rio_ioctl (struct net_device *dev, struct ifreq *rq, int cmd) { int phy_addr; struct netdev_private *np = netdev_priv(dev); struct mii_ioctl_data *miidata = if_mii(rq); phy_addr = np->phy_addr; switch (cmd) { case SIOCGMIIPHY: miidata->phy_id = phy_addr; break; case SIOCGMIIREG: miidata->val_out = mii_read (dev, phy_addr, miidata->reg_num); break; case SIOCSMIIREG: if (!capable(CAP_NET_ADMIN)) return -EPERM; mii_write (dev, phy_addr, miidata->reg_num, miidata->val_in); break; default: return -EOPNOTSUPP; } return 0; }
165,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DrawingBuffer::ScopedStateRestorer::~ScopedStateRestorer() { DCHECK_EQ(drawing_buffer_->state_restorer_, this); drawing_buffer_->state_restorer_ = previous_state_restorer_; Client* client = drawing_buffer_->client_; if (!client) return; if (clear_state_dirty_) { client->DrawingBufferClientRestoreScissorTest(); client->DrawingBufferClientRestoreMaskAndClearValues(); } if (pixel_pack_alignment_dirty_) client->DrawingBufferClientRestorePixelPackAlignment(); if (texture_binding_dirty_) client->DrawingBufferClientRestoreTexture2DBinding(); if (renderbuffer_binding_dirty_) client->DrawingBufferClientRestoreRenderbufferBinding(); if (framebuffer_binding_dirty_) client->DrawingBufferClientRestoreFramebufferBinding(); if (pixel_unpack_buffer_binding_dirty_) client->DrawingBufferClientRestorePixelUnpackBufferBinding(); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
DrawingBuffer::ScopedStateRestorer::~ScopedStateRestorer() { DCHECK_EQ(drawing_buffer_->state_restorer_, this); drawing_buffer_->state_restorer_ = previous_state_restorer_; Client* client = drawing_buffer_->client_; if (!client) return; if (clear_state_dirty_) { client->DrawingBufferClientRestoreScissorTest(); client->DrawingBufferClientRestoreMaskAndClearValues(); } if (pixel_pack_parameters_dirty_) client->DrawingBufferClientRestorePixelPackParameters(); if (texture_binding_dirty_) client->DrawingBufferClientRestoreTexture2DBinding(); if (renderbuffer_binding_dirty_) client->DrawingBufferClientRestoreRenderbufferBinding(); if (framebuffer_binding_dirty_) client->DrawingBufferClientRestoreFramebufferBinding(); if (pixel_unpack_buffer_binding_dirty_) client->DrawingBufferClientRestorePixelUnpackBufferBinding(); if (pixel_pack_buffer_binding_dirty_) client->DrawingBufferClientRestorePixelPackBufferBinding(); }
172,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static FILE *open_log_file(void) { if(log_fp) /* keep it open unless we rotate */ return log_fp; log_fp = fopen(log_file, "a+"); if(log_fp == NULL) { if (daemon_mode == FALSE) { printf("Warning: Cannot open log file '%s' for writing\n", log_file); } return NULL; } (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC); return log_fp; } Commit Message: Merge branch 'maint' CWE ID: CWE-264
static FILE *open_log_file(void) { int fh; struct stat st; if(log_fp) /* keep it open unless we rotate */ return log_fp; if ((fh = open(log_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1) { if (daemon_mode == FALSE) printf("Warning: Cannot open log file '%s' for writing\n", log_file); return NULL; } log_fp = fdopen(fh, "a+"); if(log_fp == NULL) { if (daemon_mode == FALSE) printf("Warning: Cannot open log file '%s' for writing\n", log_file); return NULL; } if ((fstat(fh, &st)) == -1) { log_fp = NULL; close(fh); if (daemon_mode == FALSE) printf("Warning: Cannot fstat log file '%s'\n", log_file); return NULL; } if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) { log_fp = NULL; close(fh); if (daemon_mode == FALSE) printf("Warning: log file '%s' has an invalid mode\n", log_file); return NULL; } (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC); return log_fp; }
166,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) { HEVCLocalContext *lc = s->HEVClc; GetBitContext *gb = &lc->gb; int ctb_addr_ts, ret; *gb = nal->gb; s->nal_unit_type = nal->type; s->temporal_id = nal->temporal_id; switch (s->nal_unit_type) { case HEVC_NAL_VPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps, s->apply_defdispwin); if (ret < 0) goto fail; break; case HEVC_NAL_PPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SEI_PREFIX: case HEVC_NAL_SEI_SUFFIX: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type); if (ret < 0) goto fail; break; case HEVC_NAL_TRAIL_R: case HEVC_NAL_TRAIL_N: case HEVC_NAL_TSA_N: case HEVC_NAL_TSA_R: case HEVC_NAL_STSA_N: case HEVC_NAL_STSA_R: case HEVC_NAL_BLA_W_LP: case HEVC_NAL_BLA_W_RADL: case HEVC_NAL_BLA_N_LP: case HEVC_NAL_IDR_W_RADL: case HEVC_NAL_IDR_N_LP: case HEVC_NAL_CRA_NUT: case HEVC_NAL_RADL_N: case HEVC_NAL_RADL_R: case HEVC_NAL_RASL_N: case HEVC_NAL_RASL_R: ret = hls_slice_header(s); if (ret < 0) return ret; if ( (s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) || (s->avctx->skip_frame >= AVDISCARD_NONINTRA && s->sh.slice_type != HEVC_SLICE_I) || (s->avctx->skip_frame >= AVDISCARD_NONKEY && !IS_IRAP(s))) { break; } if (s->sh.first_slice_in_pic_flag) { if (s->ref) { av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n"); goto fail; } if (s->max_ra == INT_MAX) { if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) { s->max_ra = s->poc; } else { if (IS_IDR(s)) s->max_ra = INT_MIN; } } if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) && s->poc <= s->max_ra) { s->is_decoded = 0; break; } else { if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra) s->max_ra = INT_MIN; } s->overlap ++; ret = hevc_frame_start(s); if (ret < 0) return ret; } else if (!s->ref) { av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n"); goto fail; } if (s->nal_unit_type != s->first_nal_type) { av_log(s->avctx, AV_LOG_ERROR, "Non-matching NAL types of the VCL NALUs: %d %d\n", s->first_nal_type, s->nal_unit_type); return AVERROR_INVALIDDATA; } if (!s->sh.dependent_slice_segment_flag && s->sh.slice_type != HEVC_SLICE_I) { ret = ff_hevc_slice_rpl(s); if (ret < 0) { av_log(s->avctx, AV_LOG_WARNING, "Error constructing the reference lists for the current slice.\n"); goto fail; } } if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) { ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0); if (ret < 0) goto fail; } if (s->avctx->hwaccel) { ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } else { if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0) ctb_addr_ts = hls_slice_data_wpp(s, nal); else ctb_addr_ts = hls_slice_data(s); if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) { s->is_decoded = 1; } if (ctb_addr_ts < 0) { ret = ctb_addr_ts; goto fail; } } break; case HEVC_NAL_EOS_NUT: case HEVC_NAL_EOB_NUT: s->seq_decode = (s->seq_decode + 1) & 0xff; s->max_ra = INT_MAX; break; case HEVC_NAL_AUD: case HEVC_NAL_FD_NUT: break; default: av_log(s->avctx, AV_LOG_INFO, "Skipping NAL unit %d\n", s->nal_unit_type); } return 0; fail: if (s->avctx->err_recognition & AV_EF_EXPLODE) return ret; return 0; } Commit Message: avcodec/hevcdec: Avoid only partly skiping duplicate first slices Fixes: NULL pointer dereference and out of array access Fixes: 13871/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5746167087890432 Fixes: 13845/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5650370728034304 This also fixes the return code for explode mode Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Reviewed-by: James Almer <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-476
static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) { HEVCLocalContext *lc = s->HEVClc; GetBitContext *gb = &lc->gb; int ctb_addr_ts, ret; *gb = nal->gb; s->nal_unit_type = nal->type; s->temporal_id = nal->temporal_id; switch (s->nal_unit_type) { case HEVC_NAL_VPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_vps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sps(gb, s->avctx, &s->ps, s->apply_defdispwin); if (ret < 0) goto fail; break; case HEVC_NAL_PPS: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_pps(gb, s->avctx, &s->ps); if (ret < 0) goto fail; break; case HEVC_NAL_SEI_PREFIX: case HEVC_NAL_SEI_SUFFIX: if (s->avctx->hwaccel && s->avctx->hwaccel->decode_params) { ret = s->avctx->hwaccel->decode_params(s->avctx, nal->type, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } ret = ff_hevc_decode_nal_sei(gb, s->avctx, &s->sei, &s->ps, s->nal_unit_type); if (ret < 0) goto fail; break; case HEVC_NAL_TRAIL_R: case HEVC_NAL_TRAIL_N: case HEVC_NAL_TSA_N: case HEVC_NAL_TSA_R: case HEVC_NAL_STSA_N: case HEVC_NAL_STSA_R: case HEVC_NAL_BLA_W_LP: case HEVC_NAL_BLA_W_RADL: case HEVC_NAL_BLA_N_LP: case HEVC_NAL_IDR_W_RADL: case HEVC_NAL_IDR_N_LP: case HEVC_NAL_CRA_NUT: case HEVC_NAL_RADL_N: case HEVC_NAL_RADL_R: case HEVC_NAL_RASL_N: case HEVC_NAL_RASL_R: ret = hls_slice_header(s); if (ret < 0) return ret; if (ret == 1) { ret = AVERROR_INVALIDDATA; goto fail; } if ( (s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) || (s->avctx->skip_frame >= AVDISCARD_NONINTRA && s->sh.slice_type != HEVC_SLICE_I) || (s->avctx->skip_frame >= AVDISCARD_NONKEY && !IS_IRAP(s))) { break; } if (s->sh.first_slice_in_pic_flag) { if (s->max_ra == INT_MAX) { if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) { s->max_ra = s->poc; } else { if (IS_IDR(s)) s->max_ra = INT_MIN; } } if ((s->nal_unit_type == HEVC_NAL_RASL_R || s->nal_unit_type == HEVC_NAL_RASL_N) && s->poc <= s->max_ra) { s->is_decoded = 0; break; } else { if (s->nal_unit_type == HEVC_NAL_RASL_R && s->poc > s->max_ra) s->max_ra = INT_MIN; } s->overlap ++; ret = hevc_frame_start(s); if (ret < 0) return ret; } else if (!s->ref) { av_log(s->avctx, AV_LOG_ERROR, "First slice in a frame missing.\n"); goto fail; } if (s->nal_unit_type != s->first_nal_type) { av_log(s->avctx, AV_LOG_ERROR, "Non-matching NAL types of the VCL NALUs: %d %d\n", s->first_nal_type, s->nal_unit_type); return AVERROR_INVALIDDATA; } if (!s->sh.dependent_slice_segment_flag && s->sh.slice_type != HEVC_SLICE_I) { ret = ff_hevc_slice_rpl(s); if (ret < 0) { av_log(s->avctx, AV_LOG_WARNING, "Error constructing the reference lists for the current slice.\n"); goto fail; } } if (s->sh.first_slice_in_pic_flag && s->avctx->hwaccel) { ret = s->avctx->hwaccel->start_frame(s->avctx, NULL, 0); if (ret < 0) goto fail; } if (s->avctx->hwaccel) { ret = s->avctx->hwaccel->decode_slice(s->avctx, nal->raw_data, nal->raw_size); if (ret < 0) goto fail; } else { if (s->threads_number > 1 && s->sh.num_entry_point_offsets > 0) ctb_addr_ts = hls_slice_data_wpp(s, nal); else ctb_addr_ts = hls_slice_data(s); if (ctb_addr_ts >= (s->ps.sps->ctb_width * s->ps.sps->ctb_height)) { s->is_decoded = 1; } if (ctb_addr_ts < 0) { ret = ctb_addr_ts; goto fail; } } break; case HEVC_NAL_EOS_NUT: case HEVC_NAL_EOB_NUT: s->seq_decode = (s->seq_decode + 1) & 0xff; s->max_ra = INT_MAX; break; case HEVC_NAL_AUD: case HEVC_NAL_FD_NUT: break; default: av_log(s->avctx, AV_LOG_INFO, "Skipping NAL unit %d\n", s->nal_unit_type); } return 0; fail: if (s->avctx->err_recognition & AV_EF_EXPLODE) return ret; return 0; }
169,706
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InputMethodDescriptors* GetInputMethodDescriptorsForTesting() { InputMethodDescriptors* descriptions = new InputMethodDescriptors; descriptions->push_back(InputMethodDescriptor( "xkb:nl::nld", "Netherlands", "nl", "nl", "nld")); descriptions->push_back(InputMethodDescriptor( "xkb:be::nld", "Belgium", "be", "be", "nld")); descriptions->push_back(InputMethodDescriptor( "xkb:fr::fra", "France", "fr", "fr", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:be::fra", "Belgium", "be", "be", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:ca::fra", "Canada", "ca", "ca", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "ch(fr)", "fra")); descriptions->push_back(InputMethodDescriptor( "xkb:de::ger", "Germany", "de", "de", "ger")); descriptions->push_back(InputMethodDescriptor( "xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "de(neo)", "ger")); descriptions->push_back(InputMethodDescriptor( "xkb:be::ger", "Belgium", "be", "be", "ger")); descriptions->push_back(InputMethodDescriptor( "xkb:ch::ger", "Switzerland", "ch", "ch", "ger")); descriptions->push_back(InputMethodDescriptor( "mozc", "Mozc (US keyboard layout)", "us", "us", "ja")); descriptions->push_back(InputMethodDescriptor( "mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "jp", "ja")); descriptions->push_back(InputMethodDescriptor( "mozc-dv", "Mozc (US Dvorak keyboard layout)", "us(dvorak)", "us(dvorak)", "ja")); descriptions->push_back(InputMethodDescriptor( "xkb:jp::jpn", "Japan", "jp", "jp", "jpn")); descriptions->push_back(InputMethodDescriptor( "xkb:ru::rus", "Russia", "ru", "ru", "rus")); descriptions->push_back(InputMethodDescriptor( "xkb:ru:phonetic:rus", "Russia - Phonetic", "ru(phonetic)", "ru(phonetic)", "rus")); descriptions->push_back(InputMethodDescriptor( "m17n:th:kesmanee", "kesmanee (m17n)", "us", "us", "th")); descriptions->push_back(InputMethodDescriptor( "m17n:th:pattachote", "pattachote (m17n)", "us", "us", "th")); descriptions->push_back(InputMethodDescriptor( "m17n:th:tis820", "tis820 (m17n)", "us", "us", "th")); descriptions->push_back(InputMethodDescriptor( "mozc-chewing", "Mozc Chewing (Chewing)", "us", "us", "zh_TW")); descriptions->push_back(InputMethodDescriptor( "m17n:zh:cangjie", "cangjie (m17n)", "us", "us", "zh")); descriptions->push_back(InputMethodDescriptor( "m17n:zh:quick", "quick (m17n)", "us", "us", "zh")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:tcvn", "tcvn (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:telex", "telex (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:viqr", "viqr (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "m17n:vi:vni", "vni (m17n)", "us", "us", "vi")); descriptions->push_back(InputMethodDescriptor( "xkb:us::eng", "USA", "us", "us", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:intl:eng", "USA - International (with dead keys)", "us(intl)", "us(intl)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:altgr-intl:eng", "USA - International (AltGr dead keys)", "us(altgr-intl)", "us(altgr-intl)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:dvorak:eng", "USA - Dvorak", "us(dvorak)", "us(dvorak)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:us:colemak:eng", "USA - Colemak", "us(colemak)", "us(colemak)", "eng")); descriptions->push_back(InputMethodDescriptor( "hangul", "Korean", "kr(kr104)", "kr(kr104)", "ko")); descriptions->push_back(InputMethodDescriptor( "pinyin", "Pinyin", "us", "us", "zh")); descriptions->push_back(InputMethodDescriptor( "pinyin-dv", "Pinyin (for US Dvorak keyboard)", "us(dvorak)", "us(dvorak)", "zh")); descriptions->push_back(InputMethodDescriptor( "m17n:ar:kbd", "kbd (m17n)", "us", "us", "ar")); descriptions->push_back(InputMethodDescriptor( "m17n:hi:itrans", "itrans (m17n)", "us", "us", "hi")); descriptions->push_back(InputMethodDescriptor( "m17n:fa:isiri", "isiri (m17n)", "us", "us", "fa")); descriptions->push_back(InputMethodDescriptor( "xkb:br::por", "Brazil", "br", "br", "por")); descriptions->push_back(InputMethodDescriptor( "xkb:bg::bul", "Bulgaria", "bg", "bg", "bul")); descriptions->push_back(InputMethodDescriptor( "xkb:bg:phonetic:bul", "Bulgaria - Traditional phonetic", "bg(phonetic)", "bg(phonetic)", "bul")); descriptions->push_back(InputMethodDescriptor( "xkb:ca:eng:eng", "Canada - English", "ca(eng)", "ca(eng)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:cz::cze", "Czechia", "cz", "cz", "cze")); descriptions->push_back(InputMethodDescriptor( "xkb:ee::est", "Estonia", "ee", "ee", "est")); descriptions->push_back(InputMethodDescriptor( "xkb:es::spa", "Spain", "es", "es", "spa")); descriptions->push_back(InputMethodDescriptor( "xkb:es:cat:cat", "Spain - Catalan variant with middle-dot L", "es(cat)", "es(cat)", "cat")); descriptions->push_back(InputMethodDescriptor( "xkb:dk::dan", "Denmark", "dk", "dk", "dan")); descriptions->push_back(InputMethodDescriptor( "xkb:gr::gre", "Greece", "gr", "gr", "gre")); descriptions->push_back(InputMethodDescriptor( "xkb:il::heb", "Israel", "il", "il", "heb")); descriptions->push_back(InputMethodDescriptor( "xkb:kr:kr104:kor", "Korea, Republic of - 101/104 key Compatible", "kr(kr104)", "kr(kr104)", "kor")); descriptions->push_back(InputMethodDescriptor( "xkb:latam::spa", "Latin American", "latam", "latam", "spa")); descriptions->push_back(InputMethodDescriptor( "xkb:lt::lit", "Lithuania", "lt", "lt", "lit")); descriptions->push_back(InputMethodDescriptor( "xkb:lv:apostrophe:lav", "Latvia - Apostrophe (') variant", "lv(apostrophe)", "lv(apostrophe)", "lav")); descriptions->push_back(InputMethodDescriptor( "xkb:hr::scr", "Croatia", "hr", "hr", "scr")); descriptions->push_back(InputMethodDescriptor( "xkb:gb:extd:eng", "United Kingdom - Extended - Winkeys", "gb(extd)", "gb(extd)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:gb:dvorak:eng", "United Kingdom - Dvorak", "gb(dvorak)", "gb(dvorak)", "eng")); descriptions->push_back(InputMethodDescriptor( "xkb:fi::fin", "Finland", "fi", "fi", "fin")); descriptions->push_back(InputMethodDescriptor( "xkb:hu::hun", "Hungary", "hu", "hu", "hun")); descriptions->push_back(InputMethodDescriptor( "xkb:it::ita", "Italy", "it", "it", "ita")); descriptions->push_back(InputMethodDescriptor( "xkb:no::nob", "Norway", "no", "no", "nob")); descriptions->push_back(InputMethodDescriptor( "xkb:pl::pol", "Poland", "pl", "pl", "pol")); descriptions->push_back(InputMethodDescriptor( "xkb:pt::por", "Portugal", "pt", "pt", "por")); descriptions->push_back(InputMethodDescriptor( "xkb:ro::rum", "Romania", "ro", "ro", "rum")); descriptions->push_back(InputMethodDescriptor( "xkb:se::swe", "Sweden", "se", "se", "swe")); descriptions->push_back(InputMethodDescriptor( "xkb:sk::slo", "Slovakia", "sk", "sk", "slo")); descriptions->push_back(InputMethodDescriptor( "xkb:si::slv", "Slovenia", "si", "si", "slv")); descriptions->push_back(InputMethodDescriptor( "xkb:rs::srp", "Serbia", "rs", "rs", "srp")); descriptions->push_back(InputMethodDescriptor( "xkb:tr::tur", "Turkey", "tr", "tr", "tur")); descriptions->push_back(InputMethodDescriptor( "xkb:ua::ukr", "Ukraine", "ua", "ua", "ukr")); return descriptions; } 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
InputMethodDescriptors* GetInputMethodDescriptorsForTesting() { input_method::InputMethodDescriptors* GetInputMethodDescriptorsForTesting() { input_method::InputMethodDescriptors* descriptions = new input_method::InputMethodDescriptors; descriptions->push_back(input_method::InputMethodDescriptor( "xkb:nl::nld", "Netherlands", "nl", "nl", "nld")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:be::nld", "Belgium", "be", "be", "nld")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:fr::fra", "France", "fr", "fr", "fra")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:be::fra", "Belgium", "be", "be", "fra")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ca::fra", "Canada", "ca", "ca", "fra")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ch:fr:fra", "Switzerland - French", "ch(fr)", "ch(fr)", "fra")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:de::ger", "Germany", "de", "de", "ger")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:de:neo:ger", "Germany - Neo 2", "de(neo)", "de(neo)", "ger")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:be::ger", "Belgium", "be", "be", "ger")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ch::ger", "Switzerland", "ch", "ch", "ger")); descriptions->push_back(input_method::InputMethodDescriptor( "mozc", "Mozc (US keyboard layout)", "us", "us", "ja")); descriptions->push_back(input_method::InputMethodDescriptor( "mozc-jp", "Mozc (Japanese keyboard layout)", "jp", "jp", "ja")); descriptions->push_back(input_method::InputMethodDescriptor( "mozc-dv", "Mozc (US Dvorak keyboard layout)", "us(dvorak)", "us(dvorak)", "ja")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:jp::jpn", "Japan", "jp", "jp", "jpn")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ru::rus", "Russia", "ru", "ru", "rus")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ru:phonetic:rus", "Russia - Phonetic", "ru(phonetic)", "ru(phonetic)", "rus")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:th:kesmanee", "kesmanee (m17n)", "us", "us", "th")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:th:pattachote", "pattachote (m17n)", "us", "us", "th")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:th:tis820", "tis820 (m17n)", "us", "us", "th")); descriptions->push_back(input_method::InputMethodDescriptor( "mozc-chewing", "Mozc Chewing (Chewing)", "us", "us", "zh_TW")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:zh:cangjie", "cangjie (m17n)", "us", "us", "zh")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:zh:quick", "quick (m17n)", "us", "us", "zh")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:vi:tcvn", "tcvn (m17n)", "us", "us", "vi")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:vi:telex", "telex (m17n)", "us", "us", "vi")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:vi:viqr", "viqr (m17n)", "us", "us", "vi")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:vi:vni", "vni (m17n)", "us", "us", "vi")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:us::eng", "USA", "us", "us", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:us:intl:eng", "USA - International (with dead keys)", "us(intl)", "us(intl)", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:us:altgr-intl:eng", "USA - International (AltGr dead keys)", "us(altgr-intl)", "us(altgr-intl)", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:us:dvorak:eng", "USA - Dvorak", "us(dvorak)", "us(dvorak)", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:us:colemak:eng", "USA - Colemak", "us(colemak)", "us(colemak)", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "hangul", "Korean", "kr(kr104)", "kr(kr104)", "ko")); descriptions->push_back(input_method::InputMethodDescriptor( "pinyin", "Pinyin", "us", "us", "zh")); descriptions->push_back(input_method::InputMethodDescriptor( "pinyin-dv", "Pinyin (for US Dvorak keyboard)", "us(dvorak)", "us(dvorak)", "zh")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:ar:kbd", "kbd (m17n)", "us", "us", "ar")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:hi:itrans", "itrans (m17n)", "us", "us", "hi")); descriptions->push_back(input_method::InputMethodDescriptor( "m17n:fa:isiri", "isiri (m17n)", "us", "us", "fa")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:br::por", "Brazil", "br", "br", "por")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:bg::bul", "Bulgaria", "bg", "bg", "bul")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:bg:phonetic:bul", "Bulgaria - Traditional phonetic", "bg(phonetic)", "bg(phonetic)", "bul")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ca:eng:eng", "Canada - English", "ca(eng)", "ca(eng)", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:cz::cze", "Czechia", "cz", "cz", "cze")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ee::est", "Estonia", "ee", "ee", "est")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:es::spa", "Spain", "es", "es", "spa")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:es:cat:cat", "Spain - Catalan variant with middle-dot L", "es(cat)", "es(cat)", "cat")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:dk::dan", "Denmark", "dk", "dk", "dan")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:gr::gre", "Greece", "gr", "gr", "gre")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:il::heb", "Israel", "il", "il", "heb")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:kr:kr104:kor", "Korea, Republic of - 101/104 key Compatible", "kr(kr104)", "kr(kr104)", "kor")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:latam::spa", "Latin American", "latam", "latam", "spa")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:lt::lit", "Lithuania", "lt", "lt", "lit")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:lv:apostrophe:lav", "Latvia - Apostrophe (') variant", "lv(apostrophe)", "lv(apostrophe)", "lav")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:hr::scr", "Croatia", "hr", "hr", "scr")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:gb:extd:eng", "United Kingdom - Extended - Winkeys", "gb(extd)", "gb(extd)", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:gb:dvorak:eng", "United Kingdom - Dvorak", "gb(dvorak)", "gb(dvorak)", "eng")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:fi::fin", "Finland", "fi", "fi", "fin")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:hu::hun", "Hungary", "hu", "hu", "hun")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:it::ita", "Italy", "it", "it", "ita")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:no::nob", "Norway", "no", "no", "nob")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:pl::pol", "Poland", "pl", "pl", "pol")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:pt::por", "Portugal", "pt", "pt", "por")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ro::rum", "Romania", "ro", "ro", "rum")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:se::swe", "Sweden", "se", "se", "swe")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:sk::slo", "Slovakia", "sk", "sk", "slo")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:si::slv", "Slovenia", "si", "si", "slv")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:rs::srp", "Serbia", "rs", "rs", "srp")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:tr::tur", "Turkey", "tr", "tr", "tur")); descriptions->push_back(input_method::InputMethodDescriptor( "xkb:ua::ukr", "Ukraine", "ua", "ua", "ukr")); return descriptions; }
170,488
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int PrintPreviewDataService::GetAvailableDraftPageCount( const std::string& preview_ui_addr_str) { if (data_store_map_.find(preview_ui_addr_str) != data_store_map_.end()) return data_store_map_[preview_ui_addr_str]->GetAvailableDraftPageCount(); return 0; } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
int PrintPreviewDataService::GetAvailableDraftPageCount( int PrintPreviewDataService::GetAvailableDraftPageCount(int32 preview_ui_id) { PreviewDataStoreMap::const_iterator it = data_store_map_.find(preview_ui_id); return (it == data_store_map_.end()) ? 0 : it->second->GetAvailableDraftPageCount(); }
170,820
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void get_frame_stats(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, vpx_fixed_buf_t *stats) { vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to get frame stats."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { if (pkt->kind == VPX_CODEC_STATS_PKT) { const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf; const size_t pkt_size = pkt->data.twopass_stats.sz; stats->buf = realloc(stats->buf, stats->sz + pkt_size); memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size); stats->sz += pkt_size; } } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static void get_frame_stats(vpx_codec_ctx_t *ctx, static int get_frame_stats(vpx_codec_ctx_t *ctx, const vpx_image_t *img, vpx_codec_pts_t pts, unsigned int duration, vpx_enc_frame_flags_t flags, unsigned int deadline, vpx_fixed_buf_t *stats) { int got_pkts = 0; vpx_codec_iter_t iter = NULL; const vpx_codec_cx_pkt_t *pkt = NULL; const vpx_codec_err_t res = vpx_codec_encode(ctx, img, pts, duration, flags, deadline); if (res != VPX_CODEC_OK) die_codec(ctx, "Failed to get frame stats."); while ((pkt = vpx_codec_get_cx_data(ctx, &iter)) != NULL) { got_pkts = 1; if (pkt->kind == VPX_CODEC_STATS_PKT) { const uint8_t *const pkt_buf = pkt->data.twopass_stats.buf; const size_t pkt_size = pkt->data.twopass_stats.sz; stats->buf = realloc(stats->buf, stats->sz + pkt_size); memcpy((uint8_t *)stats->buf + stats->sz, pkt_buf, pkt_size); stats->sz += pkt_size; } } return got_pkts; }
174,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IW_IMPL(int) iw_get_input_density(struct iw_context *ctx, double *px, double *py, int *pcode) { *px = 1.0; *py = 1.0; *pcode = ctx->img1.density_code; if(ctx->img1.density_code!=IW_DENSITY_UNKNOWN) { *px = ctx->img1.density_x; *py = ctx->img1.density_y; return 1; } return 0; } Commit Message: Double-check that the input image's density is valid Fixes a bug that could result in division by zero, at least for a JPEG source image. Fixes issues #19, #20 CWE ID: CWE-369
IW_IMPL(int) iw_get_input_density(struct iw_context *ctx, double *px, double *py, int *pcode) { *px = 1.0; *py = 1.0; *pcode = IW_DENSITY_UNKNOWN; if(ctx->img1.density_code==IW_DENSITY_UNKNOWN) { return 0; } if(!iw_is_valid_density(ctx->img1.density_x, ctx->img1.density_y, ctx->img1.density_code)) { return 0; } *px = ctx->img1.density_x; *py = ctx->img1.density_y; *pcode = ctx->img1.density_code; return 1; }
168,119
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mrb_class_real(struct RClass* cl) { if (cl == 0) return NULL; while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) { cl = cl->super; } return cl; } Commit Message: `mrb_class_real()` did not work for `BasicObject`; fix #4037 CWE ID: CWE-476
mrb_class_real(struct RClass* cl) { if (cl == 0) return NULL; while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) { cl = cl->super; if (cl == 0) return NULL; } return cl; }
169,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 )); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; return chr; } Commit Message: New Pre Source CWE ID: CWE-119
SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return NULL; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 )); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; return chr; }
169,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mcs_recv_connect_response(STREAM mcs_data) { UNUSED(mcs_data); uint8 result; int length; STREAM s; RD_BOOL is_fastpath; uint8 fastpath_hdr; logger(Protocol, Debug, "%s()", __func__); s = iso_recv(&is_fastpath, &fastpath_hdr); if (s == NULL) return False; ber_parse_header(s, MCS_CONNECT_RESPONSE, &length); ber_parse_header(s, BER_TAG_RESULT, &length); in_uint8(s, result); if (result != 0) { logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result); return False; } ber_parse_header(s, BER_TAG_INTEGER, &length); in_uint8s(s, length); /* connect id */ mcs_parse_domain_params(s); ber_parse_header(s, BER_TAG_OCTET_STRING, &length); sec_process_mcs_data(s); /* if (length > mcs_data->size) { logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size); length = mcs_data->size; } in_uint8a(s, mcs_data->data, length); mcs_data->p = mcs_data->data; mcs_data->end = mcs_data->data + length; */ return s_check_end(s); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
mcs_recv_connect_response(STREAM mcs_data) { UNUSED(mcs_data); uint8 result; uint32 length; STREAM s; struct stream packet; RD_BOOL is_fastpath; uint8 fastpath_hdr; logger(Protocol, Debug, "%s()", __func__); s = iso_recv(&is_fastpath, &fastpath_hdr); if (s == NULL) return False; packet = *s; ber_parse_header(s, MCS_CONNECT_RESPONSE, &length); ber_parse_header(s, BER_TAG_RESULT, &length); in_uint8(s, result); if (result != 0) { logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result); return False; } ber_parse_header(s, BER_TAG_INTEGER, &length); in_uint8s(s, length); /* connect id */ if (!s_check_rem(s, length)) { rdp_protocol_error("mcs_recv_connect_response(), consume connect id from stream would overrun", &packet); } mcs_parse_domain_params(s); ber_parse_header(s, BER_TAG_OCTET_STRING, &length); sec_process_mcs_data(s); /* if (length > mcs_data->size) { logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size); length = mcs_data->size; } in_uint8a(s, mcs_data->data, length); mcs_data->p = mcs_data->data; mcs_data->end = mcs_data->data + length; */ return s_check_end(s); }
169,800
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationWithCallWithAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithCallWith()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefCallWith(callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationWithCallWithAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithCallWith()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHrefCallWith(callingDOMWindow(info.GetIsolate()), enteredDOMWindow(info.GetIsolate()), cppValue); }
171,687
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: char *X509_NAME_oneline(X509_NAME *a, char *buf, int len) { X509_NAME_ENTRY *ne; int i; int n, lold, l, l1, l2, num, j, type; const char *s; char *p; unsigned char *q; BUF_MEM *b = NULL; static const char hex[17] = "0123456789ABCDEF"; int gs_doit[4]; char tmp_buf[80]; #ifdef CHARSET_EBCDIC char ebcdic_buf[1024]; #endif if (buf == NULL) { if ((b = BUF_MEM_new()) == NULL) goto err; if (!BUF_MEM_grow(b, 200)) goto err; b->data[0] = '\0'; len = 200; } else if (len == 0) { return NULL; } if (a == NULL) { if (b) { buf = b->data; OPENSSL_free(b); } strncpy(buf, "NO X509_NAME", len); buf[len - 1] = '\0'; return buf; } len--; /* space for '\0' */ l = 0; for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) { ne = sk_X509_NAME_ENTRY_value(a->entries, i); n = OBJ_obj2nid(ne->object); if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) { i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object); s = tmp_buf; } l1 = strlen(s); type = ne->value->type; num = ne->value->length; if (num > NAME_ONELINE_MAX) { X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG); goto end; } q = ne->value->data; #ifdef CHARSET_EBCDIC if (type == V_ASN1_GENERALSTRING || type == V_ASN1_VISIBLESTRING || type == V_ASN1_PRINTABLESTRING || type == V_ASN1_TELETEXSTRING || type == V_ASN1_VISIBLESTRING || type == V_ASN1_IA5STRING) { ascii2ebcdic(ebcdic_buf, q, (num > sizeof ebcdic_buf) ? sizeof ebcdic_buf : num); q = ebcdic_buf; } #endif if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) { gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0; for (j = 0; j < num; j++) if (q[j] != 0) gs_doit[j & 3] = 1; if (gs_doit[0] | gs_doit[1] | gs_doit[2]) gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1; else { gs_doit[0] = gs_doit[1] = gs_doit[2] = 0; gs_doit[3] = 1; } } else gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1; for (l2 = j = 0; j < num; j++) { if (!gs_doit[j & 3]) continue; l2++; #ifndef CHARSET_EBCDIC if ((q[j] < ' ') || (q[j] > '~')) l2 += 3; #else if ((os_toascii[q[j]] < os_toascii[' ']) || (os_toascii[q[j]] > os_toascii['~'])) l2 += 3; #endif } lold = l; l += 1 + l1 + 1 + l2; if (l > NAME_ONELINE_MAX) { X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG); goto end; } if (b != NULL) { if (!BUF_MEM_grow(b, l + 1)) goto err; p = &(b->data[lold]); } else if (l > len) { break; } else p = &(buf[lold]); *(p++) = '/'; memcpy(p, s, (unsigned int)l1); p += l1; *(p++) = '='; #ifndef CHARSET_EBCDIC /* q was assigned above already. */ q = ne->value->data; #endif for (j = 0; j < num; j++) { if (!gs_doit[j & 3]) continue; #ifndef CHARSET_EBCDIC n = q[j]; if ((n < ' ') || (n > '~')) { *(p++) = '\\'; *(p++) = 'x'; *(p++) = hex[(n >> 4) & 0x0f]; *(p++) = hex[n & 0x0f]; } else *(p++) = n; #else n = os_toascii[q[j]]; if ((n < os_toascii[' ']) || (n > os_toascii['~'])) { *(p++) = '\\'; *(p++) = 'x'; *(p++) = hex[(n >> 4) & 0x0f]; *(p++) = hex[n & 0x0f]; } else *(p++) = q[j]; #endif } *p = '\0'; } if (b != NULL) { p = b->data; OPENSSL_free(b); } else p = buf; if (i == 0) *p = '\0'; return (p); err: X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE); end: BUF_MEM_free(b); return (NULL); } Commit Message: CWE ID: CWE-119
char *X509_NAME_oneline(X509_NAME *a, char *buf, int len) { X509_NAME_ENTRY *ne; int i; int n, lold, l, l1, l2, num, j, type; const char *s; char *p; unsigned char *q; BUF_MEM *b = NULL; static const char hex[17] = "0123456789ABCDEF"; int gs_doit[4]; char tmp_buf[80]; #ifdef CHARSET_EBCDIC char ebcdic_buf[1024]; #endif if (buf == NULL) { if ((b = BUF_MEM_new()) == NULL) goto err; if (!BUF_MEM_grow(b, 200)) goto err; b->data[0] = '\0'; len = 200; } else if (len == 0) { return NULL; } if (a == NULL) { if (b) { buf = b->data; OPENSSL_free(b); } strncpy(buf, "NO X509_NAME", len); buf[len - 1] = '\0'; return buf; } len--; /* space for '\0' */ l = 0; for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) { ne = sk_X509_NAME_ENTRY_value(a->entries, i); n = OBJ_obj2nid(ne->object); if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) { i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object); s = tmp_buf; } l1 = strlen(s); type = ne->value->type; num = ne->value->length; if (num > NAME_ONELINE_MAX) { X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG); goto end; } q = ne->value->data; #ifdef CHARSET_EBCDIC if (type == V_ASN1_GENERALSTRING || type == V_ASN1_VISIBLESTRING || type == V_ASN1_PRINTABLESTRING || type == V_ASN1_TELETEXSTRING || type == V_ASN1_VISIBLESTRING || type == V_ASN1_IA5STRING) { if (num > (int)sizeof(ebcdic_buf)) num = sizeof(ebcdic_buf); ascii2ebcdic(ebcdic_buf, q, num); q = ebcdic_buf; } #endif if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) { gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0; for (j = 0; j < num; j++) if (q[j] != 0) gs_doit[j & 3] = 1; if (gs_doit[0] | gs_doit[1] | gs_doit[2]) gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1; else { gs_doit[0] = gs_doit[1] = gs_doit[2] = 0; gs_doit[3] = 1; } } else gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1; for (l2 = j = 0; j < num; j++) { if (!gs_doit[j & 3]) continue; l2++; #ifndef CHARSET_EBCDIC if ((q[j] < ' ') || (q[j] > '~')) l2 += 3; #else if ((os_toascii[q[j]] < os_toascii[' ']) || (os_toascii[q[j]] > os_toascii['~'])) l2 += 3; #endif } lold = l; l += 1 + l1 + 1 + l2; if (l > NAME_ONELINE_MAX) { X509err(X509_F_X509_NAME_ONELINE, X509_R_NAME_TOO_LONG); goto end; } if (b != NULL) { if (!BUF_MEM_grow(b, l + 1)) goto err; p = &(b->data[lold]); } else if (l > len) { break; } else p = &(buf[lold]); *(p++) = '/'; memcpy(p, s, (unsigned int)l1); p += l1; *(p++) = '='; #ifndef CHARSET_EBCDIC /* q was assigned above already. */ q = ne->value->data; #endif for (j = 0; j < num; j++) { if (!gs_doit[j & 3]) continue; #ifndef CHARSET_EBCDIC n = q[j]; if ((n < ' ') || (n > '~')) { *(p++) = '\\'; *(p++) = 'x'; *(p++) = hex[(n >> 4) & 0x0f]; *(p++) = hex[n & 0x0f]; } else *(p++) = n; #else n = os_toascii[q[j]]; if ((n < os_toascii[' ']) || (n > os_toascii['~'])) { *(p++) = '\\'; *(p++) = 'x'; *(p++) = hex[(n >> 4) & 0x0f]; *(p++) = hex[n & 0x0f]; } else *(p++) = q[j]; #endif } *p = '\0'; } if (b != NULL) { p = b->data; OPENSSL_free(b); } else p = buf; if (i == 0) *p = '\0'; return (p); err: X509err(X509_F_X509_NAME_ONELINE, ERR_R_MALLOC_FAILURE); end: BUF_MEM_free(b); return (NULL); }
165,207
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void dvb_usbv2_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *name = d->name; struct device dev = d->udev->dev; dev_dbg(&d->udev->dev, "%s: bInterfaceNumber=%d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); if (d->props->exit) d->props->exit(d); dvb_usbv2_exit(d); dev_info(&dev, "%s: '%s' successfully deinitialized and disconnected\n", KBUILD_MODNAME, name); } Commit Message: [media] dvb-usb-v2: avoid use-after-free I ran into a stack frame size warning because of the on-stack copy of the USB device structure: drivers/media/usb/dvb-usb-v2/dvb_usb_core.c: In function 'dvb_usbv2_disconnect': drivers/media/usb/dvb-usb-v2/dvb_usb_core.c:1029:1: error: the frame size of 1104 bytes is larger than 1024 bytes [-Werror=frame-larger-than=] Copying a device structure like this is wrong for a number of other reasons too aside from the possible stack overflow. One of them is that the dev_info() call will print the name of the device later, but AFAICT we have only copied a pointer to the name earlier and the actual name has been freed by the time it gets printed. This removes the on-stack copy of the device and instead copies the device name using kstrdup(). I'm ignoring the possible failure here as both printk() and kfree() are able to deal with NULL pointers. Signed-off-by: Arnd Bergmann <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
void dvb_usbv2_disconnect(struct usb_interface *intf) { struct dvb_usb_device *d = usb_get_intfdata(intf); const char *devname = kstrdup(dev_name(&d->udev->dev), GFP_KERNEL); const char *drvname = d->name; dev_dbg(&d->udev->dev, "%s: bInterfaceNumber=%d\n", __func__, intf->cur_altsetting->desc.bInterfaceNumber); if (d->props->exit) d->props->exit(d); dvb_usbv2_exit(d); pr_info("%s: '%s:%s' successfully deinitialized and disconnected\n", KBUILD_MODNAME, drvname, devname); kfree(devname); }
168,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void StorageHandler::GetUsageAndQuota( const String& origin, std::unique_ptr<GetUsageAndQuotaCallback> callback) { if (!process_) return callback->sendFailure(Response::InternalError()); GURL origin_url(origin); if (!origin_url.is_valid()) { return callback->sendFailure( Response::Error(origin + " is not a valid URL")); } storage::QuotaManager* manager = process_->GetStoragePartition()->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&GetUsageAndQuotaOnIOThread, base::RetainedRef(manager), origin_url, base::Passed(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 StorageHandler::GetUsageAndQuota( const String& origin, std::unique_ptr<GetUsageAndQuotaCallback> callback) { if (!storage_partition_) return callback->sendFailure(Response::InternalError()); GURL origin_url(origin); if (!origin_url.is_valid()) { return callback->sendFailure( Response::Error(origin + " is not a valid URL")); } storage::QuotaManager* manager = storage_partition_->GetQuotaManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&GetUsageAndQuotaOnIOThread, base::RetainedRef(manager), origin_url, base::Passed(std::move(callback)))); }
172,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool decode(const SharedBuffer& data, bool onlySize) { m_decodingSizeOnly = onlySize; unsigned newByteCount = data.size() - m_bufferLength; unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer += newByteCount; m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset; if (m_bytesToSkip) skipBytes(m_bytesToSkip); m_bufferLength = data.size(); if (setjmp(m_err.setjmp_buffer)) return m_decoder->setFailed(); switch (m_state) { case JPEG_HEADER: if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED) return false; // I/O suspension. switch (m_info.jpeg_color_space) { case JCS_GRAYSCALE: case JCS_RGB: case JCS_YCbCr: m_info.out_color_space = rgbOutputColorSpace(); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_info.saw_JFIF_marker) break; if (m_info.saw_Adobe_marker && !m_info.Adobe_transform) m_info.out_color_space = JCS_RGB; #endif break; case JCS_CMYK: case JCS_YCCK: m_info.out_color_space = JCS_CMYK; break; default: return m_decoder->setFailed(); } m_state = JPEG_START_DECOMPRESS; if (!m_decoder->setSize(m_info.image_width, m_info.image_height)) return false; m_decoder->setOrientation(readImageOrientation(info())); #if ENABLE(IMAGE_DECODER_DOWN_SAMPLING) && defined(TURBO_JPEG_RGB_SWIZZLE) if (m_decoder->willDownSample() && turboSwizzled(m_info.out_color_space)) m_info.out_color_space = JCS_RGB; #endif #if USE(QCMSLIB) if (!m_decoder->ignoresGammaAndColorProfile()) { ColorProfile colorProfile = readColorProfile(info()); createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space)); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_transform && m_info.out_color_space == JCS_EXT_BGRA) m_info.out_color_space = JCS_EXT_RGBA; #endif } #endif m_info.buffered_image = jpeg_has_multiple_scans(&m_info); jpeg_calc_output_dimensions(&m_info); m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1); if (m_decodingSizeOnly) { m_bufferLength -= m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer = 0; return true; } case JPEG_START_DECOMPRESS: m_info.dct_method = dctMethod(); m_info.dither_mode = ditherMode(); m_info.do_fancy_upsampling = doFancyUpsampling(); m_info.enable_2pass_quant = false; m_info.do_block_smoothing = true; if (!jpeg_start_decompress(&m_info)) return false; // I/O suspension. m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL; case JPEG_DECOMPRESS_SEQUENTIAL: if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) { if (!m_decoder->outputScanlines()) return false; // I/O suspension. ASSERT(m_info.output_scanline == m_info.output_height); m_state = JPEG_DONE; } case JPEG_DECOMPRESS_PROGRESSIVE: if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) { int status; do { status = jpeg_consume_input(&m_info); } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI)); for (;;) { if (!m_info.output_scanline) { int scan = m_info.input_scan_number; if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI)) --scan; if (!jpeg_start_output(&m_info, scan)) return false; // I/O suspension. } if (m_info.output_scanline == 0xffffff) m_info.output_scanline = 0; if (!m_decoder->outputScanlines()) { if (!m_info.output_scanline) m_info.output_scanline = 0xffffff; return false; // I/O suspension. } if (m_info.output_scanline == m_info.output_height) { if (!jpeg_finish_output(&m_info)) return false; // I/O suspension. if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number)) break; m_info.output_scanline = 0; } } m_state = JPEG_DONE; } case JPEG_DONE: return jpeg_finish_decompress(&m_info); case JPEG_ERROR: return m_decoder->setFailed(); } return true; } Commit Message: Progressive JPEG outputScanlines() calls should handle failure outputScanlines() can fail and delete |this|, so any attempt to access members thereafter should be avoided. Copy the decoder pointer member, and use that copy to detect and handle the failure case. BUG=232763 [email protected] Review URL: https://codereview.chromium.org/14844003 git-svn-id: svn://svn.chromium.org/blink/trunk@150545 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
bool decode(const SharedBuffer& data, bool onlySize) { m_decodingSizeOnly = onlySize; unsigned newByteCount = data.size() - m_bufferLength; unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer += newByteCount; m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset; if (m_bytesToSkip) skipBytes(m_bytesToSkip); m_bufferLength = data.size(); if (setjmp(m_err.setjmp_buffer)) return m_decoder->setFailed(); switch (m_state) { case JPEG_HEADER: if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED) return false; // I/O suspension. switch (m_info.jpeg_color_space) { case JCS_GRAYSCALE: case JCS_RGB: case JCS_YCbCr: m_info.out_color_space = rgbOutputColorSpace(); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_info.saw_JFIF_marker) break; if (m_info.saw_Adobe_marker && !m_info.Adobe_transform) m_info.out_color_space = JCS_RGB; #endif break; case JCS_CMYK: case JCS_YCCK: m_info.out_color_space = JCS_CMYK; break; default: return m_decoder->setFailed(); } m_state = JPEG_START_DECOMPRESS; if (!m_decoder->setSize(m_info.image_width, m_info.image_height)) return false; m_decoder->setOrientation(readImageOrientation(info())); #if ENABLE(IMAGE_DECODER_DOWN_SAMPLING) && defined(TURBO_JPEG_RGB_SWIZZLE) if (m_decoder->willDownSample() && turboSwizzled(m_info.out_color_space)) m_info.out_color_space = JCS_RGB; #endif #if USE(QCMSLIB) if (!m_decoder->ignoresGammaAndColorProfile()) { ColorProfile colorProfile = readColorProfile(info()); createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space)); #if defined(TURBO_JPEG_RGB_SWIZZLE) if (m_transform && m_info.out_color_space == JCS_EXT_BGRA) m_info.out_color_space = JCS_EXT_RGBA; #endif } #endif m_info.buffered_image = jpeg_has_multiple_scans(&m_info); jpeg_calc_output_dimensions(&m_info); m_samples = (*m_info.mem->alloc_sarray)((j_common_ptr) &m_info, JPOOL_IMAGE, m_info.output_width * 4, 1); if (m_decodingSizeOnly) { m_bufferLength -= m_info.src->bytes_in_buffer; m_info.src->bytes_in_buffer = 0; return true; } case JPEG_START_DECOMPRESS: m_info.dct_method = dctMethod(); m_info.dither_mode = ditherMode(); m_info.do_fancy_upsampling = doFancyUpsampling(); m_info.enable_2pass_quant = false; m_info.do_block_smoothing = true; if (!jpeg_start_decompress(&m_info)) return false; // I/O suspension. m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL; case JPEG_DECOMPRESS_SEQUENTIAL: if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) { if (!m_decoder->outputScanlines()) return false; // I/O suspension. ASSERT(m_info.output_scanline == m_info.output_height); m_state = JPEG_DONE; } case JPEG_DECOMPRESS_PROGRESSIVE: if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) { int status; do { status = jpeg_consume_input(&m_info); } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI)); for (;;) { if (!m_info.output_scanline) { int scan = m_info.input_scan_number; if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI)) --scan; if (!jpeg_start_output(&m_info, scan)) return false; // I/O suspension. } if (m_info.output_scanline == 0xffffff) m_info.output_scanline = 0; // If outputScanlines() fails, it deletes |this|. Therefore, // copy the decoder pointer and use it to check for failure // to avoid member access in the failure case. JPEGImageDecoder* decoder = m_decoder; if (!decoder->outputScanlines()) { if (decoder->failed()) // Careful; |this| is deleted. return false; if (!m_info.output_scanline) m_info.output_scanline = 0xffffff; return false; // I/O suspension. } if (m_info.output_scanline == m_info.output_height) { if (!jpeg_finish_output(&m_info)) return false; // I/O suspension. if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number)) break; m_info.output_scanline = 0; } } m_state = JPEG_DONE; } case JPEG_DONE: return jpeg_finish_decompress(&m_info); case JPEG_ERROR: return m_decoder->setFailed(); } return true; }
171,590
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) { WaitableEvent done(false, false); scoped_refptr<WorkerTask> task(new WorkerTask(work, &done)); history_service_->ScheduleDBTask(task.get(), this); done.Wait(); } Commit Message: Enable HistoryModelWorker by default, now that bug 69561 is fixed. BUG=69561 TEST=Run sync manually and run integration tests, sync should not crash. Review URL: http://codereview.chromium.org/7016007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85211 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void HistoryModelWorker::DoWorkAndWaitUntilDone(Callback0::Type* work) { WaitableEvent done(false, false); scoped_refptr<WorkerTask> task(new WorkerTask(work, &done)); history_service_->ScheduleDBTask(task.get(), &cancelable_consumer_); done.Wait(); }
170,613
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t len; uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) { return; } } n = r->iov.iov_len / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { len = r->sector_count * 512; if (len > SCSI_DMA_BUF_SIZE) { len = SCSI_DMA_BUF_SIZE; } r->iov.iov_len = len; DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, len); scsi_req_data(&r->req, len); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) { return; } } n = r->qiov.size / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { scsi_init_iovec(r); DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size); scsi_req_data(&r->req, r->qiov.size); } }
169,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Cues::Init() const { if (m_cue_points) return; assert(m_count == 0); assert(m_preload_count == 0); IMkvReader* const pReader = m_pSegment->m_pReader; const long long stop = m_start + m_size; long long pos = m_start; long cue_points_size = 0; while (pos < stop) { const long long idpos = pos; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); //TODO assert((pos + len) <= stop); pos += len; //consume ID const long long size = ReadUInt(pReader, pos, len); assert(size >= 0); assert((pos + len) <= stop); pos += len; //consume Size field assert((pos + size) <= stop); if (id == 0x3B) //CuePoint ID PreloadCuePoint(cue_points_size, idpos); pos += size; //consume payload assert(pos <= stop); } } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Cues::Init() const long len; const long long id = ReadUInt(pReader, m_pos, len); assert(id >= 0); // TODO assert((m_pos + len) <= stop); m_pos += len; // consume ID const long long size = ReadUInt(pReader, m_pos, len); assert(size >= 0); assert((m_pos + len) <= stop); m_pos += len; // consume Size field assert((m_pos + size) <= stop); if (id != 0x3B) { // CuePoint ID m_pos += size; // consume payload assert(m_pos <= stop);
174,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GDataDirectory* AddDirectory(GDataDirectory* parent, GDataDirectoryService* directory_service, int sequence_id) { GDataDirectory* dir = new GDataDirectory(NULL, directory_service); const std::string dir_name = "dir" + base::IntToString(sequence_id); const std::string resource_id = std::string("dir_resource_id:") + dir_name; dir->set_title(dir_name); dir->set_resource_id(resource_id); GDataFileError error = GDATA_FILE_ERROR_FAILED; FilePath moved_file_path; directory_service->MoveEntryToDirectory( parent->GetFilePath(), dir, base::Bind(&test_util::CopyResultsFromFileMoveCallback, &error, &moved_file_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(GDATA_FILE_OK, error); EXPECT_EQ(parent->GetFilePath().AppendASCII(dir_name), moved_file_path); return dir; } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
GDataDirectory* AddDirectory(GDataDirectory* parent, GDataDirectoryService* directory_service, int sequence_id) { GDataDirectory* dir = directory_service->CreateGDataDirectory(); const std::string dir_name = "dir" + base::IntToString(sequence_id); const std::string resource_id = std::string("dir_resource_id:") + dir_name; dir->set_title(dir_name); dir->set_resource_id(resource_id); GDataFileError error = GDATA_FILE_ERROR_FAILED; FilePath moved_file_path; directory_service->MoveEntryToDirectory( parent->GetFilePath(), dir, base::Bind(&test_util::CopyResultsFromFileMoveCallback, &error, &moved_file_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(GDATA_FILE_OK, error); EXPECT_EQ(parent->GetFilePath().AppendASCII(dir_name), moved_file_path); return dir; }
171,494
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SerializeDefaultPaddingKey() { return (*GetPaddingKey())->key(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
std::string SerializeDefaultPaddingKey() { return (*GetPaddingKeyInternal())->key(); }
173,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool)>& callback, skia::PlatformBitmap* output) { base::ScopedClosureRunner scoped_callback_runner(base::Bind(callback, false)); std::map<uint64, scoped_refptr<ui::Texture> >::iterator it = image_transport_clients_.find(current_surface_); if (it == image_transport_clients_.end()) return; ui::Texture* container = it->second; DCHECK(container); gfx::Size dst_size_in_pixel = ConvertSizeToPixel(this, dst_size); if (!output->Allocate( dst_size_in_pixel.width(), dst_size_in_pixel.height(), true)) return; ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); GLHelper* gl_helper = factory->GetGLHelper(); if (!gl_helper) return; unsigned char* addr = static_cast<unsigned char*>( output->GetBitmap().getPixels()); scoped_callback_runner.Release(); base::Callback<void(bool)> wrapper_callback = base::Bind( &RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished, AsWeakPtr(), callback); ++pending_thumbnail_tasks_; gfx::Rect src_subrect_in_gl = src_subrect; src_subrect_in_gl.set_y(GetViewBounds().height() - src_subrect.bottom()); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(this, src_subrect_in_gl); gl_helper->CropScaleReadbackAndCleanTexture(container->PrepareTexture(), container->size(), src_subrect_in_pixel, dst_size_in_pixel, addr, wrapper_callback); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool)>& callback, skia::PlatformBitmap* output) { base::ScopedClosureRunner scoped_callback_runner(base::Bind(callback, false)); std::map<uint64, scoped_refptr<ui::Texture> >::iterator it = image_transport_clients_.find(current_surface_); if (it == image_transport_clients_.end()) return; ui::Texture* container = it->second; DCHECK(container); gfx::Size dst_size_in_pixel = ConvertSizeToPixel(this, dst_size); if (!output->Allocate( dst_size_in_pixel.width(), dst_size_in_pixel.height(), true)) return; ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); GLHelper* gl_helper = factory->GetGLHelper(); if (!gl_helper) return; unsigned char* addr = static_cast<unsigned char*>( output->GetBitmap().getPixels()); scoped_callback_runner.Release(); // own completion handlers (where we can try to free the frontbuffer). base::Callback<void(bool)> wrapper_callback = base::Bind( &RenderWidgetHostViewAura::CopyFromCompositingSurfaceFinished, AsWeakPtr(), callback); ++pending_thumbnail_tasks_; gfx::Rect src_subrect_in_gl = src_subrect; src_subrect_in_gl.set_y(GetViewBounds().height() - src_subrect.bottom()); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(this, src_subrect_in_gl); gl_helper->CropScaleReadbackAndCleanTexture(container->PrepareTexture(), container->size(), src_subrect_in_pixel, dst_size_in_pixel, addr, wrapper_callback); }
171,377
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_module_is_block_algorithm) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) if (mcrypt_module_is_block_algorithm(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_module_is_block_algorithm) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) if (mcrypt_module_is_block_algorithm(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } }
167,097
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mdecrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; 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); } mdecrypt_generic(pm->td, data_s, data_size); 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(mdecrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; 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); } mdecrypt_generic(pm->td, data_s, data_size); RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); }
167,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebNotificationData ToWebNotificationData( const PlatformNotificationData& platform_data) { WebNotificationData web_data; web_data.title = platform_data.title; switch (platform_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: web_data.direction = WebNotificationData::DirectionLeftToRight; break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: web_data.direction = WebNotificationData::DirectionRightToLeft; break; case PlatformNotificationData::DIRECTION_AUTO: web_data.direction = WebNotificationData::DirectionAuto; break; } web_data.lang = blink::WebString::fromUTF8(platform_data.lang); web_data.body = platform_data.body; web_data.tag = blink::WebString::fromUTF8(platform_data.tag); web_data.icon = blink::WebURL(platform_data.icon); web_data.vibrate = platform_data.vibration_pattern; web_data.timestamp = platform_data.timestamp.ToJsTime(); web_data.silent = platform_data.silent; web_data.requireInteraction = platform_data.require_interaction; web_data.data = platform_data.data; blink::WebVector<blink::WebNotificationAction> resized( platform_data.actions.size()); web_data.actions.swap(resized); for (size_t i = 0; i < platform_data.actions.size(); ++i) { web_data.actions[i].action = blink::WebString::fromUTF8(platform_data.actions[i].action); web_data.actions[i].title = platform_data.actions[i].title; } return web_data; } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
WebNotificationData ToWebNotificationData( const PlatformNotificationData& platform_data) { WebNotificationData web_data; web_data.title = platform_data.title; switch (platform_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: web_data.direction = WebNotificationData::DirectionLeftToRight; break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: web_data.direction = WebNotificationData::DirectionRightToLeft; break; case PlatformNotificationData::DIRECTION_AUTO: web_data.direction = WebNotificationData::DirectionAuto; break; } web_data.lang = blink::WebString::fromUTF8(platform_data.lang); web_data.body = platform_data.body; web_data.tag = blink::WebString::fromUTF8(platform_data.tag); web_data.icon = blink::WebURL(platform_data.icon); web_data.vibrate = platform_data.vibration_pattern; web_data.timestamp = platform_data.timestamp.ToJsTime(); web_data.silent = platform_data.silent; web_data.requireInteraction = platform_data.require_interaction; web_data.data = platform_data.data; blink::WebVector<blink::WebNotificationAction> resized( platform_data.actions.size()); web_data.actions.swap(resized); for (size_t i = 0; i < platform_data.actions.size(); ++i) { web_data.actions[i].action = blink::WebString::fromUTF8(platform_data.actions[i].action); web_data.actions[i].title = platform_data.actions[i].title; web_data.actions[i].icon = blink::WebURL(platform_data.actions[i].icon); } return web_data; }
171,632
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeOSStopInputMethodProcess(InputMethodStatusConnection* connection) { g_return_val_if_fail(connection, false); return connection->StopInputMethodProcess(); } 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
bool ChromeOSStopInputMethodProcess(InputMethodStatusConnection* connection) {
170,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { guchar *match; int i; /* First try to match any leftover at the start */ if (client->auth_end_offset > 0) { gsize left = strlen (AUTH_END_STRING) - client->auth_end_offset; gsize to_match = MIN (left, buffer->pos); /* Matched at least up to to_match */ if (memcmp (buffer->data, &AUTH_END_STRING[client->auth_end_offset], to_match) == 0) { client->auth_end_offset += to_match; /* Matched all */ if (client->auth_end_offset == strlen (AUTH_END_STRING)) return to_match; /* Matched to end of buffer */ return -1; } /* Did not actually match at start */ client->auth_end_offset = -1; } /* Look for whole match inside buffer */ match = memmem (buffer, buffer->pos, AUTH_END_STRING, strlen (AUTH_END_STRING)); if (match != NULL) return match - buffer->data + strlen (AUTH_END_STRING); /* Record longest prefix match at the end */ for (i = MIN (strlen (AUTH_END_STRING) - 1, buffer->pos); i > 0; i--) { if (memcmp (buffer->data + buffer->pos - i, AUTH_END_STRING, i) == 0) { client->auth_end_offset = i; break; } } return -1; } Commit Message: Fix vulnerability in dbus proxy During the authentication all client data is directly forwarded to the dbus daemon as is, until we detect the BEGIN command after which we start filtering the binary dbus protocol. Unfortunately the detection of the BEGIN command in the proxy did not exactly match the detection in the dbus daemon. A BEGIN followed by a space or tab was considered ok in the daemon but not by the proxy. This could be exploited to send arbitrary dbus messages to the host, which can be used to break out of the sandbox. This was noticed by Gabriel Campana of The Google Security Team. This fix makes the detection of the authentication phase end match the dbus code. In addition we duplicate the authentication line validation from dbus, which includes ensuring all data is ASCII, and limiting the size of a line to 16k. In fact, we add some extra stringent checks, disallowing ASCII control chars and requiring that auth lines start with a capital letter. CWE ID: CWE-436
find_auth_end (FlatpakProxyClient *client, Buffer *buffer) { goffset offset = 0; gsize original_size = client->auth_buffer->len; /* Add the new data to the remaining data from last iteration */ g_byte_array_append (client->auth_buffer, buffer->data, buffer->pos); while (TRUE) { guint8 *line_start = client->auth_buffer->data + offset; gsize remaining_data = client->auth_buffer->len - offset; guint8 *line_end; line_end = memmem (line_start, remaining_data, AUTH_LINE_SENTINEL, strlen (AUTH_LINE_SENTINEL)); if (line_end) /* Found end of line */ { offset = (line_end + strlen (AUTH_LINE_SENTINEL) - line_start); if (!auth_line_is_valid (line_start, line_end)) return FIND_AUTH_END_ABORT; *line_end = 0; if (auth_line_is_begin (line_start)) return offset - original_size; /* continue with next line */ } else { /* No end-of-line in this buffer */ g_byte_array_remove_range (client->auth_buffer, 0, offset); /* Abort if more than 16k before newline, similar to what dbus-daemon does */ if (client->auth_buffer->len >= 16*1024) return FIND_AUTH_END_ABORT; return FIND_AUTH_END_CONTINUE; } } }
169,340
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ProfileChooserView::RemoveAccount() { DCHECK(!account_id_to_remove_.empty()); ProfileOAuth2TokenService* oauth2_token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile()); if (oauth2_token_service) { oauth2_token_service->RevokeCredentials(account_id_to_remove_); PostActionPerformed(ProfileMetrics::PROFILE_DESKTOP_MENU_REMOVE_ACCT); } account_id_to_remove_.clear(); ShowViewFromMode(profiles::BUBBLE_VIEW_MODE_ACCOUNT_MANAGEMENT); } Commit Message: [signin] Add metrics to track the source for refresh token updated events This CL add a source for update and revoke credentials operations. It then surfaces the source in the chrome://signin-internals page. This CL also records the following histograms that track refresh token events: * Signin.RefreshTokenUpdated.ToValidToken.Source * Signin.RefreshTokenUpdated.ToInvalidToken.Source * Signin.RefreshTokenRevoked.Source These histograms are needed to validate the assumptions of how often tokens are revoked by the browser and the sources for the token revocations. Bug: 896182 Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90 Reviewed-on: https://chromium-review.googlesource.com/c/1286464 Reviewed-by: Jochen Eisinger <[email protected]> Reviewed-by: David Roger <[email protected]> Reviewed-by: Ilya Sherman <[email protected]> Commit-Queue: Mihai Sardarescu <[email protected]> Cr-Commit-Position: refs/heads/master@{#606181} CWE ID: CWE-20
void ProfileChooserView::RemoveAccount() { DCHECK(!account_id_to_remove_.empty()); ProfileOAuth2TokenService* oauth2_token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile()); if (oauth2_token_service) { oauth2_token_service->RevokeCredentials( account_id_to_remove_, signin_metrics::SourceForRefreshTokenOperation:: kUserMenu_RemoveAccount); PostActionPerformed(ProfileMetrics::PROFILE_DESKTOP_MENU_REMOVE_ACCT); } account_id_to_remove_.clear(); ShowViewFromMode(profiles::BUBBLE_VIEW_MODE_ACCOUNT_MANAGEMENT); }
172,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Blob::Blob(const KURL& srcURL, const String& type, long long size) : m_type(type) , m_size(size) { ScriptWrappable::init(this); m_internalURL = BlobURL::createInternalURL(); ThreadableBlobRegistry::registerBlobURL(0, m_internalURL, srcURL); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
Blob::Blob(const KURL& srcURL, const String& type, long long size) : m_type(type) , m_size(size) { ScriptWrappable::init(this); m_internalURL = BlobURL::createInternalURL(); BlobRegistry::registerBlobURL(0, m_internalURL, srcURL); }
170,676
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AudioInputRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, const std::string& device_id, bool automatic_gain_control) { VLOG(1) << "AudioInputRendererHost::OnCreateStream(stream_id=" << stream_id << ")"; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(LookupById(stream_id) == NULL); media::AudioParameters audio_params(params); if (media_stream_manager_->audio_input_device_manager()-> ShouldUseFakeDevice()) { audio_params.Reset(media::AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } else if (WebContentsCaptureUtil::IsWebContentsDeviceId(device_id)) { audio_params.Reset(media::AudioParameters::AUDIO_VIRTUAL, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } DCHECK_GT(audio_params.frames_per_buffer(), 0); uint32 buffer_size = audio_params.GetBytesPerBuffer(); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 mem_size = sizeof(media::AudioInputBufferParameters) + buffer_size; if (!entry->shared_memory.CreateAndMapAnonymous(mem_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioInputSyncWriter> writer( new AudioInputSyncWriter(&entry->shared_memory)); if (!writer->Init()) { SendErrorMessage(stream_id); return; } entry->writer.reset(writer.release()); entry->controller = media::AudioInputController::CreateLowLatency( audio_manager_, this, audio_params, device_id, entry->writer.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } if (params.format() == media::AudioParameters::AUDIO_PCM_LOW_LATENCY) entry->controller->SetAutomaticGainControl(automatic_gain_control); entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); } Commit Message: Improve validation when creating audio streams. BUG=166795 Review URL: https://codereview.chromium.org/11647012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void AudioInputRendererHost::OnCreateStream( int stream_id, const media::AudioParameters& params, const std::string& device_id, bool automatic_gain_control) { VLOG(1) << "AudioInputRendererHost::OnCreateStream(stream_id=" << stream_id << ")"; DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // media::AudioParameters is validated in the deserializer. if (LookupById(stream_id) != NULL) { SendErrorMessage(stream_id); return; } media::AudioParameters audio_params(params); if (media_stream_manager_->audio_input_device_manager()-> ShouldUseFakeDevice()) { audio_params.Reset(media::AudioParameters::AUDIO_FAKE, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } else if (WebContentsCaptureUtil::IsWebContentsDeviceId(device_id)) { audio_params.Reset(media::AudioParameters::AUDIO_VIRTUAL, params.channel_layout(), params.sample_rate(), params.bits_per_sample(), params.frames_per_buffer()); } uint32 buffer_size = audio_params.GetBytesPerBuffer(); scoped_ptr<AudioEntry> entry(new AudioEntry()); uint32 mem_size = sizeof(media::AudioInputBufferParameters) + buffer_size; if (!entry->shared_memory.CreateAndMapAnonymous(mem_size)) { SendErrorMessage(stream_id); return; } scoped_ptr<AudioInputSyncWriter> writer( new AudioInputSyncWriter(&entry->shared_memory)); if (!writer->Init()) { SendErrorMessage(stream_id); return; } entry->writer.reset(writer.release()); entry->controller = media::AudioInputController::CreateLowLatency( audio_manager_, this, audio_params, device_id, entry->writer.get()); if (!entry->controller) { SendErrorMessage(stream_id); return; } if (params.format() == media::AudioParameters::AUDIO_PCM_LOW_LATENCY) entry->controller->SetAutomaticGainControl(automatic_gain_control); entry->stream_id = stream_id; audio_entries_.insert(std::make_pair(stream_id, entry.release())); }
171,524