instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: asn1_get_bit_der (const unsigned char *der, int der_len, int *ret_len, unsigned char *str, int str_size, int *bit_len) { int len_len, len_byte; if (der_len <= 0) return ASN1_GENERIC_ERROR; len_byte = asn1_get_length_der (der, der_len, &len_len) - 1; if (len_byte < 0) return ASN1_DER_ERROR; *ret_len = len_byte + len_len + 1; *bit_len = len_byte * 8 - der[len_len]; if (str_size >= len_byte) memcpy (str, der + len_len + 1, len_byte); } Commit Message: CWE ID: CWE-189
asn1_get_bit_der (const unsigned char *der, int der_len, int *ret_len, unsigned char *str, int str_size, int *bit_len) { int len_len = 0, len_byte; if (der_len <= 0) return ASN1_GENERIC_ERROR; len_byte = asn1_get_length_der (der, der_len, &len_len) - 1; if (len_byte < 0) return ASN1_DER_ERROR; *ret_len = len_byte + len_len + 1; *bit_len = len_byte * 8 - der[len_len]; if (*bit_len <= 0) return ASN1_DER_ERROR; if (str_size >= len_byte) memcpy (str, der + len_len + 1, len_byte); }
165,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_png(struct control *control) /* Read a PNG, return 0 on success else an error (status) code; a bit mask as * defined for file::status_code as above. */ { png_structp png_ptr; png_infop info_ptr = NULL; volatile png_bytep row = NULL, display = NULL; volatile int rc; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control, error_handler, warning_handler); if (png_ptr == NULL) { /* This is not really expected. */ log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct"); control->file.status_code |= INTERNAL_ERROR; return LIBPNG_ERROR_CODE; } rc = setjmp(control->file.jmpbuf); if (rc == 0) { png_set_read_fn(png_ptr, control, read_callback); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); if (control->file.global->verbose) fprintf(stderr, " INFO\n"); png_read_info(png_ptr, info_ptr); { png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); row = png_voidcast(png_byte*, malloc(rowbytes)); display = png_voidcast(png_byte*, malloc(rowbytes)); if (row == NULL || display == NULL) png_error(png_ptr, "OOM allocating row buffers"); { png_uint_32 height = png_get_image_height(png_ptr, info_ptr); int passes = png_set_interlace_handling(png_ptr); int pass; png_start_read_image(png_ptr); for (pass = 0; pass < passes; ++pass) { png_uint_32 y = height; /* NOTE: this trashes the row each time; interlace handling won't * work, but this avoids memory thrashing for speed testing. */ while (y-- > 0) png_read_row(png_ptr, row, display); } } } if (control->file.global->verbose) fprintf(stderr, " END\n"); /* Make sure to read to the end of the file: */ png_read_end(png_ptr, info_ptr); } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); if (row != NULL) free(row); if (display != NULL) free(display); return rc; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
read_png(struct control *control) /* Read a PNG, return 0 on success else an error (status) code; a bit mask as * defined for file::status_code as above. */ { png_structp png_ptr; png_infop info_ptr = NULL; volatile int rc; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control, error_handler, warning_handler); if (png_ptr == NULL) { /* This is not really expected. */ log_error(&control->file, LIBPNG_ERROR_CODE, "OOM allocating png_struct"); control->file.status_code |= INTERNAL_ERROR; return LIBPNG_ERROR_CODE; } rc = setjmp(control->file.jmpbuf); if (rc == 0) { # ifdef PNG_SET_USER_LIMITS_SUPPORTED /* Remove any limits on the size of PNG files that can be read, * without this we may reject files based on built-in safety * limits. */ png_set_user_limits(png_ptr, 0x7fffffff, 0x7fffffff); png_set_chunk_cache_max(png_ptr, 0); png_set_chunk_malloc_max(png_ptr, 0); # endif png_set_read_fn(png_ptr, control, read_callback); info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) png_error(png_ptr, "OOM allocating info structure"); if (control->file.global->verbose) fprintf(stderr, " INFO\n"); png_read_info(png_ptr, info_ptr); { png_uint_32 height = png_get_image_height(png_ptr, info_ptr); int passes = png_set_interlace_handling(png_ptr); int pass; png_start_read_image(png_ptr); for (pass = 0; pass < passes; ++pass) { png_uint_32 y = height; /* NOTE: this skips asking libpng to return either version of * the image row, but libpng still reads the rows. */ while (y-- > 0) png_read_row(png_ptr, NULL, NULL); } } if (control->file.global->verbose) fprintf(stderr, " END\n"); /* Make sure to read to the end of the file: */ png_read_end(png_ptr, info_ptr); } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return rc; }
173,738
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perf_callchain_user_64(struct perf_callchain_entry *entry, struct pt_regs *regs) { unsigned long sp, next_sp; unsigned long next_ip; unsigned long lr; long level = 0; struct signal_frame_64 __user *sigframe; unsigned long __user *fp, *uregs; next_ip = perf_instruction_pointer(regs); lr = regs->link; sp = regs->gpr[1]; perf_callchain_store(entry, next_ip); for (;;) { fp = (unsigned long __user *) sp; if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp)) return; if (level > 0 && read_user_stack_64(&fp[2], &next_ip)) return; /* * Note: the next_sp - sp >= signal frame size check * is true when next_sp < sp, which can happen when * transitioning from an alternate signal stack to the * normal stack. */ if (next_sp - sp >= sizeof(struct signal_frame_64) && (is_sigreturn_64_address(next_ip, sp) || (level <= 1 && is_sigreturn_64_address(lr, sp))) && sane_signal_64_frame(sp)) { /* * This looks like an signal frame */ sigframe = (struct signal_frame_64 __user *) sp; uregs = sigframe->uc.uc_mcontext.gp_regs; if (read_user_stack_64(&uregs[PT_NIP], &next_ip) || read_user_stack_64(&uregs[PT_LNK], &lr) || read_user_stack_64(&uregs[PT_R1], &sp)) return; level = 0; perf_callchain_store(entry, PERF_CONTEXT_USER); perf_callchain_store(entry, next_ip); continue; } if (level == 0) next_ip = lr; perf_callchain_store(entry, next_ip); ++level; sp = next_sp; } } Commit Message: powerpc/perf: Cap 64bit userspace backtraces to PERF_MAX_STACK_DEPTH We cap 32bit userspace backtraces to PERF_MAX_STACK_DEPTH (currently 127), but we forgot to do the same for 64bit backtraces. Cc: stable@vger.kernel.org Signed-off-by: Anton Blanchard <anton@samba.org> Signed-off-by: Michael Ellerman <mpe@ellerman.id.au> CWE ID: CWE-399
static void perf_callchain_user_64(struct perf_callchain_entry *entry, struct pt_regs *regs) { unsigned long sp, next_sp; unsigned long next_ip; unsigned long lr; long level = 0; struct signal_frame_64 __user *sigframe; unsigned long __user *fp, *uregs; next_ip = perf_instruction_pointer(regs); lr = regs->link; sp = regs->gpr[1]; perf_callchain_store(entry, next_ip); while (entry->nr < PERF_MAX_STACK_DEPTH) { fp = (unsigned long __user *) sp; if (!valid_user_sp(sp, 1) || read_user_stack_64(fp, &next_sp)) return; if (level > 0 && read_user_stack_64(&fp[2], &next_ip)) return; /* * Note: the next_sp - sp >= signal frame size check * is true when next_sp < sp, which can happen when * transitioning from an alternate signal stack to the * normal stack. */ if (next_sp - sp >= sizeof(struct signal_frame_64) && (is_sigreturn_64_address(next_ip, sp) || (level <= 1 && is_sigreturn_64_address(lr, sp))) && sane_signal_64_frame(sp)) { /* * This looks like an signal frame */ sigframe = (struct signal_frame_64 __user *) sp; uregs = sigframe->uc.uc_mcontext.gp_regs; if (read_user_stack_64(&uregs[PT_NIP], &next_ip) || read_user_stack_64(&uregs[PT_LNK], &lr) || read_user_stack_64(&uregs[PT_R1], &sp)) return; level = 0; perf_callchain_store(entry, PERF_CONTEXT_USER); perf_callchain_store(entry, next_ip); continue; } if (level == 0) next_ip = lr; perf_callchain_store(entry, next_ip); ++level; sp = next_sp; } }
166,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PaintImage AcceleratedStaticBitmapImage::PaintImageForCurrentFrame() { CheckThread(); if (!IsValid()) return PaintImage(); sk_sp<SkImage> image; if (original_skia_image_ && original_skia_image_thread_id_ == Platform::Current()->CurrentThread()->ThreadId()) { image = original_skia_image_; } else { CreateImageFromMailboxIfNeeded(); image = texture_holder_->GetSkImage(); } return CreatePaintImageBuilder() .set_image(image, paint_image_content_id_) .set_completion_state(PaintImage::CompletionState::DONE) .TakePaintImage(); } Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy - AcceleratedStaticBitmapImage was misusing ThreadChecker by having its own detach logic. Using proper DetachThread is simpler, cleaner and correct. - UnacceleratedStaticBitmapImage didn't destroy the SkImage in the proper thread, leading to GrContext/SkSp problems. Bug: 890576 Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723 Reviewed-on: https://chromium-review.googlesource.com/c/1307775 Reviewed-by: Gabriel Charette <gab@chromium.org> Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
PaintImage AcceleratedStaticBitmapImage::PaintImageForCurrentFrame() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (!IsValid()) return PaintImage(); sk_sp<SkImage> image; if (original_skia_image_ && original_skia_image_task_runner_->BelongsToCurrentThread()) { image = original_skia_image_; } else { CreateImageFromMailboxIfNeeded(); image = texture_holder_->GetSkImage(); } return CreatePaintImageBuilder() .set_image(image, paint_image_content_id_) .set_completion_state(PaintImage::CompletionState::DONE) .TakePaintImage(); }
172,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FrameSelection::Clear() { granularity_ = TextGranularity::kCharacter; if (granularity_strategy_) granularity_strategy_->Clear(); SetSelection(SelectionInDOMTree()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Reviewed-by: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
void FrameSelection::Clear() { granularity_ = TextGranularity::kCharacter; if (granularity_strategy_) granularity_strategy_->Clear(); SetSelection(SelectionInDOMTree()); is_handle_visible_ = false; }
171,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t Camera3Device::createDefaultRequest(int templateId, CameraMetadata *request) { ATRACE_CALL(); ALOGV("%s: for template %d", __FUNCTION__, templateId); Mutex::Autolock il(mInterfaceLock); Mutex::Autolock l(mLock); switch (mStatus) { case STATUS_ERROR: CLOGE("Device has encountered a serious error"); return INVALID_OPERATION; case STATUS_UNINITIALIZED: CLOGE("Device is not initialized!"); return INVALID_OPERATION; case STATUS_UNCONFIGURED: case STATUS_CONFIGURED: case STATUS_ACTIVE: break; default: SET_ERR_L("Unexpected status: %d", mStatus); return INVALID_OPERATION; } if (!mRequestTemplateCache[templateId].isEmpty()) { *request = mRequestTemplateCache[templateId]; return OK; } const camera_metadata_t *rawRequest; ATRACE_BEGIN("camera3->construct_default_request_settings"); rawRequest = mHal3Device->ops->construct_default_request_settings( mHal3Device, templateId); ATRACE_END(); if (rawRequest == NULL) { ALOGI("%s: template %d is not supported on this camera device", __FUNCTION__, templateId); return BAD_VALUE; } *request = rawRequest; mRequestTemplateCache[templateId] = rawRequest; return OK; } Commit Message: Camera3Device: Validate template ID Validate template ID before creating a default request. Bug: 26866110 Bug: 27568958 Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d CWE ID: CWE-264
status_t Camera3Device::createDefaultRequest(int templateId, CameraMetadata *request) { ATRACE_CALL(); ALOGV("%s: for template %d", __FUNCTION__, templateId); if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) { android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110", IPCThreadState::self()->getCallingUid(), NULL, 0); return BAD_VALUE; } Mutex::Autolock il(mInterfaceLock); Mutex::Autolock l(mLock); switch (mStatus) { case STATUS_ERROR: CLOGE("Device has encountered a serious error"); return INVALID_OPERATION; case STATUS_UNINITIALIZED: CLOGE("Device is not initialized!"); return INVALID_OPERATION; case STATUS_UNCONFIGURED: case STATUS_CONFIGURED: case STATUS_ACTIVE: break; default: SET_ERR_L("Unexpected status: %d", mStatus); return INVALID_OPERATION; } if (!mRequestTemplateCache[templateId].isEmpty()) { *request = mRequestTemplateCache[templateId]; return OK; } const camera_metadata_t *rawRequest; ATRACE_BEGIN("camera3->construct_default_request_settings"); rawRequest = mHal3Device->ops->construct_default_request_settings( mHal3Device, templateId); ATRACE_END(); if (rawRequest == NULL) { ALOGI("%s: template %d is not supported on this camera device", __FUNCTION__, templateId); return BAD_VALUE; } *request = rawRequest; mRequestTemplateCache[templateId] = rawRequest; return OK; }
173,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ShellWindowFrameView::ButtonPressed(views::Button* sender, const views::Event& event) { if (sender == close_button_) frame_->Close(); } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 R=ben@chromium.org Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
void ShellWindowFrameView::ButtonPressed(views::Button* sender, const views::Event& event) { DCHECK(!is_frameless_); if (sender == close_button_) frame_->Close(); }
170,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(navigation_handle); if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSameDocument()) { return; } first_time_title_set_ = false; first_time_favicon_set_ = false; if (!navigation_handle->HasCommitted()) return; const url::Origin new_origin = url::Origin::Create(navigation_handle->GetURL()); if (writer_ && new_origin == writer_origin_) return; writer_.reset(); writer_origin_ = url::Origin(); if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS()) return; Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); DCHECK(profile); SiteCharacteristicsDataStore* data_store = LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile); DCHECK(data_store); writer_ = data_store->GetWriterForOrigin( new_origin, ContentVisibilityToRCVisibility(web_contents()->GetVisibility())); if (TabLoadTracker::Get()->GetLoadingState(web_contents()) == LoadingState::LOADED) { writer_->NotifySiteLoaded(); } writer_origin_ = new_origin; } 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 <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void LocalSiteCharacteristicsWebContentsObserver::DidFinishNavigation( content::NavigationHandle* navigation_handle) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(navigation_handle); if (!navigation_handle->IsInMainFrame() || navigation_handle->IsSameDocument()) { return; } first_time_title_set_ = false; first_time_favicon_set_ = false; if (!navigation_handle->HasCommitted()) return; const url::Origin new_origin = url::Origin::Create(navigation_handle->GetURL()); if (writer_ && new_origin == writer_origin_) return; writer_.reset(); writer_origin_ = url::Origin(); if (!URLShouldBeStoredInLocalDatabase(navigation_handle->GetURL())) return; Profile* profile = Profile::FromBrowserContext(web_contents()->GetBrowserContext()); DCHECK(profile); SiteCharacteristicsDataStore* data_store = LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile); DCHECK(data_store); writer_ = data_store->GetWriterForOrigin( new_origin, ContentVisibilityToRCVisibility(web_contents()->GetVisibility())); if (TabLoadTracker::Get()->GetLoadingState(web_contents()) == LoadingState::LOADED) { writer_->NotifySiteLoaded(); } writer_origin_ = new_origin; }
172,216
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DataReductionProxySettings::IsDataSaverEnabledByUser() const { //// static if (params::ShouldForceEnableDataReductionProxy()) return true; if (spdy_proxy_auth_enabled_.GetPrefName().empty()) return false; return spdy_proxy_auth_enabled_.GetValue(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
bool DataReductionProxySettings::IsDataSaverEnabledByUser() const { //// static bool DataReductionProxySettings::IsDataSaverEnabledByUser(PrefService* prefs) { if (params::ShouldForceEnableDataReductionProxy()) return true; return prefs && prefs->GetBoolean(prefs::kDataSaverEnabled); }
172,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_get_uint_31(png_structp png_ptr, png_bytep buf) { #ifdef PNG_READ_BIG_ENDIAN_SUPPORTED png_uint_32 i = png_get_uint_32(buf); #else /* Avoid an extra function call by inlining the result. */ png_uint_32 i = ((png_uint_32)(*buf) << 24) + ((png_uint_32)(*(buf + 1)) << 16) + ((png_uint_32)(*(buf + 2)) << 8) + (png_uint_32)(*(buf + 3)); #endif if (i > PNG_UINT_31_MAX) png_error(png_ptr, "PNG unsigned integer out of range."); return (i); } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_get_uint_31(png_structp png_ptr, png_bytep buf) { #ifdef PNG_READ_BIG_ENDIAN_SUPPORTED png_uint_32 i = png_get_uint_32(buf); #else /* Avoid an extra function call by inlining the result. */ png_uint_32 i = ((png_uint_32)((*(buf )) & 0xff) << 24) + ((png_uint_32)((*(buf + 1)) & 0xff) << 16) + ((png_uint_32)((*(buf + 2)) & 0xff) << 8) + ((png_uint_32)((*(buf + 3)) & 0xff) ); #endif if (i > PNG_UINT_31_MAX) png_error(png_ptr, "PNG unsigned integer out of range."); return (i); }
172,175
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SegmentInfo::Parse() { assert(m_pMuxingAppAsUTF8 == NULL); assert(m_pWritingAppAsUTF8 == NULL); assert(m_pTitleAsUTF8 == NULL); IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = m_start; const long long stop = m_start + m_size; m_timecodeScale = 1000000; m_duration = -1; while (pos < stop) { long long id, size; const long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x0AD7B1) //Timecode Scale { m_timecodeScale = UnserializeUInt(pReader, pos, size); if (m_timecodeScale <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0489) //Segment duration { const long status = UnserializeFloat( pReader, pos, size, m_duration); if (status < 0) return status; if (m_duration < 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0D80) //MuxingApp { const long status = UnserializeString( pReader, pos, size, m_pMuxingAppAsUTF8); if (status) return status; } else if (id == 0x1741) //WritingApp { const long status = UnserializeString( pReader, pos, size, m_pWritingAppAsUTF8); if (status) return status; } else if (id == 0x3BA9) //Title { const long status = UnserializeString( pReader, pos, size, m_pTitleAsUTF8); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long SegmentInfo::Parse()
174,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GaiaOAuthClient::Core::OnAuthTokenFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); if (!status.is_success()) { delegate_->OnNetworkError(response_code); return; } if (response_code == net::HTTP_BAD_REQUEST) { LOG(ERROR) << "Gaia response: response code=net::HTTP_BAD_REQUEST."; delegate_->OnOAuthError(); return; } if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); response_dict->GetString(kAccessTokenValue, &access_token_); response_dict->GetInteger(kExpiresInValue, &expires_in_seconds_); } VLOG(1) << "Gaia response: acess_token='" << access_token_ << "', expires in " << expires_in_seconds_ << " second(s)"; } else { LOG(ERROR) << "Gaia response: response code=" << response_code; } if (access_token_.empty()) { delegate_->OnNetworkError(response_code); } else { FetchUserInfoAndInvokeCallback(); } } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::OnAuthTokenFetchComplete( const net::URLRequestStatus& status, int response_code, const std::string& response) { request_.reset(); if (!status.is_success()) { delegate_->OnNetworkError(response_code); return; } if (response_code == net::HTTP_BAD_REQUEST) { LOG(ERROR) << "Gaia response: response code=net::HTTP_BAD_REQUEST."; delegate_->OnOAuthError(); return; } if (response_code == net::HTTP_OK) { scoped_ptr<Value> message_value(base::JSONReader::Read(response)); if (message_value.get() && message_value->IsType(Value::TYPE_DICTIONARY)) { scoped_ptr<DictionaryValue> response_dict( static_cast<DictionaryValue*>(message_value.release())); std::string access_token; response_dict->GetString(kAccessTokenValue, &access_token); if (access_token.find("\r\n") != std::string::npos) { LOG(ERROR) << "Gaia response: access token include CRLF"; delegate_->OnOAuthError(); return; } access_token_ = access_token; response_dict->GetInteger(kExpiresInValue, &expires_in_seconds_); } VLOG(1) << "Gaia response: acess_token='" << access_token_ << "', expires in " << expires_in_seconds_ << " second(s)"; } else { LOG(ERROR) << "Gaia response: response code=" << response_code; } if (access_token_.empty()) { delegate_->OnNetworkError(response_code); } else { FetchUserInfoAndInvokeCallback(); } }
170,807
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { if (printer_.get()) printer_->GetDefaultPrintSettings(params); } 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
void ChromeMockRenderThread::OnGetDefaultPrintSettings( PrintMsg_Print_Params* params) { printer_->GetDefaultPrintSettings(params); }
170,851
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual bool IsURLAcceptableForWebUI( BrowserContext* browser_context, const GURL& url) const { return HasWebUIScheme(url); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual bool IsURLAcceptableForWebUI( BrowserContext* browser_context, const GURL& url) const { return content::GetContentClient()->HasWebUIScheme(url); } }; class TabContentsTestClient : public TestContentClient { public: TabContentsTestClient() { } virtual bool HasWebUIScheme(const GURL& url) const OVERRIDE { return url.SchemeIs("tabcontentstest"); }
171,013
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ExtensionFunction::ResponseAction UsbFindDevicesFunction::Run() { scoped_ptr<extensions::core_api::usb::FindDevices::Params> parameters = FindDevices::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(parameters.get()); vendor_id_ = parameters->options.vendor_id; product_id_ = parameters->options.product_id; interface_id_ = parameters->options.interface_id.get() ? *parameters->options.interface_id.get() : UsbDevicePermissionData::ANY_INTERFACE; UsbDevicePermission::CheckParam param(vendor_id_, product_id_, interface_id_); if (!extension()->permissions_data()->CheckAPIPermissionWithParam( APIPermission::kUsbDevice, &param)) { return RespondNow(Error(kErrorPermissionDenied)); } UsbService* service = device::DeviceClient::Get()->GetUsbService(); if (!service) { return RespondNow(Error(kErrorInitService)); } service->GetDevices( base::Bind(&UsbFindDevicesFunction::OnGetDevicesComplete, this)); return RespondLater(); } Commit Message: Remove fallback when requesting a single USB interface. This reverts commit 2d475d0ed37bf8f19385537ad31e361f1b21624b. The permission broker now supports opening devices that are partially claimed through the OpenPath method and RequestPathAccess will always fail for these devices so the fallback path from RequestPathAccess to OpenPath is always taken. BUG=500057 Review URL: https://codereview.chromium.org/1227313003 Cr-Commit-Position: refs/heads/master@{#338354} CWE ID: CWE-399
ExtensionFunction::ResponseAction UsbFindDevicesFunction::Run() { scoped_ptr<extensions::core_api::usb::FindDevices::Params> parameters = FindDevices::Params::Create(*args_); EXTENSION_FUNCTION_VALIDATE(parameters.get()); vendor_id_ = parameters->options.vendor_id; product_id_ = parameters->options.product_id; int interface_id = parameters->options.interface_id.get() ? *parameters->options.interface_id.get() : UsbDevicePermissionData::ANY_INTERFACE; UsbDevicePermission::CheckParam param(vendor_id_, product_id_, interface_id); if (!extension()->permissions_data()->CheckAPIPermissionWithParam( APIPermission::kUsbDevice, &param)) { return RespondNow(Error(kErrorPermissionDenied)); } UsbService* service = device::DeviceClient::Get()->GetUsbService(); if (!service) { return RespondNow(Error(kErrorInitService)); } service->GetDevices( base::Bind(&UsbFindDevicesFunction::OnGetDevicesComplete, this)); return RespondLater(); }
171,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || data_size < 8) { return ERROR_MALFORMED; } mSyncSampleOffset = data_offset; uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mNumSyncSamples = U32_AT(&header[4]); if (mNumSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } mSyncSamples = new uint32_t[mNumSyncSamples]; size_t size = mNumSyncSamples * sizeof(uint32_t); if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size) != (ssize_t)size) { return ERROR_IO; } for (size_t i = 0; i < mNumSyncSamples; ++i) { mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } return OK; } Commit Message: SampleTable: check integer overflow during table alloc Bug: 15328708 Bug: 15342615 Bug: 15342751 Change-Id: I6bb110a1eba46506799c73be8ff9a4f71c7e7053 CWE ID: CWE-189
status_t SampleTable::setSyncSampleParams(off64_t data_offset, size_t data_size) { if (mSyncSampleOffset >= 0 || data_size < 8) { return ERROR_MALFORMED; } mSyncSampleOffset = data_offset; uint8_t header[8]; if (mDataSource->readAt( data_offset, header, sizeof(header)) < (ssize_t)sizeof(header)) { return ERROR_IO; } if (U32_AT(header) != 0) { return ERROR_MALFORMED; } mNumSyncSamples = U32_AT(&header[4]); if (mNumSyncSamples < 2) { ALOGV("Table of sync samples is empty or has only a single entry!"); } uint64_t allocSize = mNumSyncSamples * sizeof(uint32_t); if (allocSize > SIZE_MAX) { return ERROR_OUT_OF_RANGE; } mSyncSamples = new uint32_t[mNumSyncSamples]; size_t size = mNumSyncSamples * sizeof(uint32_t); if (mDataSource->readAt(mSyncSampleOffset + 8, mSyncSamples, size) != (ssize_t)size) { return ERROR_IO; } for (size_t i = 0; i < mNumSyncSamples; ++i) { mSyncSamples[i] = ntohl(mSyncSamples[i]) - 1; } return OK; }
173,376
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mailimf_group_parse(const char * message, size_t length, size_t * indx, struct mailimf_group ** result) { size_t cur_token; char * display_name; struct mailimf_mailbox_list * mailbox_list; struct mailimf_group * group; int r; int res; cur_token = * indx; mailbox_list = NULL; r = mailimf_display_name_parse(message, length, &cur_token, &display_name); if (r != MAILIMF_NO_ERROR) { res = r; goto err; } r = mailimf_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_display_name; } r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list); switch (r) { case MAILIMF_NO_ERROR: break; case MAILIMF_ERROR_PARSE: r = mailimf_cfws_parse(message, length, &cur_token); if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) { res = r; goto free_display_name; } break; default: res = r; goto free_display_name; } r = mailimf_semi_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_mailbox_list; } group = mailimf_group_new(display_name, mailbox_list); if (group == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_mailbox_list; } * indx = cur_token; * result = group; return MAILIMF_NO_ERROR; free_mailbox_list: if (mailbox_list != NULL) { mailimf_mailbox_list_free(mailbox_list); } free_display_name: mailimf_display_name_free(display_name); err: return res; } Commit Message: Fixed crash #274 CWE ID: CWE-476
static int mailimf_group_parse(const char * message, size_t length, size_t * indx, struct mailimf_group ** result) { size_t cur_token; char * display_name; struct mailimf_mailbox_list * mailbox_list; struct mailimf_group * group; int r; int res; clist * list; cur_token = * indx; mailbox_list = NULL; r = mailimf_display_name_parse(message, length, &cur_token, &display_name); if (r != MAILIMF_NO_ERROR) { res = r; goto err; } r = mailimf_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_display_name; } r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list); switch (r) { case MAILIMF_NO_ERROR: break; case MAILIMF_ERROR_PARSE: r = mailimf_cfws_parse(message, length, &cur_token); if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) { res = r; goto free_display_name; } list = clist_new(); if (list == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_display_name; } mailbox_list = mailimf_mailbox_list_new(list); if (mailbox_list == NULL) { res = MAILIMF_ERROR_MEMORY; clist_free(list); goto free_display_name; } break; default: res = r; goto free_display_name; } r = mailimf_semi_colon_parse(message, length, &cur_token); if (r != MAILIMF_NO_ERROR) { res = r; goto free_mailbox_list; } group = mailimf_group_new(display_name, mailbox_list); if (group == NULL) { res = MAILIMF_ERROR_MEMORY; goto free_mailbox_list; } * indx = cur_token; * result = group; return MAILIMF_NO_ERROR; free_mailbox_list: if (mailbox_list != NULL) { mailimf_mailbox_list_free(mailbox_list); } free_display_name: mailimf_display_name_free(display_name); err: return res; }
168,192
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(stream_resolve_include_path) { char *filename, *resolved_path; int filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &filename, &filename_len) == FAILURE) { return; } resolved_path = zend_resolve_path(filename, filename_len TSRMLS_CC); if (resolved_path) { RETURN_STRING(resolved_path, 0); } RETURN_FALSE; } Commit Message: CWE ID: CWE-254
PHP_FUNCTION(stream_resolve_include_path) { char *filename, *resolved_path; int filename_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &filename, &filename_len) == FAILURE) { return; } resolved_path = zend_resolve_path(filename, filename_len TSRMLS_CC); if (resolved_path) { RETURN_STRING(resolved_path, 0); } RETURN_FALSE; }
165,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 accept_server_socket(int sfd) { struct sockaddr_un remote; struct pollfd pfd; int fd; socklen_t len = sizeof(struct sockaddr_un); BTIF_TRACE_EVENT("accept fd %d", sfd); /* make sure there is data to process */ pfd.fd = sfd; pfd.events = POLLIN; if (poll(&pfd, 1, 0) == 0) { BTIF_TRACE_EVENT("accept poll timeout"); return -1; } if ((fd = accept(sfd, (struct sockaddr *)&remote, &len)) == -1) { BTIF_TRACE_ERROR("sock accept failed (%s)", strerror(errno)); return -1; } return fd; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int accept_server_socket(int sfd) { struct sockaddr_un remote; struct pollfd pfd; int fd; socklen_t len = sizeof(struct sockaddr_un); BTIF_TRACE_EVENT("accept fd %d", sfd); /* make sure there is data to process */ pfd.fd = sfd; pfd.events = POLLIN; if (TEMP_FAILURE_RETRY(poll(&pfd, 1, 0)) == 0) { BTIF_TRACE_EVENT("accept poll timeout"); return -1; } if ((fd = TEMP_FAILURE_RETRY(accept(sfd, (struct sockaddr *)&remote, &len))) == -1) { BTIF_TRACE_ERROR("sock accept failed (%s)", strerror(errno)); return -1; } return fd; }
173,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readargs *args) { unsigned int len; int v; p = decode_fh(p, &args->fh); if (!p) return 0; args->offset = ntohl(*p++); len = args->count = ntohl(*p++); p++; /* totalcount - unused */ len = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2); /* set up somewhere to store response. * We take pages, put them on reslist and include in iovec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfssvc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd_readargs *args) { unsigned int len; int v; p = decode_fh(p, &args->fh); if (!p) return 0; args->offset = ntohl(*p++); len = args->count = ntohl(*p++); p++; /* totalcount - unused */ if (!xdr_argsize_check(rqstp, p)) return 0; len = min_t(unsigned int, len, NFSSVC_MAXBLKSIZE_V2); /* set up somewhere to store response. * We take pages, put them on reslist and include in iovec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return 1; }
168,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); } Commit Message: CVE-2017-12998/IS-IS: Check for 2 bytes if we're going to fetch 2 bytes. Probably a copy-and-pasteo. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
isis_print_extd_ip_reach(netdissect_options *ndo, const uint8_t *tptr, const char *ident, uint16_t afi) { char ident_buffer[20]; uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */ u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen; if (!ND_TTEST2(*tptr, 4)) return (0); metric = EXTRACT_32BITS(tptr); processed=4; tptr+=4; if (afi == AF_INET) { if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */ return (0); status_byte=*(tptr++); bit_length = status_byte&0x3f; if (bit_length > 32) { ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u", ident, bit_length)); return (0); } processed++; } else if (afi == AF_INET6) { if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */ return (0); status_byte=*(tptr++); bit_length=*(tptr++); if (bit_length > 128) { ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u", ident, bit_length)); return (0); } processed+=2; } else return (0); /* somebody is fooling us */ byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */ if (!ND_TTEST2(*tptr, byte_length)) return (0); memset(prefix, 0, sizeof prefix); /* clear the copy buffer */ memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */ tptr+=byte_length; processed+=byte_length; if (afi == AF_INET) ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u", ident, ipaddr_string(ndo, prefix), bit_length)); else if (afi == AF_INET6) ND_PRINT((ndo, "%sIPv6 prefix: %s/%u", ident, ip6addr_string(ndo, prefix), bit_length)); ND_PRINT((ndo, ", Distribution: %s, Metric: %u", ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up", metric)); if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) ND_PRINT((ndo, ", sub-TLVs present")); else if (afi == AF_INET6) ND_PRINT((ndo, ", %s%s", ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal", ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : "")); if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte)) || (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte)) ) { /* assume that one prefix can hold more than one subTLV - therefore the first byte must reflect the aggregate bytecount of the subTLVs for this prefix */ if (!ND_TTEST2(*tptr, 1)) return (0); sublen=*(tptr++); processed+=sublen+1; ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */ while (sublen>0) { if (!ND_TTEST2(*tptr,2)) return (0); subtlvtype=*(tptr++); subtlvlen=*(tptr++); /* prepend the indent string */ snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident); if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer)) return(0); tptr+=subtlvlen; sublen-=(subtlvlen+2); } } return (processed); }
167,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: long Track::GetFirst(const BlockEntry*& pBlockEntry) const { const Cluster* pCluster = m_pSegment->GetFirst(); for (int i = 0;;) { if (pCluster == NULL) { pBlockEntry = GetEOS(); return 1; } if (pCluster->EOS()) { #if 0 if (m_pSegment->Unparsed() <= 0) { //all clusters have been loaded pBlockEntry = GetEOS(); return 1; } #else if (m_pSegment->DoneParsing()) { pBlockEntry = GetEOS(); return 1; } #endif pBlockEntry = 0; return E_BUFFER_NOT_FULL; } long status = pCluster->GetFirst(pBlockEntry); if (status < 0) // error return status; if (pBlockEntry == 0) { // empty cluster pCluster = m_pSegment->GetNext(pCluster); continue; } for (;;) { const Block* const pBlock = pBlockEntry->GetBlock(); assert(pBlock); const long long tn = pBlock->GetTrackNumber(); if ((tn == m_info.number) && VetEntry(pBlockEntry)) return 0; const BlockEntry* pNextEntry; status = pCluster->GetNext(pBlockEntry, pNextEntry); if (status < 0) // error return status; if (pNextEntry == 0) break; pBlockEntry = pNextEntry; } ++i; if (i >= 100) break; pCluster = m_pSegment->GetNext(pCluster); } pBlockEntry = GetEOS(); // so we can return a non-NULL value return 1; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Track::GetFirst(const BlockEntry*& pBlockEntry) const { const Cluster* pCluster = m_pSegment->GetFirst(); for (int i = 0;;) { if (pCluster == NULL) { pBlockEntry = GetEOS(); return 1; } if (pCluster->EOS()) { if (m_pSegment->DoneParsing()) { pBlockEntry = GetEOS(); return 1; } pBlockEntry = 0; return E_BUFFER_NOT_FULL; } long status = pCluster->GetFirst(pBlockEntry); if (status < 0) // error return status; if (pBlockEntry == 0) { // empty cluster pCluster = m_pSegment->GetNext(pCluster); continue; } for (;;) { const Block* const pBlock = pBlockEntry->GetBlock(); assert(pBlock); const long long tn = pBlock->GetTrackNumber(); if ((tn == m_info.number) && VetEntry(pBlockEntry)) return 0; const BlockEntry* pNextEntry; status = pCluster->GetNext(pBlockEntry, pNextEntry); if (status < 0) // error return status; if (pNextEntry == 0) break; pBlockEntry = pNextEntry; } ++i; if (i >= 100) break; pCluster = m_pSegment->GetNext(pCluster); } pBlockEntry = GetEOS(); // so we can return a non-NULL value return 1; }
173,819
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UnloadController::TabDetachedImpl(TabContents* contents) { if (is_attempting_to_close_browser_) ClearUnloadState(contents->web_contents(), false); registrar_.Remove( this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::Source<content::WebContents>(contents->web_contents())); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void UnloadController::TabDetachedImpl(TabContents* contents) { void UnloadController::TabDetachedImpl(content::WebContents* contents) { if (is_attempting_to_close_browser_) ClearUnloadState(contents, false); registrar_.Remove(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::Source<content::WebContents>(contents)); }
171,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BaseRenderingContext2D::BaseRenderingContext2D() : clip_antialiasing_(kNotAntiAliased) { state_stack_.push_back(CanvasRenderingContext2DState::Create()); } Commit Message: [PE] Distinguish between tainting due to canvas content and filter. A filter on a canvas can itself lead to origin tainting, for reasons other than that the canvas contents are tainted. This CL changes to distinguish these two causes, so that we recompute filters on content-tainting change. Bug: 778506 Change-Id: I3cec8ef3b2772f2af78cdd4b290520113092cca6 Reviewed-on: https://chromium-review.googlesource.com/811767 Reviewed-by: Fredrik Söderquist <fs@opera.com> Commit-Queue: Chris Harrelson <chrishtr@chromium.org> Cr-Commit-Position: refs/heads/master@{#522274} CWE ID: CWE-200
BaseRenderingContext2D::BaseRenderingContext2D() : clip_antialiasing_(kNotAntiAliased), origin_tainted_by_content_(false) { state_stack_.push_back(CanvasRenderingContext2DState::Create()); }
172,904
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: base::string16 GetAppForProtocolUsingRegistry(const GURL& url) { base::string16 command_to_launch; base::string16 cmd_key_path = base::ASCIIToUTF16(url.scheme()); base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } cmd_key_path = base::ASCIIToUTF16(url.scheme() + "\\shell\\open\\command"); base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return base::string16(); } Commit Message: Validate external protocols before launching on Windows Bug: 889459 Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef Reviewed-on: https://chromium-review.googlesource.com/c/1256208 Reviewed-by: Greg Thompson <grt@chromium.org> Commit-Queue: Mustafa Emre Acer <meacer@chromium.org> Cr-Commit-Position: refs/heads/master@{#597611} CWE ID: CWE-20
base::string16 GetAppForProtocolUsingRegistry(const GURL& url) { const base::string16 url_scheme = base::ASCIIToUTF16(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) return base::string16(); base::string16 command_to_launch; base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, url_scheme.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } const base::string16 cmd_key_path = url_scheme + L"\\shell\\open\\command"; base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return base::string16(); }
172,636
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void scsi_dma_restart_bh(void *opaque) { SCSIDiskState *s = opaque; SCSIRequest *req; SCSIDiskReq *r; qemu_bh_delete(s->bh); s->bh = NULL; QTAILQ_FOREACH(req, &s->qdev.requests, next) { r = DO_UPCAST(SCSIDiskReq, req, req); if (r->status & SCSI_REQ_STATUS_RETRY) { int status = r->status; int ret; r->status &= ~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK); switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) { case SCSI_REQ_STATUS_RETRY_READ: scsi_read_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_WRITE: scsi_write_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_FLUSH: ret = scsi_disk_emulate_command(r, r->iov.iov_base); if (ret == 0) { scsi_req_complete(&r->req, GOOD); } } } } } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Kevin Wolf <kwolf@redhat.com> CWE ID: CWE-119
static void scsi_dma_restart_bh(void *opaque) { SCSIDiskState *s = opaque; SCSIRequest *req; SCSIDiskReq *r; qemu_bh_delete(s->bh); s->bh = NULL; QTAILQ_FOREACH(req, &s->qdev.requests, next) { r = DO_UPCAST(SCSIDiskReq, req, req); if (r->status & SCSI_REQ_STATUS_RETRY) { int status = r->status; int ret; r->status &= ~(SCSI_REQ_STATUS_RETRY | SCSI_REQ_STATUS_RETRY_TYPE_MASK); switch (status & SCSI_REQ_STATUS_RETRY_TYPE_MASK) { case SCSI_REQ_STATUS_RETRY_READ: scsi_read_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_WRITE: scsi_write_data(&r->req); break; case SCSI_REQ_STATUS_RETRY_FLUSH: ret = scsi_disk_emulate_command(r); if (ret == 0) { scsi_req_complete(&r->req, GOOD); } } } } }
166,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 XSSAuditor::Init(Document* document, XSSAuditorDelegate* auditor_delegate) { DCHECK(IsMainThread()); if (state_ != kUninitialized) return; state_ = kFilteringTokens; if (Settings* settings = document->GetSettings()) is_enabled_ = settings->GetXSSAuditorEnabled(); if (!is_enabled_) return; document_url_ = document->Url().Copy(); if (!document->GetFrame()) { is_enabled_ = false; return; } if (document_url_.IsEmpty()) { is_enabled_ = false; return; } if (document_url_.ProtocolIsData()) { is_enabled_ = false; return; } if (document->Encoding().IsValid()) encoding_ = document->Encoding(); if (DocumentLoader* document_loader = document->GetFrame()->Loader().GetDocumentLoader()) { const AtomicString& header_value = document_loader->GetResponse().HttpHeaderField( HTTPNames::X_XSS_Protection); String error_details; unsigned error_position = 0; String report_url; KURL xss_protection_report_url; ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader( header_value, error_details, error_position, report_url); if (xss_protection_header == kAllowReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled); else if (xss_protection_header == kFilterReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter); else if (xss_protection_header == kBlockReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock); else if (xss_protection_header == kReflectedXSSInvalid) UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid); did_send_valid_xss_protection_header_ = xss_protection_header != kReflectedXSSUnset && xss_protection_header != kReflectedXSSInvalid; if ((xss_protection_header == kFilterReflectedXSS || xss_protection_header == kBlockReflectedXSS) && !report_url.IsEmpty()) { xss_protection_report_url = document->CompleteURL(report_url); if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(), xss_protection_report_url)) { error_details = "insecure reporting URL for secure page"; xss_protection_header = kReflectedXSSInvalid; xss_protection_report_url = KURL(); } } if (xss_protection_header == kReflectedXSSInvalid) { document->AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Error parsing header X-XSS-Protection: " + header_value + ": " + error_details + " at character position " + String::Format("%u", error_position) + ". The default protections will be applied.")); } xss_protection_ = xss_protection_header; if (xss_protection_ == kReflectedXSSInvalid || xss_protection_ == kReflectedXSSUnset) { xss_protection_ = kBlockReflectedXSS; } if (auditor_delegate) auditor_delegate->SetReportURL(xss_protection_report_url.Copy()); EncodedFormData* http_body = document_loader->GetRequest().HttpBody(); if (http_body && !http_body->IsEmpty()) http_body_as_string_ = http_body->FlattenToString(); } SetEncoding(encoding_); } Commit Message: Restrict the xss audit report URL to same origin BUG=441275 R=tsepez@chromium.org,mkwst@chromium.org Change-Id: I27bc8e251b9ad962c3b4fdebf084a2b9152f915d Reviewed-on: https://chromium-review.googlesource.com/768367 Reviewed-by: Tom Sepez <tsepez@chromium.org> Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#516666} CWE ID: CWE-79
void XSSAuditor::Init(Document* document, XSSAuditorDelegate* auditor_delegate) { DCHECK(IsMainThread()); if (state_ != kUninitialized) return; state_ = kFilteringTokens; if (Settings* settings = document->GetSettings()) is_enabled_ = settings->GetXSSAuditorEnabled(); if (!is_enabled_) return; document_url_ = document->Url().Copy(); if (!document->GetFrame()) { is_enabled_ = false; return; } if (document_url_.IsEmpty()) { is_enabled_ = false; return; } if (document_url_.ProtocolIsData()) { is_enabled_ = false; return; } if (document->Encoding().IsValid()) encoding_ = document->Encoding(); if (DocumentLoader* document_loader = document->GetFrame()->Loader().GetDocumentLoader()) { const AtomicString& header_value = document_loader->GetResponse().HttpHeaderField( HTTPNames::X_XSS_Protection); String error_details; unsigned error_position = 0; String report_url; KURL xss_protection_report_url; ReflectedXSSDisposition xss_protection_header = ParseXSSProtectionHeader( header_value, error_details, error_position, report_url); if (xss_protection_header == kAllowReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorDisabled); else if (xss_protection_header == kFilterReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledFilter); else if (xss_protection_header == kBlockReflectedXSS) UseCounter::Count(*document, WebFeature::kXSSAuditorEnabledBlock); else if (xss_protection_header == kReflectedXSSInvalid) UseCounter::Count(*document, WebFeature::kXSSAuditorInvalid); did_send_valid_xss_protection_header_ = xss_protection_header != kReflectedXSSUnset && xss_protection_header != kReflectedXSSInvalid; if ((xss_protection_header == kFilterReflectedXSS || xss_protection_header == kBlockReflectedXSS) && !report_url.IsEmpty()) { xss_protection_report_url = document->CompleteURL(report_url); if (!SecurityOrigin::Create(xss_protection_report_url) ->IsSameSchemeHostPort(document->GetSecurityOrigin())) { error_details = "reporting URL is not same scheme, host, and port as page"; xss_protection_header = kReflectedXSSInvalid; xss_protection_report_url = KURL(); } if (MixedContentChecker::IsMixedContent(document->GetSecurityOrigin(), xss_protection_report_url)) { error_details = "insecure reporting URL for secure page"; xss_protection_header = kReflectedXSSInvalid; xss_protection_report_url = KURL(); } } if (xss_protection_header == kReflectedXSSInvalid) { document->AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Error parsing header X-XSS-Protection: " + header_value + ": " + error_details + " at character position " + String::Format("%u", error_position) + ". The default protections will be applied.")); } xss_protection_ = xss_protection_header; if (xss_protection_ == kReflectedXSSInvalid || xss_protection_ == kReflectedXSSUnset) { xss_protection_ = kBlockReflectedXSS; } if (auditor_delegate) auditor_delegate->SetReportURL(xss_protection_report_url.Copy()); EncodedFormData* http_body = document_loader->GetRequest().HttpBody(); if (http_body && !http_body->IsEmpty()) http_body_as_string_ = http_body->FlattenToString(); } SetEncoding(encoding_); }
172,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np) { struct platform_device *pdev = cqspi->pdev; struct device *dev = &pdev->dev; struct cqspi_flash_pdata *f_pdata; struct spi_nor *nor; struct mtd_info *mtd; unsigned int cs; int i, ret; /* Get flash device data */ for_each_available_child_of_node(dev->of_node, np) { if (of_property_read_u32(np, "reg", &cs)) { dev_err(dev, "Couldn't determine chip select.\n"); goto err; } if (cs > CQSPI_MAX_CHIPSELECT) { dev_err(dev, "Chip select %d out of range.\n", cs); goto err; } f_pdata = &cqspi->f_pdata[cs]; f_pdata->cqspi = cqspi; f_pdata->cs = cs; ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np); if (ret) goto err; nor = &f_pdata->nor; mtd = &nor->mtd; mtd->priv = nor; nor->dev = dev; spi_nor_set_flash_node(nor, np); nor->priv = f_pdata; nor->read_reg = cqspi_read_reg; nor->write_reg = cqspi_write_reg; nor->read = cqspi_read; nor->write = cqspi_write; nor->erase = cqspi_erase; nor->prepare = cqspi_prep; nor->unprepare = cqspi_unprep; mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d", dev_name(dev), cs); if (!mtd->name) { ret = -ENOMEM; goto err; } ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD); if (ret) goto err; ret = mtd_device_register(mtd, NULL, 0); if (ret) goto err; f_pdata->registered = true; } return 0; err: for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++) if (cqspi->f_pdata[i].registered) mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd); return ret; } Commit Message: mtd: spi-nor: Off by one in cqspi_setup_flash() There are CQSPI_MAX_CHIPSELECT elements in the ->f_pdata array so the > should be >=. Fixes: 140623410536 ('mtd: spi-nor: Add driver for Cadence Quad SPI Flash Controller') Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Reviewed-by: Marek Vasut <marex@denx.de> Signed-off-by: Cyrille Pitchen <cyrille.pitchen@atmel.com> CWE ID: CWE-119
static int cqspi_setup_flash(struct cqspi_st *cqspi, struct device_node *np) { struct platform_device *pdev = cqspi->pdev; struct device *dev = &pdev->dev; struct cqspi_flash_pdata *f_pdata; struct spi_nor *nor; struct mtd_info *mtd; unsigned int cs; int i, ret; /* Get flash device data */ for_each_available_child_of_node(dev->of_node, np) { if (of_property_read_u32(np, "reg", &cs)) { dev_err(dev, "Couldn't determine chip select.\n"); goto err; } if (cs >= CQSPI_MAX_CHIPSELECT) { dev_err(dev, "Chip select %d out of range.\n", cs); goto err; } f_pdata = &cqspi->f_pdata[cs]; f_pdata->cqspi = cqspi; f_pdata->cs = cs; ret = cqspi_of_get_flash_pdata(pdev, f_pdata, np); if (ret) goto err; nor = &f_pdata->nor; mtd = &nor->mtd; mtd->priv = nor; nor->dev = dev; spi_nor_set_flash_node(nor, np); nor->priv = f_pdata; nor->read_reg = cqspi_read_reg; nor->write_reg = cqspi_write_reg; nor->read = cqspi_read; nor->write = cqspi_write; nor->erase = cqspi_erase; nor->prepare = cqspi_prep; nor->unprepare = cqspi_unprep; mtd->name = devm_kasprintf(dev, GFP_KERNEL, "%s.%d", dev_name(dev), cs); if (!mtd->name) { ret = -ENOMEM; goto err; } ret = spi_nor_scan(nor, NULL, SPI_NOR_QUAD); if (ret) goto err; ret = mtd_device_register(mtd, NULL, 0); if (ret) goto err; f_pdata->registered = true; } return 0; err: for (i = 0; i < CQSPI_MAX_CHIPSELECT; i++) if (cqspi->f_pdata[i].registered) mtd_device_unregister(&cqspi->f_pdata[i].nor.mtd); return ret; }
169,861
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 int add_post_vars(zval *arr, post_var_data_t *vars, zend_bool eof TSRMLS_DC) { uint64_t max_vars = PG(max_input_vars); vars->ptr = vars->str.c; vars->end = vars->str.c + vars->str.len; while (add_post_var(arr, vars, eof TSRMLS_CC)) { if (++vars->cnt > max_vars) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %" PRIu64 ". " "To increase the limit change max_input_vars in php.ini.", max_vars); return FAILURE; } } if (!eof) { memmove(vars->str.c, vars->ptr, vars->str.len = vars->end - vars->ptr); } return SUCCESS; } Commit Message: Fix bug #73807 CWE ID: CWE-400
static inline int add_post_vars(zval *arr, post_var_data_t *vars, zend_bool eof TSRMLS_DC) { uint64_t max_vars = PG(max_input_vars); vars->ptr = vars->str.c; vars->end = vars->str.c + vars->str.len; while (add_post_var(arr, vars, eof TSRMLS_CC)) { if (++vars->cnt > max_vars) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %" PRIu64 ". " "To increase the limit change max_input_vars in php.ini.", max_vars); return FAILURE; } } if (!eof && vars->str.c != vars->ptr) { memmove(vars->str.c, vars->ptr, vars->str.len = vars->end - vars->ptr); } return SUCCESS; }
168,055
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXARIAGridCell::isAriaRowHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringCase(role, "rowheader"); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXARIAGridCell::isAriaRowHeader() const { const AtomicString& role = getAttribute(HTMLNames::roleAttr); return equalIgnoringASCIICase(role, "rowheader"); }
171,902
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::Seek(long long time_ns, const BlockEntry*& pResult) const { const long status = GetFirst(pResult); if (status < 0) // buffer underflow, etc return status; assert(pResult); if (pResult->EOS()) return 0; const Cluster* pCluster = pResult->GetCluster(); assert(pCluster); assert(pCluster->GetIndex() >= 0); if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) return 0; Cluster** const clusters = m_pSegment->m_clusters; assert(clusters); const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded assert(count > 0); Cluster** const i = clusters + pCluster->GetIndex(); assert(i); assert(*i == pCluster); assert(pCluster->GetTime() <= time_ns); Cluster** const j = clusters + count; Cluster** lo = i; Cluster** hi = j; while (lo < hi) { Cluster** const mid = lo + (hi - lo) / 2; assert(mid < hi); pCluster = *mid; assert(pCluster); assert(pCluster->GetIndex() >= 0); assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); const long long t = pCluster->GetTime(); if (t <= time_ns) lo = mid + 1; else hi = mid; assert(lo <= hi); } assert(lo == hi); assert(lo > i); assert(lo <= j); pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); pResult = pCluster->GetEntry(this, time_ns); if ((pResult != 0) && !pResult->EOS()) // found a keyframe return 0; while (lo != i) { pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); #if 0 pResult = pCluster->GetMaxKey(this); #else pResult = pCluster->GetEntry(this, time_ns); #endif if ((pResult != 0) && !pResult->EOS()) return 0; } pResult = GetEOS(); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const { const long status = GetFirst(pResult); if (status < 0) // buffer underflow, etc return status; assert(pResult); if (pResult->EOS()) return 0; const Cluster* pCluster = pResult->GetCluster(); assert(pCluster); assert(pCluster->GetIndex() >= 0); if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) return 0; Cluster** const clusters = m_pSegment->m_clusters; assert(clusters); const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded assert(count > 0); Cluster** const i = clusters + pCluster->GetIndex(); assert(i); assert(*i == pCluster); assert(pCluster->GetTime() <= time_ns); Cluster** const j = clusters + count; Cluster** lo = i; Cluster** hi = j; while (lo < hi) { Cluster** const mid = lo + (hi - lo) / 2; assert(mid < hi); pCluster = *mid; assert(pCluster); assert(pCluster->GetIndex() >= 0); assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); const long long t = pCluster->GetTime(); if (t <= time_ns) lo = mid + 1; else hi = mid; assert(lo <= hi); } assert(lo == hi); assert(lo > i); assert(lo <= j); pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); pResult = pCluster->GetEntry(this, time_ns); if ((pResult != 0) && !pResult->EOS()) // found a keyframe return 0; while (lo != i) { pCluster = *--lo; assert(pCluster); assert(pCluster->GetTime() <= time_ns); pResult = pCluster->GetEntry(this, time_ns); if ((pResult != 0) && !pResult->EOS()) return 0; } pResult = GetEOS(); return 0; }
173,863
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: e1000e_ring_empty(E1000ECore *core, const E1000E_RingInfo *r) { return core->mac[r->dh] == core->mac[r->dt]; } Commit Message: CWE ID: CWE-835
e1000e_ring_empty(E1000ECore *core, const E1000E_RingInfo *r) { return core->mac[r->dh] == core->mac[r->dt] || core->mac[r->dt] >= core->mac[r->dlen] / E1000_RING_DESC_LEN; }
164,799
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 P2PSocketDispatcherHost::OnAcceptIncomingTcpConnection( const IPC::Message& msg, int listen_socket_id, net::IPEndPoint remote_address, int connected_socket_id) { P2PSocketHost* socket = LookupSocket(msg.routing_id(), listen_socket_id); if (!socket) { LOG(ERROR) << "Received P2PHostMsg_AcceptIncomingTcpConnection " "for invalid socket_id."; return; } P2PSocketHost* accepted_connection = socket->AcceptIncomingTcpConnection(remote_address, connected_socket_id); if (accepted_connection) { sockets_.insert(std::pair<ExtendedSocketId, P2PSocketHost*>( ExtendedSocketId(msg.routing_id(), connected_socket_id), accepted_connection)); } } Commit Message: Fixing Coverity bugs (DEAD_CODE and PASS_BY_VALUE) CIDs 16230, 16439, 16610, 16635 BUG=NONE TEST=NONE Review URL: http://codereview.chromium.org/7215029 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@90134 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void P2PSocketDispatcherHost::OnAcceptIncomingTcpConnection( const IPC::Message& msg, int listen_socket_id, const net::IPEndPoint& remote_address, int connected_socket_id) { P2PSocketHost* socket = LookupSocket(msg.routing_id(), listen_socket_id); if (!socket) { LOG(ERROR) << "Received P2PHostMsg_AcceptIncomingTcpConnection " "for invalid socket_id."; return; } P2PSocketHost* accepted_connection = socket->AcceptIncomingTcpConnection(remote_address, connected_socket_id); if (accepted_connection) { sockets_.insert(std::pair<ExtendedSocketId, P2PSocketHost*>( ExtendedSocketId(msg.routing_id(), connected_socket_id), accepted_connection)); } }
170,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionSettingsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { RegisterTitle(localized_strings, "extensionSettings", IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE); localized_strings->SetString("extensionSettingsVisitWebsite", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VISIT_WEBSITE)); localized_strings->SetString("extensionSettingsDeveloperMode", l10n_util::GetStringUTF16(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings->SetString("extensionSettingsNoExtensions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings->SetString("extensionSettingsSuggestGallery", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsGetMoreExtensions", l10n_util::GetStringFUTF16(IDS_GET_MORE_EXTENSIONS, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsExtensionId", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ID)); localized_strings->SetString("extensionSettingsExtensionPath", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PATH)); localized_strings->SetString("extensionSettingsInspectViews", l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings->SetString("viewIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VIEW_INCOGNITO)); localized_strings->SetString("extensionSettingsEnable", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE)); localized_strings->SetString("extensionSettingsEnabled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLED)); localized_strings->SetString("extensionSettingsRemove", l10n_util::GetStringUTF16(IDS_EXTENSIONS_REMOVE)); localized_strings->SetString("extensionSettingsEnableIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE_INCOGNITO)); localized_strings->SetString("extensionSettingsAllowFileAccess", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ALLOW_FILE_ACCESS)); localized_strings->SetString("extensionSettingsIncognitoWarning", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_INCOGNITO_WARNING, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME))); localized_strings->SetString("extensionSettingsReload", l10n_util::GetStringUTF16(IDS_EXTENSIONS_RELOAD)); localized_strings->SetString("extensionSettingsOptions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS)); localized_strings->SetString("extensionSettingsPolicyControlled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_POLICY_CONTROLLED)); localized_strings->SetString("extensionSettingsShowButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_BUTTON)); localized_strings->SetString("extensionSettingsLoadUnpackedButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings->SetString("extensionSettingsPackButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings->SetString("extensionSettingsUpdateButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings->SetString("extensionSettingsCrashMessage", l10n_util::GetStringUTF16(IDS_EXTENSIONS_CRASHED_EXTENSION)); localized_strings->SetString("extensionSettingsInDevelopment", l10n_util::GetStringUTF16(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings->SetString("extensionSettingsWarningsTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WARNINGS_TITLE)); localized_strings->SetString("extensionSettingsShowDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS)); localized_strings->SetString("extensionSettingsHideDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS)); } 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 ExtensionSettingsHandler::GetLocalizedValues( DictionaryValue* localized_strings) { RegisterTitle(localized_strings, "extensionSettings", IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE); localized_strings->SetString("extensionSettingsVisitWebsite", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VISIT_WEBSITE)); localized_strings->SetString("extensionSettingsDeveloperMode", l10n_util::GetStringUTF16(IDS_EXTENSIONS_DEVELOPER_MODE_LINK)); localized_strings->SetString("extensionSettingsNoExtensions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_NONE_INSTALLED)); localized_strings->SetString("extensionSettingsSuggestGallery", l10n_util::GetStringFUTF16(IDS_EXTENSIONS_NONE_INSTALLED_SUGGEST_GALLERY, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsGetMoreExtensions", l10n_util::GetStringFUTF16(IDS_GET_MORE_EXTENSIONS, ASCIIToUTF16(google_util::AppendGoogleLocaleParam( GURL(extension_urls::GetWebstoreLaunchURL())).spec()))); localized_strings->SetString("extensionSettingsExtensionId", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ID)); localized_strings->SetString("extensionSettingsExtensionPath", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PATH)); localized_strings->SetString("extensionSettingsInspectViews", l10n_util::GetStringUTF16(IDS_EXTENSIONS_INSPECT_VIEWS)); localized_strings->SetString("viewIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_VIEW_INCOGNITO)); localized_strings->SetString("extensionSettingsEnable", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE)); localized_strings->SetString("extensionSettingsEnabled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLED)); localized_strings->SetString("extensionSettingsRemove", l10n_util::GetStringUTF16(IDS_EXTENSIONS_REMOVE)); localized_strings->SetString("extensionSettingsEnableIncognito", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ENABLE_INCOGNITO)); localized_strings->SetString("extensionSettingsAllowFileAccess", l10n_util::GetStringUTF16(IDS_EXTENSIONS_ALLOW_FILE_ACCESS)); localized_strings->SetString("extensionSettingsIncognitoWarning", l10n_util::GetStringUTF16(IDS_EXTENSIONS_INCOGNITO_WARNING)); localized_strings->SetString("extensionSettingsReload", l10n_util::GetStringUTF16(IDS_EXTENSIONS_RELOAD)); localized_strings->SetString("extensionSettingsOptions", l10n_util::GetStringUTF16(IDS_EXTENSIONS_OPTIONS)); localized_strings->SetString("extensionSettingsPolicyControlled", l10n_util::GetStringUTF16(IDS_EXTENSIONS_POLICY_CONTROLLED)); localized_strings->SetString("extensionSettingsShowButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_BUTTON)); localized_strings->SetString("extensionSettingsLoadUnpackedButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_UNPACKED_BUTTON)); localized_strings->SetString("extensionSettingsPackButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_PACK_BUTTON)); localized_strings->SetString("extensionSettingsUpdateButton", l10n_util::GetStringUTF16(IDS_EXTENSIONS_UPDATE_BUTTON)); localized_strings->SetString("extensionSettingsCrashMessage", l10n_util::GetStringUTF16(IDS_EXTENSIONS_CRASHED_EXTENSION)); localized_strings->SetString("extensionSettingsInDevelopment", l10n_util::GetStringUTF16(IDS_EXTENSIONS_IN_DEVELOPMENT)); localized_strings->SetString("extensionSettingsWarningsTitle", l10n_util::GetStringUTF16(IDS_EXTENSION_WARNINGS_TITLE)); localized_strings->SetString("extensionSettingsShowDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_SHOW_DETAILS)); localized_strings->SetString("extensionSettingsHideDetails", l10n_util::GetStringUTF16(IDS_EXTENSIONS_HIDE_DETAILS)); }
170,986
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UserInitiatedInfo CreateUserInitiatedInfo( content::NavigationHandle* navigation_handle, PageLoadTracker* committed_load) { if (!navigation_handle->IsRendererInitiated()) return UserInitiatedInfo::BrowserInitiated(); return UserInitiatedInfo::RenderInitiated( navigation_handle->HasUserGesture()); } Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation. Also refactor UkmPageLoadMetricsObserver to use this new boolean to report the user initiated metric in RecordPageLoadExtraInfoMetrics, so that it works correctly in the case when the page load failed. Bug: 925104 Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff Reviewed-on: https://chromium-review.googlesource.com/c/1450460 Commit-Queue: Annie Sullivan <sullivan@chromium.org> Reviewed-by: Bryan McQuade <bmcquade@chromium.org> Cr-Commit-Position: refs/heads/master@{#630870} CWE ID: CWE-79
UserInitiatedInfo CreateUserInitiatedInfo( content::NavigationHandle* navigation_handle, PageLoadTracker* committed_load) { if (!navigation_handle->IsRendererInitiated()) return UserInitiatedInfo::BrowserInitiated(); return UserInitiatedInfo::RenderInitiated( navigation_handle->HasUserGesture(), !navigation_handle->NavigationInputStart().is_null()); }
172,495
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MagickBooleanType ConcatenateImages(int argc,char **argv, ExceptionInfo *exception ) { FILE *input, *output; int c; register ssize_t i; if (ExpandFilenames(&argc,&argv) == MagickFalse) ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed", GetExceptionMessage(errno)); output=fopen_utf8(argv[argc-1],"wb"); if (output == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[argc-1]); return(MagickFalse); } for (i=2; i < (ssize_t) (argc-1); i++) { #if 0 fprintf(stderr, "DEBUG: Concatenate Image: \"%s\"\n", argv[i]); #endif input=fopen_utf8(argv[i],"rb"); if (input == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]); continue; } for (c=fgetc(input); c != EOF; c=fgetc(input)) (void) fputc((char) c,output); (void) fclose(input); (void) remove_utf8(argv[i]); } (void) fclose(output); return(MagickTrue); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/196 CWE ID: CWE-20
static MagickBooleanType ConcatenateImages(int argc,char **argv, ExceptionInfo *exception ) { FILE *input, *output; MagickBooleanType status; int c; register ssize_t i; if (ExpandFilenames(&argc,&argv) == MagickFalse) ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed", GetExceptionMessage(errno)); output=fopen_utf8(argv[argc-1],"wb"); if (output == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", argv[argc-1]); return(MagickFalse); } status=MagickTrue; for (i=2; i < (ssize_t) (argc-1); i++) { input=fopen_utf8(argv[i],"rb"); if (input == (FILE *) NULL) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]); continue; } for (c=fgetc(input); c != EOF; c=fgetc(input)) if (fputc((char) c,output) != c) status=MagickFalse; (void) fclose(input); (void) remove_utf8(argv[i]); } (void) fclose(output); return(status); }
168,628
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4], const DVprofile *sys) { int size, chan, i, j, d, of, smpls, freq, quant, half_ch; uint16_t lc, rc; const uint8_t* as_pack; uint8_t *pcm, ipcm; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack) /* No audio ? */ return 0; smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (quant > 1) return -1; /* unsupported quantization */ size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */ half_ch = sys->difseg_size / 2; /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0; pcm = ppcm[ipcm++]; /* for each DIF channel */ for (chan = 0; chan < sys->n_difchan; chan++) { /* for each DIF segment */ for (i = 0; i < sys->difseg_size; i++) { frame += 6 * 80; /* skip DIF segment header */ break; } /* for each AV sequence */ for (j = 0; j < 9; j++) { for (d = 8; d < 80; d += 2) { if (quant == 0) { /* 16bit quantization */ of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00) pcm[of*2+1] = 0; } else { /* 12bit quantization */ lc = ((uint16_t)frame[d] << 4) | ((uint16_t)frame[d+2] >> 4); rc = ((uint16_t)frame[d+1] << 4) | ((uint16_t)frame[d+2] & 0x0f); lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc)); rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc)); of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM of = sys->audio_shuffle[i%half_ch+half_ch][j] + (d - 8) / 3 * sys->audio_stride; pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM ++d; } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } Commit Message: CWE ID: CWE-20
static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4], const DVprofile *sys) { int size, chan, i, j, d, of, smpls, freq, quant, half_ch; uint16_t lc, rc; const uint8_t* as_pack; uint8_t *pcm, ipcm; as_pack = dv_extract_pack(frame, dv_audio_source); if (!as_pack) /* No audio ? */ return 0; smpls = as_pack[1] & 0x3f; /* samples in this frame - min. samples */ freq = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */ quant = as_pack[4] & 0x07; /* 0 - 16bit linear, 1 - 12bit nonlinear */ if (quant > 1) return -1; /* unsupported quantization */ size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */ half_ch = sys->difseg_size / 2; /* We work with 720p frames split in half, thus even frames have * channels 0,1 and odd 2,3. */ ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0; /* for each DIF channel */ for (chan = 0; chan < sys->n_difchan; chan++) { /* next stereo channel (50Mbps and 100Mbps only) */ pcm = ppcm[ipcm++]; if (!pcm) break; /* for each DIF segment */ for (i = 0; i < sys->difseg_size; i++) { frame += 6 * 80; /* skip DIF segment header */ break; } /* for each AV sequence */ for (j = 0; j < 9; j++) { for (d = 8; d < 80; d += 2) { if (quant == 0) { /* 16bit quantization */ of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = frame[d+1]; // FIXME: maybe we have to admit pcm[of*2+1] = frame[d]; // that DV is a big-endian PCM if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00) pcm[of*2+1] = 0; } else { /* 12bit quantization */ lc = ((uint16_t)frame[d] << 4) | ((uint16_t)frame[d+2] >> 4); rc = ((uint16_t)frame[d+1] << 4) | ((uint16_t)frame[d+2] & 0x0f); lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc)); rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc)); of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride; if (of*2 >= size) continue; pcm[of*2] = lc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = lc >> 8; // that DV is a big-endian PCM of = sys->audio_shuffle[i%half_ch+half_ch][j] + (d - 8) / 3 * sys->audio_stride; pcm[of*2] = rc & 0xff; // FIXME: maybe we have to admit pcm[of*2+1] = rc >> 8; // that DV is a big-endian PCM ++d; } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ } } frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */ }
165,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: my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error) { *ret = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, unset_and_free_gvalue); g_hash_table_foreach (vals, hash_foreach_stringify, *ret); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error)
165,112
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintWebViewHelper::OnPrintForSystemDialog() { blink::WebLocalFrame* frame = print_preview_context_.source_frame(); if (!frame) { NOTREACHED(); return; } Print(frame, print_preview_context_.source_node(), false); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintForSystemDialog() { CHECK_LE(ipc_nesting_level_, 1); blink::WebLocalFrame* frame = print_preview_context_.source_frame(); if (!frame) { NOTREACHED(); return; } Print(frame, print_preview_context_.source_node(), false); }
171,874
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) break; /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } elen += sizeof(struct pathComponent) + pc->lengthComponentIdent; } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; } Commit Message: udf: Check component length before reading it Check that length specified in a component of a symlink fits in the input buffer we are reading. Also properly ignore component length for component types that do not use it. Otherwise we read memory after end of buffer for corrupted udf image. Reported-by: Carl Henrik Lunde <chlunde@ping.uio.no> CC: stable@vger.kernel.org Signed-off-by: Jan Kara <jack@suse.cz> CWE ID:
static int udf_pc_to_char(struct super_block *sb, unsigned char *from, int fromlen, unsigned char *to, int tolen) { struct pathComponent *pc; int elen = 0; int comp_len; unsigned char *p = to; /* Reserve one byte for terminating \0 */ tolen--; while (elen < fromlen) { pc = (struct pathComponent *)(from + elen); elen += sizeof(struct pathComponent); switch (pc->componentType) { case 1: /* * Symlink points to some place which should be agreed * upon between originator and receiver of the media. Ignore. */ if (pc->lengthComponentIdent > 0) { elen += pc->lengthComponentIdent; break; } /* Fall through */ case 2: if (tolen == 0) return -ENAMETOOLONG; p = to; *p++ = '/'; tolen--; break; case 3: if (tolen < 3) return -ENAMETOOLONG; memcpy(p, "../", 3); p += 3; tolen -= 3; break; case 4: if (tolen < 2) return -ENAMETOOLONG; memcpy(p, "./", 2); p += 2; tolen -= 2; /* that would be . - just ignore */ break; case 5: elen += pc->lengthComponentIdent; if (elen > fromlen) return -EIO; comp_len = udf_get_filename(sb, pc->componentIdent, pc->lengthComponentIdent, p, tolen); p += comp_len; tolen -= comp_len; if (tolen == 0) return -ENAMETOOLONG; *p++ = '/'; tolen--; break; } } if (p > to + 1) p[-1] = '\0'; else p[0] = '\0'; return 0; }
166,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: null_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int length = h->len; u_int caplen = h->caplen; u_int family; if (caplen < NULL_HDRLEN) { ND_PRINT((ndo, "[|null]")); return (NULL_HDRLEN); } memcpy((char *)&family, (const char *)p, sizeof(family)); /* * This isn't necessarily in our host byte order; if this is * a DLT_LOOP capture, it's in network byte order, and if * this is a DLT_NULL capture from a machine with the opposite * byte-order, it's in the opposite byte order from ours. * * If the upper 16 bits aren't all zero, assume it's byte-swapped. */ if ((family & 0xFFFF0000) != 0) family = SWAPLONG(family); if (ndo->ndo_eflag) null_hdr_print(ndo, family, length); length -= NULL_HDRLEN; caplen -= NULL_HDRLEN; p += NULL_HDRLEN; switch (family) { case BSD_AFNUM_INET: ip_print(ndo, p, length); break; case BSD_AFNUM_INET6_BSD: case BSD_AFNUM_INET6_FREEBSD: case BSD_AFNUM_INET6_DARWIN: ip6_print(ndo, p, length); break; case BSD_AFNUM_ISO: isoclns_print(ndo, p, length, caplen); break; case BSD_AFNUM_APPLETALK: atalk_print(ndo, p, length); break; case BSD_AFNUM_IPX: ipx_print(ndo, p, length); break; default: /* unknown AF_ value */ if (!ndo->ndo_eflag) null_hdr_print(ndo, family, length + NULL_HDRLEN); if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); } return (NULL_HDRLEN); } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
null_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int length = h->len; u_int caplen = h->caplen; u_int family; if (caplen < NULL_HDRLEN) { ND_PRINT((ndo, "[|null]")); return (NULL_HDRLEN); } memcpy((char *)&family, (const char *)p, sizeof(family)); /* * This isn't necessarily in our host byte order; if this is * a DLT_LOOP capture, it's in network byte order, and if * this is a DLT_NULL capture from a machine with the opposite * byte-order, it's in the opposite byte order from ours. * * If the upper 16 bits aren't all zero, assume it's byte-swapped. */ if ((family & 0xFFFF0000) != 0) family = SWAPLONG(family); if (ndo->ndo_eflag) null_hdr_print(ndo, family, length); length -= NULL_HDRLEN; caplen -= NULL_HDRLEN; p += NULL_HDRLEN; switch (family) { case BSD_AFNUM_INET: ip_print(ndo, p, length); break; case BSD_AFNUM_INET6_BSD: case BSD_AFNUM_INET6_FREEBSD: case BSD_AFNUM_INET6_DARWIN: ip6_print(ndo, p, length); break; case BSD_AFNUM_ISO: isoclns_print(ndo, p, length); break; case BSD_AFNUM_APPLETALK: atalk_print(ndo, p, length); break; case BSD_AFNUM_IPX: ipx_print(ndo, p, length); break; default: /* unknown AF_ value */ if (!ndo->ndo_eflag) null_hdr_print(ndo, family, length + NULL_HDRLEN); if (!ndo->ndo_suppress_default_print) ND_DEFAULTPRINT(p, caplen); } return (NULL_HDRLEN); }
167,955
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::setConfig( OMX_INDEXTYPE index, const void *params, size_t size) { Mutex::Autolock autoLock(mLock); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; CLOG_CONFIG(setConfig, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params); OMX_ERRORTYPE err = OMX_SetConfig( mHandle, index, const_cast<void *>(params)); CLOG_IF_ERROR(setConfig, err, "%s(%#x)", asString(extIndex), index); return StatusFromOMXError(err); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::setConfig( OMX_INDEXTYPE index, const void *params, size_t size) { Mutex::Autolock autoLock(mLock); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; CLOG_CONFIG(setConfig, "%s(%#x), %zu@%p)", asString(extIndex), index, size, params); if (isProhibitedIndex_l(index)) { android_errorWriteLog(0x534e4554, "29422020"); return BAD_INDEX; } OMX_ERRORTYPE err = OMX_SetConfig( mHandle, index, const_cast<void *>(params)); CLOG_IF_ERROR(setConfig, err, "%s(%#x)", asString(extIndex), index); return StatusFromOMXError(err); }
174,138
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; int maxlen ; char *start ; maxlen = strlen ((char*) psf->header) ; start = ((char*) psf->header) + maxlen ; maxlen = sizeof (psf->header) - maxlen ; va_start (argptr, format) ; vsnprintf (start, maxlen, format, argptr) ; va_end (argptr) ; /* Make sure the string is properly terminated. */ start [maxlen - 1] = 0 ; psf->headindex = strlen ((char*) psf->header) ; return ; } /* psf_asciiheader_printf */ 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_asciiheader_printf (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; int maxlen ; char *start ; maxlen = strlen ((char*) psf->header.ptr) ; start = ((char*) psf->header.ptr) + maxlen ; maxlen = psf->header.len - maxlen ; va_start (argptr, format) ; vsnprintf (start, maxlen, format, argptr) ; va_end (argptr) ; /* Make sure the string is properly terminated. */ start [maxlen - 1] = 0 ; psf->header.indx = strlen ((char*) psf->header.ptr) ; return ; } /* psf_asciiheader_printf */
170,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserContextDestroyer::FinishDestroyContext() { DCHECK_EQ(pending_hosts_, 0U); delete context_; context_ = nullptr; delete this; } Commit Message: CWE ID: CWE-20
void BrowserContextDestroyer::FinishDestroyContext() { DCHECK(finish_destroy_scheduled_); CHECK_EQ(GetHostsForContext(context_.get()).size(), 0U) << "One or more RenderProcessHosts exist whilst its BrowserContext is " << "being deleted!"; g_contexts_pending_deletion.Get().remove(this); if (context_->IsOffTheRecord()) { // If this is an OTR context and its owner BrowserContext has been scheduled // for deletion, update the owner's BrowserContextDestroyer BrowserContextDestroyer* orig_destroyer = GetForContext(context_->GetOriginalContext()); if (orig_destroyer) { DCHECK_GT(orig_destroyer->otr_contexts_pending_deletion_, 0U); DCHECK(!orig_destroyer->finish_destroy_scheduled_); --orig_destroyer->otr_contexts_pending_deletion_; orig_destroyer->MaybeScheduleFinishDestroyContext(); } } delete this; }
165,420
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sycc444_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; unsigned int maxw, maxh, max, i; int offset, upb; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * (size_t)max); d1 = g = (int*)malloc(sizeof(int) * (size_t)max); d2 = b = (int*)malloc(sizeof(int) * (size_t)max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i = 0U; i < max; ++i) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++cb; ++cr; ++r; ++g; ++b; } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; return; fails: if(r) free(r); if(g) free(g); if(b) free(b); }/* sycc444_to_rgb() */ Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745) 42x Images with an odd x0/y0 lead to subsampled component starting at the 2nd column/line. That is offset = comp->dx * comp->x0 - image->x0 = 1 Fix #726 CWE ID: CWE-125
static void sycc444_to_rgb(opj_image_t *img) { int *d0, *d1, *d2, *r, *g, *b; const int *y, *cb, *cr; size_t maxw, maxh, max, i; int offset, upb; upb = (int)img->comps[0].prec; offset = 1<<(upb - 1); upb = (1<<upb)-1; maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h; max = maxw * maxh; y = img->comps[0].data; cb = img->comps[1].data; cr = img->comps[2].data; d0 = r = (int*)malloc(sizeof(int) * max); d1 = g = (int*)malloc(sizeof(int) * max); d2 = b = (int*)malloc(sizeof(int) * max); if(r == NULL || g == NULL || b == NULL) goto fails; for(i = 0U; i < max; ++i) { sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b); ++y; ++cb; ++cr; ++r; ++g; ++b; } free(img->comps[0].data); img->comps[0].data = d0; free(img->comps[1].data); img->comps[1].data = d1; free(img->comps[2].data); img->comps[2].data = d2; img->color_space = OPJ_CLRSPC_SRGB; return; fails: free(r); free(g); free(b); }/* sycc444_to_rgb() */
168,841
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Edition::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x36) // Atom ID { status = ParseAtom(pReader, pos, size); if (status < 0) // error return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Edition::Parse( Segment* const pSegment = pChapters->m_pSegment; if (pSegment == NULL) // weird return -1; const SegmentInfo* const pInfo = pSegment->GetInfo(); if (pInfo == NULL) return -1; const long long timecode_scale = pInfo->GetTimeCodeScale(); if (timecode_scale < 1) // weird return -1; if (timecode < 0) return -1; const long long result = timecode_scale * timecode; return result; } long Chapters::Atom::ParseDisplay(IMkvReader* pReader, long long pos, long long size) { if (!ExpandDisplaysArray()) return -1; Display& d = m_displays[m_displays_count++]; d.Init(); return d.Parse(pReader, pos, size); } bool Chapters::Atom::ExpandDisplaysArray() { if (m_displays_size > m_displays_count) return true; // nothing else to do const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; Display* const displays = new (std::nothrow) Display[size]; if (displays == NULL) return false; for (int idx = 0; idx < m_displays_count; ++idx) { m_displays[idx].ShallowCopy(displays[idx]); } delete[] m_displays; m_displays = displays; m_displays_size = size; return true; } Chapters::Display::Display() {} Chapters::Display::~Display() {} const char* Chapters::Display::GetString() const { return m_string; } const char* Chapters::Display::GetLanguage() const { return m_language; } const char* Chapters::Display::GetCountry() const { return m_country; } void Chapters::Display::Init() { m_string = NULL; m_language = NULL; m_country = NULL; } void Chapters::Display::ShallowCopy(Display& rhs) const { rhs.m_string = m_string; rhs.m_language = m_language; rhs.m_country = m_country; } void Chapters::Display::Clear() { delete[] m_string; m_string = NULL; delete[] m_language; m_language = NULL; delete[] m_country; m_country = NULL; } long Chapters::Display::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) { // ChapterString ID status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) { // ChapterLanguage ID status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) { // ChapterCountry ID status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; }
174,401
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WtsSessionProcessDelegate::Core::OnJobNotification(DWORD message, DWORD pid) { DCHECK(main_task_runner_->BelongsToCurrentThread()); switch (message) { case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: CHECK(SetEvent(process_exit_event_)); break; case JOB_OBJECT_MSG_NEW_PROCESS: worker_process_.Set(OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid)); break; } } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void WtsSessionProcessDelegate::Core::OnJobNotification(DWORD message, DWORD pid) { DCHECK(main_task_runner_->BelongsToCurrentThread()); switch (message) { case JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO: CHECK(SetEvent(process_exit_event_)); break; case JOB_OBJECT_MSG_NEW_PROCESS: worker_process_.Set(OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid)); break; } }
171,561
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { u8 perm_addr[MAX_ADDR_LEN]; if (!netdev->dcbnl_ops->getpermhwaddr) return -EOPNOTSUPP; netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr); return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr); } Commit Message: dcbnl: fix various netlink info leaks The dcb netlink interface leaks stack memory in various places: * perm_addr[] buffer is only filled at max with 12 of the 32 bytes but copied completely, * no in-kernel driver fills all fields of an IEEE 802.1Qaz subcommand, so we're leaking up to 58 bytes for ieee_ets structs, up to 136 bytes for ieee_pfc structs, etc., * the same is true for CEE -- no in-kernel driver fills the whole struct, Prevent all of the above stack info leaks by properly initializing the buffers/structures involved. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-399
static int dcbnl_getperm_hwaddr(struct net_device *netdev, struct nlmsghdr *nlh, u32 seq, struct nlattr **tb, struct sk_buff *skb) { u8 perm_addr[MAX_ADDR_LEN]; if (!netdev->dcbnl_ops->getpermhwaddr) return -EOPNOTSUPP; memset(perm_addr, 0, sizeof(perm_addr)); netdev->dcbnl_ops->getpermhwaddr(netdev, perm_addr); return nla_put(skb, DCB_ATTR_PERM_HWADDR, sizeof(perm_addr), perm_addr); }
166,058
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame, const GURL& url, GURL* new_url) { if (url.SchemeIs(chrome::kExtensionScheme) && !ExtensionResourceRequestPolicy::CanRequestResource( url, GURL(frame->document().url()), extension_dispatcher_->extensions())) { *new_url = GURL("chrome-extension://invalid/"); return true; } return false; } Commit Message: Do not require DevTools extension resources to be white-listed in manifest. Currently, resources used by DevTools extensions need to be white-listed as web_accessible_resources in manifest. This is quite inconvenitent and appears to be an overkill, given the fact that DevTools front-end is (a) trusted and (b) picky on the frames it loads. This change adds resources that belong to DevTools extensions and are being loaded into a DevTools front-end page to the list of exceptions from web_accessible_resources check. BUG=none TEST=DevToolsExtensionTest.* Review URL: https://chromiumcodereview.appspot.com/9663076 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126378 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool ChromeContentRendererClient::WillSendRequest(WebKit::WebFrame* frame, const GURL& url, GURL* new_url) { if (url.SchemeIs(chrome::kExtensionScheme) && !ExtensionResourceRequestPolicy::CanRequestResource( url, frame, extension_dispatcher_->extensions())) { *new_url = GURL("chrome-extension://invalid/"); return true; } return false; }
171,000
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func) { irda_queue_t* queue; unsigned long flags = 0; int i; IRDA_ASSERT(hashbin != NULL, return -1;); IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;); /* Synchronize */ if ( hashbin->hb_type & HB_LOCK ) { spin_lock_irqsave_nested(&hashbin->hb_spinlock, flags, hashbin_lock_depth++); } /* * Free the entries in the hashbin, TODO: use hashbin_clear when * it has been shown to work */ for (i = 0; i < HASHBIN_SIZE; i ++ ) { queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]); while (queue ) { if (free_func) (*free_func)(queue); queue = dequeue_first( (irda_queue_t**) &hashbin->hb_queue[i]); } } /* Cleanup local data */ hashbin->hb_current = NULL; hashbin->magic = ~HB_MAGIC; /* Release lock */ if ( hashbin->hb_type & HB_LOCK) { spin_unlock_irqrestore(&hashbin->hb_spinlock, flags); #ifdef CONFIG_LOCKDEP hashbin_lock_depth--; #endif } /* * Free the hashbin structure */ kfree(hashbin); return 0; } Commit Message: irda: Fix lockdep annotations in hashbin_delete(). A nested lock depth was added to the hasbin_delete() code but it doesn't actually work some well and results in tons of lockdep splats. Fix the code instead to properly drop the lock around the operation and just keep peeking the head of the hashbin queue. Reported-by: Dmitry Vyukov <dvyukov@google.com> Tested-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
int hashbin_delete( hashbin_t* hashbin, FREE_FUNC free_func) { irda_queue_t* queue; unsigned long flags = 0; int i; IRDA_ASSERT(hashbin != NULL, return -1;); IRDA_ASSERT(hashbin->magic == HB_MAGIC, return -1;); /* Synchronize */ if (hashbin->hb_type & HB_LOCK) spin_lock_irqsave(&hashbin->hb_spinlock, flags); /* * Free the entries in the hashbin, TODO: use hashbin_clear when * it has been shown to work */ for (i = 0; i < HASHBIN_SIZE; i ++ ) { while (1) { queue = dequeue_first((irda_queue_t**) &hashbin->hb_queue[i]); if (!queue) break; if (free_func) { if (hashbin->hb_type & HB_LOCK) spin_unlock_irqrestore(&hashbin->hb_spinlock, flags); free_func(queue); if (hashbin->hb_type & HB_LOCK) spin_lock_irqsave(&hashbin->hb_spinlock, flags); } } } /* Cleanup local data */ hashbin->hb_current = NULL; hashbin->magic = ~HB_MAGIC; /* Release lock */ if (hashbin->hb_type & HB_LOCK) spin_unlock_irqrestore(&hashbin->hb_spinlock, flags); /* * Free the hashbin structure */ kfree(hashbin); return 0; }
168,344
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::OnDownloadStarted(const std::string& filename, const std::string& mime_type) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); ScopedJavaLocalRef<jstring> jmime_type = ConvertUTF8ToJavaString(env, mime_type); Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename, jmime_type); } 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::OnDownloadStarted(const std::string& filename, void ChromeDownloadDelegate::OnDownloadStarted(const std::string& filename) { JNIEnv* env = base::android::AttachCurrentThread(); ScopedJavaLocalRef<jstring> jfilename = ConvertUTF8ToJavaString( env, filename); Java_ChromeDownloadDelegate_onDownloadStarted(env, java_ref_, jfilename); }
171,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } Commit Message: CWE ID: CWE-476
Ins_GETVARIATION( TT_ExecContext exc, FT_Long* args ) { FT_UInt num_axes = exc->face->blend->num_axis; FT_Fixed* coords = exc->face->blend->normalizedcoords; FT_UInt i; if ( BOUNDS( num_axes, exc->stackSize + 1 - exc->top ) ) { exc->error = FT_THROW( Stack_Overflow ); return; } if ( coords ) { for ( i = 0; i < num_axes; i++ ) args[i] = coords[i] >> 2; /* convert 16.16 to 2.14 format */ } else { for ( i = 0; i < num_axes; i++ ) args[i] = 0; } }
165,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, open_flags); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, open_flags); spin_unlock(&state->owner->so_lock); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, int open_flags) static void __update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, const nfs4_stateid *deleg_stateid, fmode_t fmode) { /* * Protect the call to nfs4_state_set_mode_locked and * serialise the stateid update */ write_seqlock(&state->seqlock); if (deleg_stateid != NULL) { memcpy(state->stateid.data, deleg_stateid->data, sizeof(state->stateid.data)); set_bit(NFS_DELEGATED_STATE, &state->flags); } if (open_stateid != NULL) nfs_set_open_stateid_locked(state, open_stateid, fmode); write_sequnlock(&state->seqlock); spin_lock(&state->owner->so_lock); update_open_stateflags(state, fmode); spin_unlock(&state->owner->so_lock); }
165,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sec_decrypt(uint8 * data, int length) { if (g_sec_decrypt_use_count == 4096) { sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key); rdssl_rc4_set_key(&g_rc4_decrypt_key, g_sec_decrypt_key, g_rc4_key_len); g_sec_decrypt_use_count = 0; } rdssl_rc4_crypt(&g_rc4_decrypt_key, data, data, length); g_sec_decrypt_use_count++; } 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
sec_decrypt(uint8 * data, int length) { if (length <= 0) return; if (g_sec_decrypt_use_count == 4096) { sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key); rdssl_rc4_set_key(&g_rc4_decrypt_key, g_sec_decrypt_key, g_rc4_key_len); g_sec_decrypt_use_count = 0; } rdssl_rc4_crypt(&g_rc4_decrypt_key, data, data, length); g_sec_decrypt_use_count++; }
169,810
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebsiteSettingsPopupAndroid::WebsiteSettingsPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, content::WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; url_ = nav_entry->GetURL(); popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
WebsiteSettingsPopupAndroid::WebsiteSettingsPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, content::WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; url_ = nav_entry->GetURL(); popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), web_contents, nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); }
171,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind( &CoordinatorImpl::OnChromeMemoryDumpResponse, base::Unretained(this)); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, base::Unretained(this), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, base::Unretained(this), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, base::Unretained(this), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, base::Unretained(this), request->dump_guid), kHeapDumpTimeout); } FinalizeGlobalMemoryDumpIfAllManagersReplied(); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <hjd@chromium.org> Commit-Queue: Hector Dearman <hjd@chromium.org> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind(&CoordinatorImpl::OnChromeMemoryDumpResponse, weak_ptr_factory_.GetWeakPtr()); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, weak_ptr_factory_.GetWeakPtr(), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, weak_ptr_factory_.GetWeakPtr(), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, weak_ptr_factory_.GetWeakPtr(), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, weak_ptr_factory_.GetWeakPtr(), request->dump_guid), kHeapDumpTimeout); } FinalizeGlobalMemoryDumpIfAllManagersReplied(); }
173,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftAMRNBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrnb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeNB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeNB7) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = amrParams->eAMRBandMode - 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftAMRNBEncoder::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (strncmp((const char *)roleParams->cRole, "audio_encoder.amrnb", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioPortFormat: { const OMX_AUDIO_PARAM_PORTFORMATTYPE *formatParams = (const OMX_AUDIO_PARAM_PORTFORMATTYPE *)params; if (!isValidOMXParam(formatParams)) { return OMX_ErrorBadParameter; } if (formatParams->nPortIndex > 1) { return OMX_ErrorUndefined; } if (formatParams->nIndex > 0) { return OMX_ErrorNoMore; } if ((formatParams->nPortIndex == 0 && formatParams->eEncoding != OMX_AUDIO_CodingPCM) || (formatParams->nPortIndex == 1 && formatParams->eEncoding != OMX_AUDIO_CodingAMR)) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } case OMX_IndexParamAudioAmr: { OMX_AUDIO_PARAM_AMRTYPE *amrParams = (OMX_AUDIO_PARAM_AMRTYPE *)params; if (!isValidOMXParam(amrParams)) { return OMX_ErrorBadParameter; } if (amrParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (amrParams->nChannels != 1 || amrParams->eAMRDTXMode != OMX_AUDIO_AMRDTXModeOff || amrParams->eAMRFrameFormat != OMX_AUDIO_AMRFrameFormatFSF || amrParams->eAMRBandMode < OMX_AUDIO_AMRBandModeNB0 || amrParams->eAMRBandMode > OMX_AUDIO_AMRBandModeNB7) { return OMX_ErrorUndefined; } mBitRate = amrParams->nBitRate; mMode = amrParams->eAMRBandMode - 1; amrParams->eAMRDTXMode = OMX_AUDIO_AMRDTXModeOff; amrParams->eAMRFrameFormat = OMX_AUDIO_AMRFrameFormatFSF; return OMX_ErrorNone; } case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0) { return OMX_ErrorUndefined; } if (pcmParams->nChannels != 1 || pcmParams->nSamplingRate != (OMX_U32)kSampleRate) { return OMX_ErrorUndefined; } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS && !zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); efree(buf); smart_str_free(&auth); return 1; } return 0; } Commit Message: CWE ID:
int basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS && Z_TYPE_PP(login) == IS_STRING && !zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS && Z_TYPE_PP(password) == IS_STRING) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); efree(buf); smart_str_free(&auth); return 1; } return 0; }
165,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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[]) { struct mg_context *ctx; base::AtExitManager exit; base::WaitableEvent shutdown_event(false, false); CommandLine::Init(argc, argv); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); #if defined(OS_POSIX) signal(SIGPIPE, SIG_IGN); #endif srand((unsigned int)time(NULL)); chrome::RegisterPathProvider(); TestTimeouts::Initialize(); InitChromeDriverLogging(*cmd_line); std::string port = "9515"; std::string root; std::string url_base; if (cmd_line->HasSwitch("port")) port = cmd_line->GetSwitchValueASCII("port"); if (cmd_line->HasSwitch("root")) root = cmd_line->GetSwitchValueASCII("root"); if (cmd_line->HasSwitch("url-base")) url_base = cmd_line->GetSwitchValueASCII("url-base"); webdriver::SessionManager* manager = webdriver::SessionManager::GetInstance(); manager->set_port(port); manager->set_url_base(url_base); ctx = mg_start(); if (!SetMongooseOptions(ctx, port, root)) { mg_stop(ctx); #if defined(OS_WIN) return WSAEADDRINUSE; #else return EADDRINUSE; #endif } webdriver::Dispatcher dispatcher(ctx, url_base); webdriver::InitCallbacks(ctx, &dispatcher, &shutdown_event, root.empty()); std::cout << "Started ChromeDriver" << std::endl << "port=" << port << std::endl; if (root.length()) { VLOG(1) << "Serving files from the current working directory"; } shutdown_event.Wait(); mg_stop(ctx); return (EXIT_SUCCESS); } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
int main(int argc, char *argv[]) { struct mg_context *ctx; base::AtExitManager exit; base::WaitableEvent shutdown_event(false, false); CommandLine::Init(argc, argv); CommandLine* cmd_line = CommandLine::ForCurrentProcess(); #if defined(OS_POSIX) signal(SIGPIPE, SIG_IGN); #endif srand((unsigned int)time(NULL)); chrome::RegisterPathProvider(); TestTimeouts::Initialize(); std::string port = "9515"; std::string root; std::string url_base; bool verbose = false; if (cmd_line->HasSwitch("port")) port = cmd_line->GetSwitchValueASCII("port"); if (cmd_line->HasSwitch("root")) root = cmd_line->GetSwitchValueASCII("root"); if (cmd_line->HasSwitch("url-base")) url_base = cmd_line->GetSwitchValueASCII("url-base"); // Whether or not to do verbose logging. if (cmd_line->HasSwitch("verbose")) verbose = true; webdriver::InitWebDriverLogging( verbose ? logging::LOG_INFO : logging::LOG_WARNING); webdriver::SessionManager* manager = webdriver::SessionManager::GetInstance(); manager->set_port(port); manager->set_url_base(url_base); ctx = mg_start(); if (!SetMongooseOptions(ctx, port, root)) { mg_stop(ctx); #if defined(OS_WIN) return WSAEADDRINUSE; #else return EADDRINUSE; #endif } webdriver::Dispatcher dispatcher(ctx, url_base); webdriver::InitCallbacks(ctx, &dispatcher, &shutdown_event, root.empty()); std::cout << "Started ChromeDriver" << std::endl << "port=" << port << std::endl; if (root.length()) { VLOG(1) << "Serving files from the current working directory"; } shutdown_event.Wait(); mg_stop(ctx); return (EXIT_SUCCESS); }
170,462
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void timer_config_save(UNUSED_ATTR void *data) { assert(config != NULL); assert(alarm_timer != NULL); static const size_t CACHE_MAX = 256; const char *keys[CACHE_MAX]; size_t num_keys = 0; size_t total_candidates = 0; pthread_mutex_lock(&lock); for (const config_section_node_t *snode = config_section_begin(config); snode != config_section_end(config); snode = config_section_next(snode)) { const char *section = config_section_name(snode); if (!string_is_bdaddr(section)) continue; if (config_has_key(config, section, "LinkKey") || config_has_key(config, section, "LE_KEY_PENC") || config_has_key(config, section, "LE_KEY_PID") || config_has_key(config, section, "LE_KEY_PCSRK") || config_has_key(config, section, "LE_KEY_LENC") || config_has_key(config, section, "LE_KEY_LCSRK")) continue; if (num_keys < CACHE_MAX) keys[num_keys++] = section; ++total_candidates; } if (total_candidates > CACHE_MAX * 2) while (num_keys > 0) config_remove_section(config, keys[--num_keys]); config_save(config, CONFIG_FILE_PATH); pthread_mutex_unlock(&lock); } Commit Message: Fix crashes with lots of discovered LE devices When loads of devices are discovered a config file which is too large can be written out, which causes the BT daemon to crash on startup. This limits the number of config entries for unpaired devices which are initialized, and prevents a large number from being saved to the filesystem. Bug: 26071376 Change-Id: I4a74094f57a82b17f94e99a819974b8bc8082184 CWE ID: CWE-119
static void timer_config_save(UNUSED_ATTR void *data) { static void timer_config_save_cb(UNUSED_ATTR void *data) { btif_config_write(); } static void btif_config_write(void) { assert(config != NULL); assert(alarm_timer != NULL); btif_config_devcache_cleanup(); pthread_mutex_lock(&lock); config_save(config, CONFIG_FILE_PATH); pthread_mutex_unlock(&lock); }
173,931
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_AddItemToArray( cJSON *array, cJSON *item ) { cJSON *c = array->child; if ( ! item ) return; if ( ! c ) { array->child = item; } else { while ( c && c->next ) c = c->next; suffix_object( c, item ); } } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_AddItemToArray( cJSON *array, cJSON *item )
167,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const char* SegmentInfo::GetTitleAsUTF8() const { return m_pTitleAsUTF8; } 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
const char* SegmentInfo::GetTitleAsUTF8() const
174,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: ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: ip_printts(ndo, cp, option_len); break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: CVE-2017-13037/IP: Add bounds checks when printing time stamp options. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: if (ip_printts(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); }
167,845
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AutofillPopupBaseView::AddExtraInitParams( views::Widget::InitParams* params) { params->opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params->shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
void AutofillPopupBaseView::AddExtraInitParams(
172,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: static int au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { unsigned int len; unsigned long start=0, off; struct au1200fb_device *fbdev = info->par; if (vma->vm_pgoff > (~0UL >> PAGE_SHIFT)) { return -EINVAL; } start = fbdev->fb_phys & PAGE_MASK; len = PAGE_ALIGN((start & ~PAGE_MASK) + fbdev->fb_len); off = vma->vm_pgoff << PAGE_SHIFT; if ((vma->vm_end - vma->vm_start + off) > len) { return -EINVAL; } off += start; vma->vm_pgoff = off >> PAGE_SHIFT; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); pgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */ return io_remap_pfn_range(vma, vma->vm_start, off >> PAGE_SHIFT, vma->vm_end - vma->vm_start, vma->vm_page_prot); } Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that really should use the vm_iomap_memory() helper. This trivially converts two of them to the helper, and comments about why the third one really needs to continue to use remap_pfn_range(), and adds the missing size check. Reported-by: Nico Golde <nico@ngolde.de> Cc: stable@kernel.org Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org. CWE ID: CWE-119
static int au1200fb_fb_mmap(struct fb_info *info, struct vm_area_struct *vma) { struct au1200fb_device *fbdev = info->par; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); pgprot_val(vma->vm_page_prot) |= _CACHE_MASK; /* CCA=7 */ return vm_iomap_memory(vma, fbdev->fb_phys, fbdev->fb_len); }
165,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); /* Flush temporal reference */ impeg2d_bit_stream_get(ps_stream,10); /* Picture type */ ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3); if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC)) { impeg2d_next_code(ps_dec, PICTURE_START_CODE); return IMPEG2D_INVALID_PIC_TYPE; } /* Flush vbv_delay */ impeg2d_bit_stream_get(ps_stream,16); if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC) { ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3); } if(ps_dec->e_pic_type == B_PIC) { ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3); } if(ps_dec->u2_is_mpeg2 == 0) { ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code; ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code; } /*-----------------------------------------------------------------------*/ /* Flush the extra bit value */ /* */ /* while(impeg2d_bit_stream_nxt() == '1') */ /* { */ /* extra_bit_picture 1 */ /* extra_information_picture 8 */ /* } */ /* extra_bit_picture 1 */ /*-----------------------------------------------------------------------*/ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 && ps_stream->u4_offset < ps_stream->u4_max_offset) { impeg2d_bit_stream_get(ps_stream,9); } impeg2d_bit_stream_get_bit(ps_stream); impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; } Commit Message: Adding Error Check for f_code Parameters In MPEG1, the valid range for the forward and backward f_code parameters is [1, 7]. Adding a check to enforce this. Without the check, the value could be 0. We read (f_code - 1) bits from the stream and reading a negative number of bits from the stream is undefined. Bug: 64550583 Test: monitored temp ALOGD() output Change-Id: Ia452cd43a28e9d566401f515947164635361782f (cherry picked from commit 71d734b83d72e8a59f73f1230982da97615d2689) CWE ID: CWE-200
IMPEG2D_ERROR_CODES_T impeg2d_dec_pic_hdr(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN); /* Flush temporal reference */ impeg2d_bit_stream_get(ps_stream,10); /* Picture type */ ps_dec->e_pic_type = (e_pic_type_t)impeg2d_bit_stream_get(ps_stream,3); if((ps_dec->e_pic_type < I_PIC) || (ps_dec->e_pic_type > D_PIC)) { impeg2d_next_code(ps_dec, PICTURE_START_CODE); return IMPEG2D_INVALID_PIC_TYPE; } /* Flush vbv_delay */ impeg2d_bit_stream_get(ps_stream,16); if(ps_dec->e_pic_type == P_PIC || ps_dec->e_pic_type == B_PIC) { ps_dec->u2_full_pel_forw_vector = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_forw_f_code = impeg2d_bit_stream_get(ps_stream,3); } if(ps_dec->e_pic_type == B_PIC) { ps_dec->u2_full_pel_back_vector = impeg2d_bit_stream_get_bit(ps_stream); ps_dec->u2_back_f_code = impeg2d_bit_stream_get(ps_stream,3); } if(ps_dec->u2_is_mpeg2 == 0) { if (ps_dec->u2_forw_f_code < 1 || ps_dec->u2_forw_f_code > 7 || ps_dec->u2_back_f_code < 1 || ps_dec->u2_back_f_code > 7) { return IMPEG2D_UNKNOWN_ERROR; } ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code; ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code; } /*-----------------------------------------------------------------------*/ /* Flush the extra bit value */ /* */ /* while(impeg2d_bit_stream_nxt() == '1') */ /* { */ /* extra_bit_picture 1 */ /* extra_information_picture 8 */ /* } */ /* extra_bit_picture 1 */ /*-----------------------------------------------------------------------*/ while (impeg2d_bit_stream_nxt(ps_stream,1) == 1 && ps_stream->u4_offset < ps_stream->u4_max_offset) { impeg2d_bit_stream_get(ps_stream,9); } impeg2d_bit_stream_get_bit(ps_stream); impeg2d_next_start_code(ps_dec); return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; }
174,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TracingControllerImpl::TracingControllerImpl() : delegate_(GetContentClient()->browser()->GetTracingDelegate()), weak_ptr_factory_(this) { DCHECK(!g_tracing_controller); DCHECK_CURRENTLY_ON(BrowserThread::UI); base::FileTracing::SetProvider(new FileTracingProviderImpl); AddAgents(); base::trace_event::TraceLog::GetInstance()->AddAsyncEnabledStateObserver( weak_ptr_factory_.GetWeakPtr()); g_tracing_controller = this; } Commit Message: Tracing: Connect to service on startup Temporary workaround for flaky tests introduced by https://chromium-review.googlesource.com/c/chromium/src/+/1439082 TBR=eseckler@chromium.org Bug: 928410, 928363 Change-Id: I0dcf20cbdf91a7beea167a220ba9ef7e0604c1ab Reviewed-on: https://chromium-review.googlesource.com/c/1452767 Reviewed-by: oysteine <oysteine@chromium.org> Reviewed-by: Eric Seckler <eseckler@chromium.org> Reviewed-by: Aaron Gable <agable@chromium.org> Commit-Queue: oysteine <oysteine@chromium.org> Cr-Commit-Position: refs/heads/master@{#631052} CWE ID: CWE-19
TracingControllerImpl::TracingControllerImpl() : delegate_(GetContentClient()->browser()->GetTracingDelegate()), weak_ptr_factory_(this) { DCHECK(!g_tracing_controller); DCHECK_CURRENTLY_ON(BrowserThread::UI); base::FileTracing::SetProvider(new FileTracingProviderImpl); AddAgents(); base::trace_event::TraceLog::GetInstance()->AddAsyncEnabledStateObserver( weak_ptr_factory_.GetWeakPtr()); g_tracing_controller = this; // TODO(oysteine): Instead of connecting right away, we should connect // in StartTracing once this no longer causes test flakiness. ConnectToServiceIfNeeded(); }
172,057
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DrawingBuffer::ReadBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder readback_order, WebGLImageConversion::AlphaOp op) { DCHECK(state_restorer_); state_restorer_->SetPixelPackAlignmentDirty(); gl_->PixelStorei(GL_PACK_ALIGNMENT, 1); gl_->ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); size_t buffer_size = 4 * width * height; if (readback_order == kReadbackSkia) { #if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT for (size_t i = 0; i < buffer_size; i += 4) { std::swap(pixels[i], pixels[i + 2]); } #endif } if (op == WebGLImageConversion::kAlphaDoPremultiply) { for (size_t i = 0; i < buffer_size; i += 4) { pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255); pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255); pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255); } } else if (op != WebGLImageConversion::kAlphaDoNothing) { NOTREACHED(); } } 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 R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
void DrawingBuffer::ReadBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder readback_order, WebGLImageConversion::AlphaOp op) { DCHECK(state_restorer_); state_restorer_->SetPixelPackParametersDirty(); gl_->PixelStorei(GL_PACK_ALIGNMENT, 1); if (webgl_version_ > kWebGL1) { gl_->PixelStorei(GL_PACK_SKIP_ROWS, 0); gl_->PixelStorei(GL_PACK_SKIP_PIXELS, 0); gl_->PixelStorei(GL_PACK_ROW_LENGTH, 0); state_restorer_->SetPixelPackBufferBindingDirty(); gl_->BindBuffer(GL_PIXEL_PACK_BUFFER, 0); } gl_->ReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); size_t buffer_size = 4 * width * height; if (readback_order == kReadbackSkia) { #if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT for (size_t i = 0; i < buffer_size; i += 4) { std::swap(pixels[i], pixels[i + 2]); } #endif } if (op == WebGLImageConversion::kAlphaDoPremultiply) { for (size_t i = 0; i < buffer_size; i += 4) { pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255); pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255); pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255); } } else if (op != WebGLImageConversion::kAlphaDoNothing) { NOTREACHED(); } }
172,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify) { GIOChannel *handle, *ssl_handle; handle = net_connect_ip(ip, port, my_ip); if (handle == NULL) return NULL; ssl_handle = irssi_ssl_get_iochannel(handle, cert, pkey, cafile, capath, verify); if (ssl_handle == NULL) g_io_channel_unref(handle); return ssl_handle; } Commit Message: Check if an SSL certificate matches the hostname of the server we are connecting to git-svn-id: http://svn.irssi.org/repos/irssi/trunk@5104 dbcabf3a-b0e7-0310-adc4-f8d773084564 CWE ID: CWE-20
GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify) GIOChannel *net_connect_ip_ssl(IPADDR *ip, int port, const char* hostname, IPADDR *my_ip, const char *cert, const char *pkey, const char *cafile, const char *capath, gboolean verify) { GIOChannel *handle, *ssl_handle; handle = net_connect_ip(ip, port, my_ip); if (handle == NULL) return NULL; ssl_handle = irssi_ssl_get_iochannel(handle, hostname, cert, pkey, cafile, capath, verify); if (ssl_handle == NULL) g_io_channel_unref(handle); return ssl_handle; }
165,519
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, rs_ctx ); #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else if( f_rng_blind != NULL ) ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, f_rng_blind, p_rng_blind, rs_ctx ); else { mbedtls_hmac_drbg_context *p_rng_blind_det; #if !defined(MBEDTLS_ECP_RESTARTABLE) /* * To avoid reusing rng_ctx and risking incorrect behavior we seed a * second HMAC-DRBG with the same seed. We also apply a label to avoid * reusing the bits of the ephemeral key for blinding and eliminate the * risk that they leak this way. */ const char* blind_label = "BLINDING CONTEXT"; mbedtls_hmac_drbg_context rng_ctx_blind; mbedtls_hmac_drbg_init( &rng_ctx_blind ); p_rng_blind_det = &rng_ctx_blind; mbedtls_hmac_drbg_seed_buf( p_rng_blind_det, md_info, data, 2 * grp_len ); ret = mbedtls_hmac_drbg_update_ret( p_rng_blind_det, (const unsigned char*) blind_label, strlen( blind_label ) ); if( ret != 0 ) { mbedtls_hmac_drbg_free( &rng_ctx_blind ); goto cleanup; } #else /* * In the case of restartable computations we would either need to store * the second RNG in the restart context too or set it up at every * restart. The first option would penalize the correct application of * the function and the second would defeat the purpose of the * restartable feature. * * Therefore in this case we reuse the original RNG. This comes with the * price that the resulting signature might not be a valid deterministic * ECDSA signature with a very low probability (same magnitude as * successfully guessing the private key). However even then it is still * a valid ECDSA signature. */ p_rng_blind_det = p_rng; #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Since the output of the RNGs is always the same for the same key and * message, this limits the efficiency of blinding and leaks information * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL * won't be a valid value for f_rng_blind anymore. Therefore it should * be checked by the caller and this branch and check can be removed. */ ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, mbedtls_hmac_drbg_random, p_rng_blind_det, rs_ctx ); #if !defined(MBEDTLS_ECP_RESTARTABLE) mbedtls_hmac_drbg_free( &rng_ctx_blind ); #endif } #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); }
169,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos, unsigned int *pv) { unsigned int field_type; unsigned int value_count; field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian); value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian); if(value_count!=1) return 0; if(field_type==3) { // SHORT (uint16) *pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian); return 1; } else if(field_type==4) { // LONG (uint32) *pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian); return 1; } return 0; } Commit Message: Fixed invalid memory access bugs when decoding JPEG Exif data Fixes issues #22, #23, #24, #25 CWE ID: CWE-125
static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos, unsigned int *pv) { unsigned int field_type; unsigned int value_count; field_type = get_exif_ui16(e, tag_pos+2); value_count = get_exif_ui32(e, tag_pos+4); if(value_count!=1) return 0; if(field_type==3) { // SHORT (uint16) *pv = get_exif_ui16(e, tag_pos+8); return 1; } else if(field_type==4) { // LONG (uint32) *pv = get_exif_ui32(e, tag_pos+8); return 1; } return 0; }
168,114
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost( RenderWidgetHostImpl* receiving_widget) { if (!SiteIsolationPolicy::AreCrossProcessFramesPossible()) return receiving_widget; if (receiving_widget != GetMainFrame()->GetRenderWidgetHost()) return receiving_widget; WebContentsImpl* focused_contents = GetFocusedWebContents(); if (focused_contents->ShowingInterstitialPage()) { return static_cast<RenderFrameHostImpl*>( focused_contents->GetRenderManager() ->interstitial_page() ->GetMainFrame()) ->GetRenderWidgetHost(); } FrameTreeNode* focused_frame = nullptr; if (focused_contents->browser_plugin_guest_ && !GuestMode::IsCrossProcessFrameGuest(focused_contents)) { focused_frame = frame_tree_.GetFocusedFrame(); } else { focused_frame = GetFocusedWebContents()->frame_tree_.GetFocusedFrame(); } if (!focused_frame) return receiving_widget; RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView(); if (!view) return nullptr; return RenderWidgetHostImpl::From(view->GetRenderWidgetHost()); } 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
RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost( RenderWidgetHostImpl* receiving_widget) { if (!SiteIsolationPolicy::AreCrossProcessFramesPossible()) return receiving_widget; if (receiving_widget != GetMainFrame()->GetRenderWidgetHost()) return receiving_widget; WebContentsImpl* focused_contents = GetFocusedWebContents(); if (focused_contents->ShowingInterstitialPage()) { return static_cast<RenderFrameHostImpl*>( focused_contents->interstitial_page_->GetMainFrame()) ->GetRenderWidgetHost(); } FrameTreeNode* focused_frame = nullptr; if (focused_contents->browser_plugin_guest_ && !GuestMode::IsCrossProcessFrameGuest(focused_contents)) { focused_frame = frame_tree_.GetFocusedFrame(); } else { focused_frame = GetFocusedWebContents()->frame_tree_.GetFocusedFrame(); } if (!focused_frame) return receiving_widget; RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView(); if (!view) return nullptr; return RenderWidgetHostImpl::From(view->GetRenderWidgetHost()); }
172,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || nsown_capable(CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) { return 0; } return -EPERM; } Commit Message: scm: Require CAP_SYS_ADMIN over the current pidns to spoof pids. Don't allow spoofing pids over unix domain sockets in the corner cases where a user has created a user namespace but has not yet created a pid namespace. Cc: stable@vger.kernel.org Reported-by: Andy Lutomirski <luto@amacapital.net> Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> CWE ID: CWE-264
static __inline__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || ns_capable(current->nsproxy->pid_ns->user_ns, CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || nsown_capable(CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || nsown_capable(CAP_SETGID))) { return 0; } return -EPERM; }
166,093
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, addFromString) { char *localname, *cont_str; size_t localname_len, cont_len; PHAR_ARCHIVE_OBJECT(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps", &localname, &localname_len, &cont_str, &cont_len) == FAILURE) { return; } phar_add_file(&(phar_obj->archive), localname, localname_len, cont_str, cont_len, NULL); }
165,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); } Commit Message: [IndexedDB] Fixed transaction use-after-free vuln Bug: 725032 Change-Id: I689ded6c74d5563403587b149c3f3e02e807e4aa Reviewed-on: https://chromium-review.googlesource.com/518483 Reviewed-by: Joshua Bell <jsbell@chromium.org> Commit-Queue: Daniel Murphy <dmurph@chromium.org> Cr-Commit-Position: refs/heads/master@{#475952} CWE ID: CWE-416
void DatabaseImpl::IDBThreadHelper::CreateTransaction( int64_t transaction_id, const std::vector<int64_t>& object_store_ids, blink::WebIDBTransactionMode mode) { DCHECK(idb_thread_checker_.CalledOnValidThread()); if (!connection_->IsConnected()) return; // Can't call BadMessage as we're no longer on the IO thread. So ignore. if (connection_->GetTransaction(transaction_id)) return; connection_->database()->CreateTransaction(transaction_id, connection_.get(), object_store_ids, mode); }
172,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_METHOD(snmp, setSecurity) { php_snmp_object *snmp_object; zval *object = getThis(); char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = ""; int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0; int argc = ZEND_NUM_ARGS(); snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) { RETURN_FALSE; } if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) { /* Warning message sent already, just bail out */ RETURN_FALSE; } RETURN_TRUE; } Commit Message: CWE ID: CWE-416
PHP_METHOD(snmp, setSecurity) { php_snmp_object *snmp_object; zval *object = getThis(); char *a1 = "", *a2 = "", *a3 = "", *a4 = "", *a5 = "", *a6 = "", *a7 = ""; int a1_len = 0, a2_len = 0, a3_len = 0, a4_len = 0, a5_len = 0, a6_len = 0, a7_len = 0; int argc = ZEND_NUM_ARGS(); snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); if (zend_parse_parameters(argc TSRMLS_CC, "s|ssssss", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len) == FAILURE) { RETURN_FALSE; } if (netsnmp_session_set_security(snmp_object->session, a1, a2, a3, a4, a5, a6, a7 TSRMLS_CC)) { /* Warning message sent already, just bail out */ RETURN_FALSE; } RETURN_TRUE; }
164,973
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: StorageHandler::GetCacheStorageObserver() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!cache_storage_observer_) { cache_storage_observer_ = std::make_unique<CacheStorageObserver>( weak_ptr_factory_.GetWeakPtr(), static_cast<CacheStorageContextImpl*>( process_->GetStoragePartition()->GetCacheStorageContext())); } return cache_storage_observer_.get(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
StorageHandler::GetCacheStorageObserver() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!cache_storage_observer_) { cache_storage_observer_ = std::make_unique<CacheStorageObserver>( weak_ptr_factory_.GetWeakPtr(), static_cast<CacheStorageContextImpl*>( storage_partition_->GetCacheStorageContext())); } return cache_storage_observer_.get(); }
172,771
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ static char base_address; xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)&base_address); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ static char base_address; xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)&base_address); if (val >= 0) { snprintf((char *)str, sizeof(str), "idp%ld", val); } else { snprintf((char *)str, sizeof(str), "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); }
173,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 OffscreenCanvas::Dispose() { if (context_) { context_->DetachHost(); context_ = nullptr; } if (HasPlaceholderCanvas() && GetTopExecutionContext() && GetTopExecutionContext()->IsWorkerGlobalScope()) { WorkerAnimationFrameProvider* animation_frame_provider = To<WorkerGlobalScope>(GetTopExecutionContext()) ->GetAnimationFrameProvider(); if (animation_frame_provider) animation_frame_provider->DeregisterOffscreenCanvas(this); } } Commit Message: Clean up CanvasResourceDispatcher on finalizer We may have pending mojo messages after GC, so we want to drop the dispatcher as soon as possible. Bug: 929757,913964 Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0 Reviewed-on: https://chromium-review.googlesource.com/c/1489175 Reviewed-by: Ken Rockot <rockot@google.com> Commit-Queue: Ken Rockot <rockot@google.com> Commit-Queue: Fernando Serboncini <fserb@chromium.org> Auto-Submit: Fernando Serboncini <fserb@chromium.org> Cr-Commit-Position: refs/heads/master@{#635833} CWE ID: CWE-416
void OffscreenCanvas::Dispose() { // We need to drop frame dispatcher, to prevent mojo calls from completing. frame_dispatcher_ = nullptr; if (context_) { context_->DetachHost(); context_ = nullptr; } if (HasPlaceholderCanvas() && GetTopExecutionContext() && GetTopExecutionContext()->IsWorkerGlobalScope()) { WorkerAnimationFrameProvider* animation_frame_provider = To<WorkerGlobalScope>(GetTopExecutionContext()) ->GetAnimationFrameProvider(); if (animation_frame_provider) animation_frame_provider->DeregisterOffscreenCanvas(this); } }
173,029
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool PrintWebViewHelper::UpdatePrintSettings( WebKit::WebFrame* frame, const WebKit::WebNode& node, const DictionaryValue& passed_job_settings) { DCHECK(is_preview_enabled_); const DictionaryValue* job_settings = &passed_job_settings; DictionaryValue modified_job_settings; if (job_settings->empty()) { if (!print_for_preview_) print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } bool source_is_html = true; if (print_for_preview_) { if (!job_settings->GetBoolean(printing::kSettingPreviewModifiable, &source_is_html)) { NOTREACHED(); } } else { source_is_html = !PrintingNodeOrPdfFrame(frame, node); } if (print_for_preview_ || !source_is_html) { modified_job_settings.MergeDictionary(job_settings); modified_job_settings.SetBoolean(printing::kSettingHeaderFooterEnabled, false); modified_job_settings.SetInteger(printing::kSettingMarginsType, printing::NO_MARGINS); job_settings = &modified_job_settings; } int cookie = print_pages_params_.get() ? print_pages_params_->params.document_cookie : 0; PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, *job_settings, &settings)); print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); if (!PrintMsg_Print_Params_IsValid(settings.params)) { if (!print_for_preview_) { print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS); } else { WebKit::WebFrame* print_frame = NULL; GetPrintFrame(&print_frame); if (print_frame) { render_view()->RunModalAlertDialog( print_frame, l10n_util::GetStringUTF16( IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS)); } } return false; } if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) { print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS); return false; } if (!print_for_preview_) { if (!job_settings->GetString(printing::kPreviewUIAddr, &(settings.params.preview_ui_addr)) || !job_settings->GetInteger(printing::kPreviewRequestID, &(settings.params.preview_request_id)) || !job_settings->GetBoolean(printing::kIsFirstRequest, &(settings.params.is_first_request))) { NOTREACHED(); print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings); UpdateFrameMarginsCssInfo(*job_settings); settings.params.print_scaling_option = GetPrintScalingOption( source_is_html, *job_settings, settings.params); if (settings.params.display_header_footer) { header_footer_info_.reset(new DictionaryValue()); header_footer_info_->SetString(printing::kSettingHeaderFooterDate, settings.params.date); header_footer_info_->SetString(printing::kSettingHeaderFooterURL, settings.params.url); header_footer_info_->SetString(printing::kSettingHeaderFooterTitle, settings.params.title); } } print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(), settings.params.document_cookie)); return true; } 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
bool PrintWebViewHelper::UpdatePrintSettings( WebKit::WebFrame* frame, const WebKit::WebNode& node, const DictionaryValue& passed_job_settings) { DCHECK(is_preview_enabled_); const DictionaryValue* job_settings = &passed_job_settings; DictionaryValue modified_job_settings; if (job_settings->empty()) { if (!print_for_preview_) print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } bool source_is_html = true; if (print_for_preview_) { if (!job_settings->GetBoolean(printing::kSettingPreviewModifiable, &source_is_html)) { NOTREACHED(); } } else { source_is_html = !PrintingNodeOrPdfFrame(frame, node); } if (print_for_preview_ || !source_is_html) { modified_job_settings.MergeDictionary(job_settings); modified_job_settings.SetBoolean(printing::kSettingHeaderFooterEnabled, false); modified_job_settings.SetInteger(printing::kSettingMarginsType, printing::NO_MARGINS); job_settings = &modified_job_settings; } int cookie = print_pages_params_.get() ? print_pages_params_->params.document_cookie : 0; PrintMsg_PrintPages_Params settings; Send(new PrintHostMsg_UpdatePrintSettings(routing_id(), cookie, *job_settings, &settings)); print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); if (!PrintMsg_Print_Params_IsValid(settings.params)) { if (!print_for_preview_) { print_preview_context_.set_error(PREVIEW_ERROR_INVALID_PRINTER_SETTINGS); } else { WebKit::WebFrame* print_frame = NULL; GetPrintFrame(&print_frame); if (print_frame) { render_view()->RunModalAlertDialog( print_frame, l10n_util::GetStringUTF16( IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS)); } } return false; } if (settings.params.dpi < kMinDpi || !settings.params.document_cookie) { print_preview_context_.set_error(PREVIEW_ERROR_UPDATING_PRINT_SETTINGS); return false; } if (!print_for_preview_) { if (!job_settings->GetInteger(printing::kPreviewUIID, &(settings.params.preview_ui_id)) || !job_settings->GetInteger(printing::kPreviewRequestID, &(settings.params.preview_request_id)) || !job_settings->GetBoolean(printing::kIsFirstRequest, &(settings.params.is_first_request))) { NOTREACHED(); print_preview_context_.set_error(PREVIEW_ERROR_BAD_SETTING); return false; } settings.params.print_to_pdf = IsPrintToPdfRequested(*job_settings); UpdateFrameMarginsCssInfo(*job_settings); settings.params.print_scaling_option = GetPrintScalingOption( source_is_html, *job_settings, settings.params); if (settings.params.display_header_footer) { header_footer_info_.reset(new DictionaryValue()); header_footer_info_->SetString(printing::kSettingHeaderFooterDate, settings.params.date); header_footer_info_->SetString(printing::kSettingHeaderFooterURL, settings.params.url); header_footer_info_->SetString(printing::kSettingHeaderFooterTitle, settings.params.title); } } print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings)); Send(new PrintHostMsg_DidGetDocumentCookie(routing_id(), settings.params.document_cookie)); return true; }
170,857
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); } Commit Message: CWE ID: CWE-787
char **XGetFontPath( register Display *dpy, int *npaths) /* RETURN */ { xGetFontPathReply rep; unsigned long nbytes = 0; char **flist = NULL; char *ch = NULL; char *chend; int count = 0; register unsigned i; register int length; _X_UNUSED register xReq *req; LockDisplay(dpy); GetEmptyReq (GetFontPath, req); (void) _XReply (dpy, (xReply *) &rep, 0, xFalse); if (rep.nPaths) { flist = Xmalloc(rep.nPaths * sizeof (char *)); if (rep.length < (INT_MAX >> 2)) { nbytes = (unsigned long) rep.length << 2; ch = Xmalloc (nbytes + 1); /* +1 to leave room for last null-terminator */ } if ((! flist) || (! ch)) { Xfree(flist); Xfree(ch); _XEatDataWords(dpy, rep.length); UnlockDisplay(dpy); SyncHandle(); return (char **) NULL; } _XReadPad (dpy, ch, nbytes); /* * unpack into null terminated strings. */ chend = ch + nbytes; length = *(unsigned char *)ch; for (i = 0; i < rep.nPaths; i++) { if (ch + length < chend) { flist[i] = ch+1; /* skip over length */ ch += length + 1; /* find next length ... */ length = *(unsigned char *)ch; *ch = '\0'; /* and replace with null-termination */ count++; } else flist[i] = NULL; } } *npaths = count; UnlockDisplay(dpy); SyncHandle(); return (flist); }
164,745
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ~0; args->count = ntohl(*p++); args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfs3svc_decode_readdirargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ~0; args->count = ntohl(*p++); if (!xdr_argsize_check(rqstp, p)) return 0; args->count = min_t(u32, args->count, PAGE_SIZE); args->buffer = page_address(*(rqstp->rq_next_page++)); return 1; }
168,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) return 0; ext_block = (struct grub_ext4_extent_header *) buf; } } Commit Message: Fix #7723 - crash in ext2 GRUB code because of variable size array in stack CWE ID: CWE-119
grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, struct grub_ext4_extent_header *ext_block, grub_uint32_t fileblock) { struct grub_ext4_extent_idx *index; while (1) { int i; grub_disk_addr_t block; index = (struct grub_ext4_extent_idx *) (ext_block + 1); if (grub_le_to_cpu16(ext_block->magic) != EXT4_EXT_MAGIC) return 0; if (ext_block->depth == 0) return ext_block; for (i = 0; i < grub_le_to_cpu16 (ext_block->entries); i++) { if (fileblock < grub_le_to_cpu32(index[i].block)) break; } if (--i < 0) return 0; block = grub_le_to_cpu16 (index[i].leaf_hi); block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); if (grub_disk_read (data->disk, block << LOG2_EXT2_BLOCK_SIZE (data), 0, EXT2_BLOCK_SIZE(data), buf)) { return 0; } ext_block = (struct grub_ext4_extent_header *) buf; } }
168,088
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int32 CommandBufferProxyImpl::CreateTransferBuffer( size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; scoped_ptr<base::SharedMemory> shm( channel_->factory()->AllocateSharedMemory(size)); if (!shm.get()) return -1; base::SharedMemoryHandle handle = shm->handle(); #if defined(OS_POSIX) DCHECK(!handle.auto_close); #endif int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_, handle, size, id_request, &id))) { return -1; } return id; } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
int32 CommandBufferProxyImpl::CreateTransferBuffer( size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; scoped_ptr<base::SharedMemory> shm( channel_->factory()->AllocateSharedMemory(size)); if (!shm.get()) return -1; base::SharedMemoryHandle handle = shm->handle(); #if defined(OS_WIN) // Windows needs to explicitly duplicate the handle out to another process. if (!sandbox::BrokerDuplicateHandle(handle, channel_->gpu_pid(), &handle, FILE_MAP_WRITE, 0)) { return -1; } #elif defined(OS_POSIX) DCHECK(!handle.auto_close); #endif int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer(route_id_, handle, size, id_request, &id))) { return -1; } return id; }
170,926
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); sqr_add_c2(a,4,0,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,5,0,c3,c1,c2); sqr_add_c2(a,4,1,c3,c1,c2); sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); sqr_add_c2(a,4,2,c1,c2,c3); sqr_add_c2(a,5,1,c1,c2,c3); sqr_add_c2(a,6,0,c1,c2,c3); r[6]=c1; c1=0; sqr_add_c2(a,7,0,c2,c3,c1); sqr_add_c2(a,6,1,c2,c3,c1); sqr_add_c2(a,5,2,c2,c3,c1); sqr_add_c2(a,4,3,c2,c3,c1); r[7]=c2; c2=0; sqr_add_c(a,4,c3,c1,c2); sqr_add_c2(a,5,3,c3,c1,c2); sqr_add_c2(a,6,2,c3,c1,c2); sqr_add_c2(a,7,1,c3,c1,c2); r[8]=c3; c3=0; sqr_add_c2(a,7,2,c1,c2,c3); sqr_add_c2(a,6,3,c1,c2,c3); sqr_add_c2(a,5,4,c1,c2,c3); r[9]=c1; c1=0; sqr_add_c(a,5,c2,c3,c1); sqr_add_c2(a,6,4,c2,c3,c1); sqr_add_c2(a,7,3,c2,c3,c1); r[10]=c2; c2=0; sqr_add_c2(a,7,4,c3,c1,c2); sqr_add_c2(a,6,5,c3,c1,c2); r[11]=c3; c3=0; sqr_add_c(a,6,c1,c2,c3); sqr_add_c2(a,7,5,c1,c2,c3); r[12]=c1; c1=0; sqr_add_c2(a,7,6,c2,c3,c1); r[13]=c2; c2=0; sqr_add_c(a,7,c3,c1,c2); r[14]=c3; r[15]=c1; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.org> CWE ID: CWE-310
void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); sqr_add_c2(a,4,0,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,5,0,c3,c1,c2); sqr_add_c2(a,4,1,c3,c1,c2); sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); sqr_add_c2(a,4,2,c1,c2,c3); sqr_add_c2(a,5,1,c1,c2,c3); sqr_add_c2(a,6,0,c1,c2,c3); r[6]=c1; c1=0; sqr_add_c2(a,7,0,c2,c3,c1); sqr_add_c2(a,6,1,c2,c3,c1); sqr_add_c2(a,5,2,c2,c3,c1); sqr_add_c2(a,4,3,c2,c3,c1); r[7]=c2; c2=0; sqr_add_c(a,4,c3,c1,c2); sqr_add_c2(a,5,3,c3,c1,c2); sqr_add_c2(a,6,2,c3,c1,c2); sqr_add_c2(a,7,1,c3,c1,c2); r[8]=c3; c3=0; sqr_add_c2(a,7,2,c1,c2,c3); sqr_add_c2(a,6,3,c1,c2,c3); sqr_add_c2(a,5,4,c1,c2,c3); r[9]=c1; c1=0; sqr_add_c(a,5,c2,c3,c1); sqr_add_c2(a,6,4,c2,c3,c1); sqr_add_c2(a,7,3,c2,c3,c1); r[10]=c2; c2=0; sqr_add_c2(a,7,4,c3,c1,c2); sqr_add_c2(a,6,5,c3,c1,c2); r[11]=c3; c3=0; sqr_add_c(a,6,c1,c2,c3); sqr_add_c2(a,7,5,c1,c2,c3); r[12]=c1; c1=0; sqr_add_c2(a,7,6,c2,c3,c1); r[13]=c2; c2=0; sqr_add_c(a,7,c3,c1,c2); r[14]=c3; r[15]=c1; }
166,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: TabContents* TabStripModel::DetachTabContentsAt(int index) { if (contents_data_.empty()) return NULL; DCHECK(ContainsIndex(index)); TabContents* removed_contents = GetTabContentsAtImpl(index); bool was_selected = IsTabSelected(index); int next_selected_index = order_controller_->DetermineNewSelectedIndex(index); delete contents_data_[index]; contents_data_.erase(contents_data_.begin() + index); ForgetOpenersAndGroupsReferencing(removed_contents->web_contents()); if (empty()) closing_all_ = true; FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabDetachedAt(removed_contents, index)); if (empty()) { selection_model_.Clear(); FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty()); } else { int old_active = active_index(); selection_model_.DecrementFrom(index); TabStripSelectionModel old_model; old_model.Copy(selection_model_); if (index == old_active) { NotifyIfTabDeactivated(removed_contents); if (!selection_model_.empty()) { selection_model_.set_active(selection_model_.selected_indices()[0]); selection_model_.set_anchor(selection_model_.active()); } else { selection_model_.SetSelectedIndex(next_selected_index); } NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT); } if (was_selected) { FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabSelectionChanged(this, old_model)); } } return removed_contents; } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
TabContents* TabStripModel::DetachTabContentsAt(int index) { if (contents_data_.empty()) return NULL; DCHECK(ContainsIndex(index)); TabContents* removed_contents = GetTabContentsAtImpl(index); bool was_selected = IsTabSelected(index); int next_selected_index = order_controller_->DetermineNewSelectedIndex(index); delete contents_data_[index]; contents_data_.erase(contents_data_.begin() + index); ForgetOpenersAndGroupsReferencing(removed_contents->web_contents()); if (empty()) closing_all_ = true; FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabDetachedAt(removed_contents->web_contents(), index)); if (empty()) { selection_model_.Clear(); FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabStripEmpty()); } else { int old_active = active_index(); selection_model_.DecrementFrom(index); TabStripSelectionModel old_model; old_model.Copy(selection_model_); if (index == old_active) { NotifyIfTabDeactivated(removed_contents); if (!selection_model_.empty()) { selection_model_.set_active(selection_model_.selected_indices()[0]); selection_model_.set_anchor(selection_model_.active()); } else { selection_model_.SetSelectedIndex(next_selected_index); } NotifyIfActiveTabChanged(removed_contents, NOTIFY_DEFAULT); } if (was_selected) { FOR_EACH_OBSERVER(TabStripModelObserver, observers_, TabSelectionChanged(this, old_model)); } } return removed_contents; }
171,517
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 zval *xml_call_handler(xml_parser *parser, zval *handler, zend_function *function_ptr, int argc, zval **argv) { int i; TSRMLS_FETCH(); if (parser && handler && !EG(exception)) { zval ***args; zval *retval; int result; zend_fcall_info fci; args = safe_emalloc(sizeof(zval **), argc, 0); for (i = 0; i < argc; i++) { args[i] = &argv[i]; } fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = handler; fci.symbol_table = NULL; fci.object_ptr = parser->object; fci.retval_ptr_ptr = &retval; fci.param_count = argc; fci.params = args; fci.no_separation = 0; /*fci.function_handler_cache = &function_ptr;*/ result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE) { zval **method; zval **obj; if (Z_TYPE_P(handler) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(handler)); } else if (zend_hash_index_find(Z_ARRVAL_P(handler), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(handler), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s::%s()", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler"); } for (i = 0; i < argc; i++) { zval_ptr_dtor(args[i]); } efree(args); if (result == FAILURE) { return NULL; } else { return EG(exception) ? NULL : retval; } } else { for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return NULL; } } Commit Message: CWE ID: CWE-119
static zval *xml_call_handler(xml_parser *parser, zval *handler, zend_function *function_ptr, int argc, zval **argv) { int i; TSRMLS_FETCH(); if (parser && handler && !EG(exception)) { zval ***args; zval *retval; int result; zend_fcall_info fci; args = safe_emalloc(sizeof(zval **), argc, 0); for (i = 0; i < argc; i++) { args[i] = &argv[i]; } fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.function_name = handler; fci.symbol_table = NULL; fci.object_ptr = parser->object; fci.retval_ptr_ptr = &retval; fci.param_count = argc; fci.params = args; fci.no_separation = 0; /*fci.function_handler_cache = &function_ptr;*/ result = zend_call_function(&fci, NULL TSRMLS_CC); if (result == FAILURE) { zval **method; zval **obj; if (Z_TYPE_P(handler) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s()", Z_STRVAL_P(handler)); } else if (zend_hash_index_find(Z_ARRVAL_P(handler), 0, (void **) &obj) == SUCCESS && zend_hash_index_find(Z_ARRVAL_P(handler), 1, (void **) &method) == SUCCESS && Z_TYPE_PP(obj) == IS_OBJECT && Z_TYPE_PP(method) == IS_STRING) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler %s::%s()", Z_OBJCE_PP(obj)->name, Z_STRVAL_PP(method)); } else php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to call handler"); } for (i = 0; i < argc; i++) { zval_ptr_dtor(args[i]); } efree(args); if (result == FAILURE) { return NULL; } else { return EG(exception) ? NULL : retval; } } else { for (i = 0; i < argc; i++) { zval_ptr_dtor(&argv[i]); } return NULL; } }
165,046
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame), logging_state_active_(false), was_username_autofilled_(false), was_password_autofilled_(false), weak_ptr_factory_(this) { Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id())); } Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent Unlike in AutofillAgent, the factory is no longer used in PAA. R=dvadym@chromium.org BUG=609010,609007,608100,608101,433486 Review-Url: https://codereview.chromium.org/1945723003 Cr-Commit-Position: refs/heads/master@{#391475} CWE ID:
PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame), logging_state_active_(false), was_username_autofilled_(false), was_password_autofilled_(false) { Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id())); }
173,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ModuleExport size_t RegisterPSImage(void) { MagickInfo *entry; entry=SetMagickInfo("EPI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSF"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("PostScript"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/715 CWE ID: CWE-834
ModuleExport size_t RegisterPSImage(void) { MagickInfo *entry; entry=SetMagickInfo("EPI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSF"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("PostScript"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
167,763
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: log_result (PolkitBackendInteractiveAuthority *authority, const gchar *action_id, PolkitSubject *subject, PolkitSubject *caller, PolkitAuthorizationResult *result) { PolkitBackendInteractiveAuthorityPrivate *priv; PolkitIdentity *user_of_subject; const gchar *log_result_str; gchar *subject_str; gchar *user_of_subject_str; gchar *caller_str; gchar *subject_cmdline; gchar *caller_cmdline; priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (authority); log_result_str = "DENYING"; if (polkit_authorization_result_get_is_authorized (result)) log_result_str = "ALLOWING"; user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL); subject_str = polkit_subject_to_string (subject); if (user_of_subject != NULL) user_of_subject_str = polkit_identity_to_string (user_of_subject); else user_of_subject_str = g_strdup ("<unknown>"); caller_str = polkit_subject_to_string (caller); subject_cmdline = _polkit_subject_get_cmdline (subject); if (subject_cmdline == NULL) subject_cmdline = g_strdup ("<unknown>"); caller_cmdline = _polkit_subject_get_cmdline (caller); if (caller_cmdline == NULL) caller_cmdline = g_strdup ("<unknown>"); polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority), "%s action %s for %s [%s] owned by %s (check requested by %s [%s])", log_result_str, action_id, subject_str, subject_cmdline, user_of_subject_str, caller_str, caller_cmdline); if (user_of_subject != NULL) g_object_unref (user_of_subject); g_free (subject_str); g_free (user_of_subject_str); g_free (caller_str); g_free (subject_cmdline); g_free (caller_cmdline); } Commit Message: CWE ID: CWE-200
log_result (PolkitBackendInteractiveAuthority *authority, const gchar *action_id, PolkitSubject *subject, PolkitSubject *caller, PolkitAuthorizationResult *result) { PolkitBackendInteractiveAuthorityPrivate *priv; PolkitIdentity *user_of_subject; const gchar *log_result_str; gchar *subject_str; gchar *user_of_subject_str; gchar *caller_str; gchar *subject_cmdline; gchar *caller_cmdline; priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (authority); log_result_str = "DENYING"; if (polkit_authorization_result_get_is_authorized (result)) log_result_str = "ALLOWING"; user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL, NULL); subject_str = polkit_subject_to_string (subject); if (user_of_subject != NULL) user_of_subject_str = polkit_identity_to_string (user_of_subject); else user_of_subject_str = g_strdup ("<unknown>"); caller_str = polkit_subject_to_string (caller); subject_cmdline = _polkit_subject_get_cmdline (subject); if (subject_cmdline == NULL) subject_cmdline = g_strdup ("<unknown>"); caller_cmdline = _polkit_subject_get_cmdline (caller); if (caller_cmdline == NULL) caller_cmdline = g_strdup ("<unknown>"); polkit_backend_authority_log (POLKIT_BACKEND_AUTHORITY (authority), "%s action %s for %s [%s] owned by %s (check requested by %s [%s])", log_result_str, action_id, subject_str, subject_cmdline, user_of_subject_str, caller_str, caller_cmdline); if (user_of_subject != NULL) g_object_unref (user_of_subject); g_free (subject_str); g_free (user_of_subject_str); g_free (caller_str); g_free (subject_cmdline); g_free (caller_cmdline); }
165,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_xattr_destroy_cache(struct mb_cache *cache) { if (cache) mb_cache_destroy(cache); } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
void ext4_xattr_destroy_cache(struct mb_cache *cache) void ext4_xattr_destroy_cache(struct mb2_cache *cache) { if (cache) mb2_cache_destroy(cache); }
169,994
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { } Commit Message: Fix memory error in previous CL. BUG=100315 BUG=99016 TEST=Memory bots go green Review URL: http://codereview.chromium.org/8302001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@105577 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
NavigateParams::NavigateParams( Browser* a_browser, const GURL& a_url, content::PageTransition a_transition) : url(a_url), target_contents(NULL), source_contents(NULL), disposition(CURRENT_TAB), transition(a_transition), is_renderer_initiated(false), tabstrip_index(-1), tabstrip_add_types(TabStripModel::ADD_ACTIVE), window_action(NO_ACTION), user_gesture(true), path_behavior(RESPECT), ref_behavior(IGNORE_REF), browser(a_browser), profile(NULL) { }
170,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr); close(sk); return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; TEMP_FAILURE_RETRY(ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr)); close(sk); return 0; }
173,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void CancelHandwritingStrokes(int stroke_count) { if (!initialized_successfully_) return; chromeos::CancelHandwriting(input_method_status_connection_, stroke_count); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual void CancelHandwritingStrokes(int stroke_count) { if (!initialized_successfully_) return; ibus_controller_->CancelHandwriting(stroke_count); }
170,477
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem( uint32_t id, const download::DownloadCreateInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!base::ContainsKey(downloads_, id)); download::DownloadItemImpl* download = item_factory_->CreateActiveItem(this, id, info); downloads_[id] = base::WrapUnique(download); downloads_by_guid_[download->GetGuid()] = download; DownloadItemUtils::AttachInfo( download, GetBrowserContext(), WebContentsImpl::FromRenderFrameHostID(info.render_process_id, info.render_frame_id)); return download; } Commit Message: Early return if a download Id is already used when creating a download This is protect against download Id overflow and use-after-free issue. BUG=958533 Change-Id: I2c183493cb09106686df9822b3987bfb95bcf720 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591485 Reviewed-by: Xing Liu <xingliu@chromium.org> Commit-Queue: Min Qin <qinmin@chromium.org> Cr-Commit-Position: refs/heads/master@{#656910} CWE ID: CWE-416
download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem( uint32_t id, const download::DownloadCreateInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (base::ContainsKey(downloads_, id)) return nullptr; download::DownloadItemImpl* download = item_factory_->CreateActiveItem(this, id, info); downloads_[id] = base::WrapUnique(download); downloads_by_guid_[download->GetGuid()] = download; DownloadItemUtils::AttachInfo( download, GetBrowserContext(), WebContentsImpl::FromRenderFrameHostID(info.render_process_id, info.render_frame_id)); return download; }
172,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXNodeObject::hasContentEditableAttributeSet() const { const AtomicString& contentEditableValue = getAttribute(contenteditableAttr); if (contentEditableValue.isNull()) return false; return contentEditableValue.isEmpty() || equalIgnoringCase(contentEditableValue, "true"); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
bool AXNodeObject::hasContentEditableAttributeSet() const { const AtomicString& contentEditableValue = getAttribute(contenteditableAttr); if (contentEditableValue.isNull()) return false; return contentEditableValue.isEmpty() || equalIgnoringASCIICase(contentEditableValue, "true"); }
171,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tag_name, Document& document) : HTMLElement(tag_name, document), content_frame_(nullptr), embedded_content_view_(nullptr), sandbox_flags_(kSandboxNone) {} Commit Message: Resource Timing: Do not report subsequent navigations within subframes We only want to record resource timing for the load that was initiated by parent document. We filter out subsequent navigations for <iframe>, but we should do it for other types of subframes too. Bug: 780312 Change-Id: I3a7b9e1a365c99e24bb8dac190e88c7099fc3da5 Reviewed-on: https://chromium-review.googlesource.com/750487 Reviewed-by: Nate Chapin <japhet@chromium.org> Commit-Queue: Kunihiko Sakamoto <ksakamoto@chromium.org> Cr-Commit-Position: refs/heads/master@{#513665} CWE ID: CWE-601
HTMLFrameOwnerElement::HTMLFrameOwnerElement(const QualifiedName& tag_name, Document& document) : HTMLElement(tag_name, document), content_frame_(nullptr), embedded_content_view_(nullptr),
172,928
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (istreq(str, "all")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, "none")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; } Commit Message: xkbcomp: Don't explode on invalid virtual modifiers testcase: 'virtualModifiers=LevelThreC' Signed-off-by: Daniel Stone <daniels@collabora.com> CWE ID: CWE-476
LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field, enum expr_value_type type, xkb_mod_mask_t *val_rtrn) { const char *str; xkb_mod_index_t ndx; const LookupModMaskPriv *arg = priv; const struct xkb_mod_set *mods = arg->mods; enum mod_type mod_type = arg->mod_type; if (type != EXPR_TYPE_INT) return false; str = xkb_atom_text(ctx, field); if (!str) return false; if (istreq(str, "all")) { *val_rtrn = MOD_REAL_MASK_ALL; return true; } if (istreq(str, "none")) { *val_rtrn = 0; return true; } ndx = XkbModNameToIndex(mods, field, mod_type); if (ndx == XKB_MOD_INVALID) return false; *val_rtrn = (1u << ndx); return true; }
169,089