instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MemBackendImpl::EvictIfNeeded() { if (current_size_ <= max_size_) return; int target_size = std::max(0, max_size_ - kDefaultEvictionSize); base::LinkNode<MemEntryImpl>* entry = lru_list_.head(); while (current_size_ > target_size && entry != lru_list_.end()) { MemEntryImpl* to_doom = entry->value(); do { entry = entry->next(); } while (entry != lru_list_.end() && entry->value()->parent() == to_doom); if (!to_doom->InUse()) to_doom->Doom(); } } Commit Message: [MemCache] Fix bug while iterating LRU list in range doom This is exact same thing as https://chromium-review.googlesource.com/c/chromium/src/+/987919 but on explicit mass-erase rather than eviction. Thanks to nedwilliamson@ (on gmail) for the report and testcase. Bug: 831963 Change-Id: I96a46700c1f058f7feebe038bcf983dc40eb7102 Reviewed-on: https://chromium-review.googlesource.com/1014023 Commit-Queue: Maks Orlovich <[email protected]> Reviewed-by: Josh Karlin <[email protected]> Cr-Commit-Position: refs/heads/master@{#551205} CWE ID: CWE-416
void MemBackendImpl::EvictIfNeeded() { if (current_size_ <= max_size_) return; int target_size = std::max(0, max_size_ - kDefaultEvictionSize); base::LinkNode<MemEntryImpl>* entry = lru_list_.head(); while (current_size_ > target_size && entry != lru_list_.end()) { MemEntryImpl* to_doom = entry->value(); entry = NextSkippingChildren(lru_list_, entry); if (!to_doom->InUse()) to_doom->Doom(); } }
173,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current() Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current()
167,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher( const GURL& url) { std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); fetcher->SetRequestContext(helper_->request_context()); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); fetcher->SetAutomaticallyRetryOnNetworkChanges(1); return fetcher; } Commit Message: Add data usage tracking for chrome services Add data usage tracking for captive portal, web resource and signin services BUG=655749 Review-Url: https://codereview.chromium.org/2643013004 Cr-Commit-Position: refs/heads/master@{#445810} CWE ID: CWE-190
GaiaCookieManagerService::ExternalCcResultFetcher::CreateFetcher( const GURL& url) { std::unique_ptr<net::URLFetcher> fetcher = net::URLFetcher::Create(0, url, net::URLFetcher::GET, this); fetcher->SetRequestContext(helper_->request_context()); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES); data_use_measurement::DataUseUserData::AttachToFetcher( fetcher.get(), data_use_measurement::DataUseUserData::SIGNIN); fetcher->SetAutomaticallyRetryOnNetworkChanges(1); return fetcher; }
172,019
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; long rem; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
jiffies_to_compat_timeval(unsigned long jiffies, struct compat_timeval *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; u32 rem; value->tv_sec = div_u64_rem(nsec, NSEC_PER_SEC, &rem); value->tv_usec = rem / NSEC_PER_USEC; }
165,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::detach(const AttachContext& context) { TRACE_EVENT0("blink", "Document::detach"); ASSERT(!m_frame || m_frame->tree().childCount() == 0); if (!isActive()) return; FrameNavigationDisabler navigationDisabler(*m_frame); HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates; ScriptForbiddenScope forbidScript; view()->dispose(); m_markers->prepareForDestruction(); if (LocalDOMWindow* window = this->domWindow()) window->willDetachDocumentFromFrame(); m_lifecycle.advanceTo(DocumentLifecycle::Stopping); if (page()) page()->documentDetached(this); InspectorInstrumentation::documentDetached(this); if (m_frame->loader().client()->sharedWorkerRepositoryClient()) m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this); stopActiveDOMObjects(); if (m_scriptedAnimationController) m_scriptedAnimationController->clearDocumentPointer(); m_scriptedAnimationController.clear(); m_scriptedIdleTaskController.clear(); if (svgExtensions()) accessSVGExtensions().pauseAnimations(); if (m_domWindow) m_domWindow->clearEventQueue(); if (m_layoutView) m_layoutView->setIsInWindow(false); if (registrationContext()) registrationContext()->documentWasDetached(); m_hoverNode = nullptr; m_activeHoverElement = nullptr; m_autofocusElement = nullptr; if (m_focusedElement.get()) { RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement; m_focusedElement = nullptr; if (frameHost()) frameHost()->chromeClient().focusedNodeChanged(oldFocusedElement.get(), nullptr); } if (this == &axObjectCacheOwner()) clearAXObjectCache(); m_layoutView = nullptr; ContainerNode::detach(context); if (this != &axObjectCacheOwner()) { if (AXObjectCache* cache = existingAXObjectCache()) { for (Node& node : NodeTraversal::descendantsOf(*this)) { cache->remove(&node); } } } styleEngine().didDetach(); frameHost()->eventHandlerRegistry().documentDetached(*this); m_frame->inputMethodController().documentDetached(); if (!loader()) m_fetcher->clearContext(); if (m_importsController) HTMLImportsController::removeFrom(*this); m_timers.setTimerTaskRunner( Platform::current()->currentThread()->scheduler()->timerTaskRunner()->adoptClone()); m_frame = nullptr; if (m_mediaQueryMatcher) m_mediaQueryMatcher->documentDetached(); DocumentLifecycleNotifier::notifyDocumentWasDetached(); m_lifecycle.advanceTo(DocumentLifecycle::Stopped); DocumentLifecycleNotifier::notifyContextDestroyed(); ExecutionContext::notifyContextDestroyed(); } Commit Message: Change Document::detach() to RELEASE_ASSERT all subframes are gone. BUG=556724,577105 Review URL: https://codereview.chromium.org/1667573002 Cr-Commit-Position: refs/heads/master@{#373642} CWE ID: CWE-264
void Document::detach(const AttachContext& context) { TRACE_EVENT0("blink", "Document::detach"); RELEASE_ASSERT(!m_frame || m_frame->tree().childCount() == 0); if (!isActive()) return; FrameNavigationDisabler navigationDisabler(*m_frame); HTMLFrameOwnerElement::UpdateSuspendScope suspendWidgetHierarchyUpdates; ScriptForbiddenScope forbidScript; view()->dispose(); m_markers->prepareForDestruction(); if (LocalDOMWindow* window = this->domWindow()) window->willDetachDocumentFromFrame(); m_lifecycle.advanceTo(DocumentLifecycle::Stopping); if (page()) page()->documentDetached(this); InspectorInstrumentation::documentDetached(this); if (m_frame->loader().client()->sharedWorkerRepositoryClient()) m_frame->loader().client()->sharedWorkerRepositoryClient()->documentDetached(this); stopActiveDOMObjects(); if (m_scriptedAnimationController) m_scriptedAnimationController->clearDocumentPointer(); m_scriptedAnimationController.clear(); m_scriptedIdleTaskController.clear(); if (svgExtensions()) accessSVGExtensions().pauseAnimations(); if (m_domWindow) m_domWindow->clearEventQueue(); if (m_layoutView) m_layoutView->setIsInWindow(false); if (registrationContext()) registrationContext()->documentWasDetached(); m_hoverNode = nullptr; m_activeHoverElement = nullptr; m_autofocusElement = nullptr; if (m_focusedElement.get()) { RefPtrWillBeRawPtr<Element> oldFocusedElement = m_focusedElement; m_focusedElement = nullptr; if (frameHost()) frameHost()->chromeClient().focusedNodeChanged(oldFocusedElement.get(), nullptr); } if (this == &axObjectCacheOwner()) clearAXObjectCache(); m_layoutView = nullptr; ContainerNode::detach(context); if (this != &axObjectCacheOwner()) { if (AXObjectCache* cache = existingAXObjectCache()) { for (Node& node : NodeTraversal::descendantsOf(*this)) { cache->remove(&node); } } } styleEngine().didDetach(); frameHost()->eventHandlerRegistry().documentDetached(*this); m_frame->inputMethodController().documentDetached(); if (!loader()) m_fetcher->clearContext(); if (m_importsController) HTMLImportsController::removeFrom(*this); m_timers.setTimerTaskRunner( Platform::current()->currentThread()->scheduler()->timerTaskRunner()->adoptClone()); m_frame = nullptr; if (m_mediaQueryMatcher) m_mediaQueryMatcher->documentDetached(); DocumentLifecycleNotifier::notifyDocumentWasDetached(); m_lifecycle.advanceTo(DocumentLifecycle::Stopped); DocumentLifecycleNotifier::notifyContextDestroyed(); ExecutionContext::notifyContextDestroyed(); }
171,746
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data) { int ret; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0, indx, data, size, 100); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); return ret; } Commit Message: pegasus: Use heap buffers for all register access Allocating USB buffers on the stack is not portable, and no longer works on x86_64 (with VMAP_STACK enabled as per default). Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") References: https://bugs.debian.org/852556 Reported-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]> Tested-by: Lisandro Damián Nicanor Pérez Meyer <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-119
static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, void *data) static int set_registers(pegasus_t *pegasus, __u16 indx, __u16 size, const void *data) { u8 *buf; int ret; buf = kmemdup(data, size, GFP_NOIO); if (!buf) return -ENOMEM; ret = usb_control_msg(pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), PEGASUS_REQ_SET_REGS, PEGASUS_REQT_WRITE, 0, indx, buf, size, 100); if (ret < 0) netif_dbg(pegasus, drv, pegasus->net, "%s returned %d\n", __func__, ret); kfree(buf); return ret; }
168,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol) { struct snd_ctl_elem_id id; unsigned int idx; unsigned int count; int err = -EINVAL; if (! kcontrol) return err; if (snd_BUG_ON(!card || !kcontrol->info)) goto error; id = kcontrol->id; down_write(&card->controls_rwsem); if (snd_ctl_find_id(card, &id)) { up_write(&card->controls_rwsem); dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n", id.iface, id.device, id.subdevice, id.name, id.index); err = -EBUSY; goto error; } if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); err = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; count = kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return err; } Commit Message: ALSA: control: Make sure that id->index does not overflow The ALSA control code expects that the range of assigned indices to a control is continuous and does not overflow. Currently there are no checks to enforce this. If a control with a overflowing index range is created that control becomes effectively inaccessible and unremovable since snd_ctl_find_id() will not be able to find it. This patch adds a check that makes sure that controls with a overflowing index range can not be created. Signed-off-by: Lars-Peter Clausen <[email protected]> Acked-by: Jaroslav Kysela <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-189
int snd_ctl_add(struct snd_card *card, struct snd_kcontrol *kcontrol) { struct snd_ctl_elem_id id; unsigned int idx; unsigned int count; int err = -EINVAL; if (! kcontrol) return err; if (snd_BUG_ON(!card || !kcontrol->info)) goto error; id = kcontrol->id; if (id.index > UINT_MAX - kcontrol->count) goto error; down_write(&card->controls_rwsem); if (snd_ctl_find_id(card, &id)) { up_write(&card->controls_rwsem); dev_err(card->dev, "control %i:%i:%i:%s:%i is already present\n", id.iface, id.device, id.subdevice, id.name, id.index); err = -EBUSY; goto error; } if (snd_ctl_find_hole(card, kcontrol->count) < 0) { up_write(&card->controls_rwsem); err = -ENOMEM; goto error; } list_add_tail(&kcontrol->list, &card->controls); card->controls_count += kcontrol->count; kcontrol->id.numid = card->last_numid + 1; card->last_numid += kcontrol->count; count = kcontrol->count; up_write(&card->controls_rwsem); for (idx = 0; idx < count; idx++, id.index++, id.numid++) snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_ADD, &id); return 0; error: snd_ctl_free_one(kcontrol); return err; }
169,905
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 flv_write_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; FLVContext *flv = s->priv_data; FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; unsigned ts; int size = pkt->size; uint8_t *data = NULL; int flags = -1, flags_size, ret; int64_t cur_offset = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) flags_size = 2; else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) flags_size = 5; else flags_size = 1; if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { av_free(par->extradata); par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) { par->extradata_size = 0; return AVERROR(ENOMEM); } memcpy(par->extradata, side, side_size); par->extradata_size = side_size; flv_write_codec_header(s, par, pkt->dts); } } if (flv->delay == AV_NOPTS_VALUE) flv->delay = -pkt->dts; if (pkt->dts < -flv->delay) { av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with respect to DTS\n"); return AVERROR(EINVAL); } ts = pkt->dts; if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { write_metadata(s, ts); s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; } avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: avio_w8(pb, FLV_TAG_TYPE_VIDEO); flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; break; case AVMEDIA_TYPE_AUDIO: flags = get_audio_flags(s, par); av_assert0(size); avio_w8(pb, FLV_TAG_TYPE_AUDIO); break; case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_DATA: avio_w8(pb, FLV_TAG_TYPE_META); break; default: return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { /* check if extradata looks like mp4 formatted */ if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) return ret; } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } /* check Speex packet duration */ if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); if (sc->last_ts < ts) sc->last_ts = ts; if (size + flags_size >= 1<<24) { av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n", size + flags_size, 1<<24); return AVERROR(EINVAL); } avio_wb24(pb, size + flags_size); put_timestamp(pb, ts); avio_wb24(pb, flv->reserved); if (par->codec_type == AVMEDIA_TYPE_DATA || par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { int data_size; int64_t metadata_size_pos = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_TEXT) { avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "onTextData"); avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); avio_wb32(pb, 2); put_amf_string(pb, "type"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "Text"); put_amf_string(pb, "text"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, pkt->data); put_amf_string(pb, ""); avio_w8(pb, AMF_END_OF_OBJECT); } else { avio_write(pb, data ? data : pkt->data, size); } /* write total size of tag */ data_size = avio_tell(pb) - metadata_size_pos; avio_seek(pb, metadata_size_pos - 10, SEEK_SET); avio_wb24(pb, data_size); avio_seek(pb, data_size + 10 - 3, SEEK_CUR); avio_wb32(pb, data_size + 11); } else { av_assert1(flags>=0); avio_w8(pb,flags); if (par->codec_id == AV_CODEC_ID_VP6) avio_w8(pb,0); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { if (par->extradata_size) avio_w8(pb, par->extradata[0]); else avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | (FFALIGN(par->height, 16) - par->height)); } else if (par->codec_id == AV_CODEC_ID_AAC) avio_w8(pb, 1); // AAC raw else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { avio_w8(pb, 1); // AVC NALU avio_wb24(pb, pkt->pts - pkt->dts); } avio_write(pb, data ? data : pkt->data, size); avio_wb32(pb, size + flags_size + 11); // previous tag size flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration); } if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: flv->videosize += (avio_tell(pb) - cur_offset); flv->lasttimestamp = flv->acurframeindex / flv->framerate; if (pkt->flags & AV_PKT_FLAG_KEY) { double ts = flv->acurframeindex / flv->framerate; int64_t pos = cur_offset; flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; flv->lastkeyframelocation = pos; flv_append_keyframe_info(s, flv, ts, pos); } flv->acurframeindex++; break; case AVMEDIA_TYPE_AUDIO: flv->audiosize += (avio_tell(pb) - cur_offset); break; default: av_log(s, AV_LOG_WARNING, "par->codec_type is type = [%d]\n", par->codec_type); break; } } av_free(data); return pb->error; } Commit Message: avformat/flvenc: Check audio packet size Fixes: Assertion failure Fixes: assert_flvenc.c:941_1.swf Found-by: #CHEN HONGXU# <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-617
static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; FLVContext *flv = s->priv_data; FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; unsigned ts; int size = pkt->size; uint8_t *data = NULL; int flags = -1, flags_size, ret; int64_t cur_offset = avio_tell(pb); if (par->codec_type == AVMEDIA_TYPE_AUDIO && !pkt->size) { av_log(s, AV_LOG_WARNING, "Empty audio Packet\n"); return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) flags_size = 2; else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) flags_size = 5; else flags_size = 1; if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { int side_size = 0; uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { av_free(par->extradata); par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!par->extradata) { par->extradata_size = 0; return AVERROR(ENOMEM); } memcpy(par->extradata, side, side_size); par->extradata_size = side_size; flv_write_codec_header(s, par, pkt->dts); } } if (flv->delay == AV_NOPTS_VALUE) flv->delay = -pkt->dts; if (pkt->dts < -flv->delay) { av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with respect to DTS\n"); return AVERROR(EINVAL); } ts = pkt->dts; if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { write_metadata(s, ts); s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; } avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: avio_w8(pb, FLV_TAG_TYPE_VIDEO); flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; break; case AVMEDIA_TYPE_AUDIO: flags = get_audio_flags(s, par); av_assert0(size); avio_w8(pb, FLV_TAG_TYPE_AUDIO); break; case AVMEDIA_TYPE_SUBTITLE: case AVMEDIA_TYPE_DATA: avio_w8(pb, FLV_TAG_TYPE_META); break; default: return AVERROR(EINVAL); } if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { /* check if extradata looks like mp4 formatted */ if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) return ret; } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { if (!s->streams[pkt->stream_index]->nb_frames) { av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: " "use the audio bitstream filter 'aac_adtstoasc' to fix it " "('-bsf:a aac_adtstoasc' option with ffmpeg)\n"); return AVERROR_INVALIDDATA; } av_log(s, AV_LOG_WARNING, "aac bitstream error\n"); } /* check Speex packet duration */ if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than " "8 frames per packet. Adobe Flash " "Player cannot handle this!\n"); if (sc->last_ts < ts) sc->last_ts = ts; if (size + flags_size >= 1<<24) { av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n", size + flags_size, 1<<24); return AVERROR(EINVAL); } avio_wb24(pb, size + flags_size); put_timestamp(pb, ts); avio_wb24(pb, flv->reserved); if (par->codec_type == AVMEDIA_TYPE_DATA || par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { int data_size; int64_t metadata_size_pos = avio_tell(pb); if (par->codec_id == AV_CODEC_ID_TEXT) { avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "onTextData"); avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); avio_wb32(pb, 2); put_amf_string(pb, "type"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, "Text"); put_amf_string(pb, "text"); avio_w8(pb, AMF_DATA_TYPE_STRING); put_amf_string(pb, pkt->data); put_amf_string(pb, ""); avio_w8(pb, AMF_END_OF_OBJECT); } else { avio_write(pb, data ? data : pkt->data, size); } /* write total size of tag */ data_size = avio_tell(pb) - metadata_size_pos; avio_seek(pb, metadata_size_pos - 10, SEEK_SET); avio_wb24(pb, data_size); avio_seek(pb, data_size + 10 - 3, SEEK_CUR); avio_wb32(pb, data_size + 11); } else { av_assert1(flags>=0); avio_w8(pb,flags); if (par->codec_id == AV_CODEC_ID_VP6) avio_w8(pb,0); if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { if (par->extradata_size) avio_w8(pb, par->extradata[0]); else avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | (FFALIGN(par->height, 16) - par->height)); } else if (par->codec_id == AV_CODEC_ID_AAC) avio_w8(pb, 1); // AAC raw else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { avio_w8(pb, 1); // AVC NALU avio_wb24(pb, pkt->pts - pkt->dts); } avio_write(pb, data ? data : pkt->data, size); avio_wb32(pb, size + flags_size + 11); // previous tag size flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration); } if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { switch (par->codec_type) { case AVMEDIA_TYPE_VIDEO: flv->videosize += (avio_tell(pb) - cur_offset); flv->lasttimestamp = flv->acurframeindex / flv->framerate; if (pkt->flags & AV_PKT_FLAG_KEY) { double ts = flv->acurframeindex / flv->framerate; int64_t pos = cur_offset; flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; flv->lastkeyframelocation = pos; flv_append_keyframe_info(s, flv, ts, pos); } flv->acurframeindex++; break; case AVMEDIA_TYPE_AUDIO: flv->audiosize += (avio_tell(pb) - cur_offset); break; default: av_log(s, AV_LOG_WARNING, "par->codec_type is type = [%d]\n", par->codec_type); break; } } av_free(data); return pb->error; }
169,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: emit_string(const char *str, FILE *out) /* Print a string with spaces replaced by '_' and non-printing characters by * an octal escape. */ { for (; *str; ++str) if (isgraph(UCHAR_MAX & *str)) putc(*str, out); else if (isspace(UCHAR_MAX & *str)) putc('_', out); else fprintf(out, "\\%.3o", *str); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
emit_string(const char *str, FILE *out) /* Print a string with spaces replaced by '_' and non-printing characters by * an octal escape. */ { for (; *str; ++str) if (isgraph(UCHAR_MAX & *str)) putc(*str, out); else if (isspace(UCHAR_MAX & *str)) putc('_', out); else fprintf(out, "\\%.3o", *str); }
173,731
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: off_t HFSForkReadStream::Seek(off_t offset, int whence) { DCHECK_EQ(SEEK_SET, whence); DCHECK_GE(offset, 0); DCHECK_LT(static_cast<uint64_t>(offset), fork_.logicalSize); size_t target_block = offset / hfs_->block_size(); size_t block_count = 0; for (size_t i = 0; i < arraysize(fork_.extents); ++i) { const HFSPlusExtentDescriptor* extent = &fork_.extents[i]; if (extent->startBlock == 0 && extent->blockCount == 0) break; base::CheckedNumeric<size_t> new_block_count(block_count); new_block_count += extent->blockCount; if (!new_block_count.IsValid()) { DLOG(ERROR) << "Seek offset block count overflows"; return false; } if (target_block < new_block_count.ValueOrDie()) { if (current_extent_ != i) { read_current_extent_ = false; current_extent_ = i; } auto iterator_block_offset = base::CheckedNumeric<size_t>(block_count) * hfs_->block_size(); if (!iterator_block_offset.IsValid()) { DLOG(ERROR) << "Seek block offset overflows"; return false; } fork_logical_offset_ = offset; return offset; } block_count = new_block_count.ValueOrDie(); } return -1; } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
off_t HFSForkReadStream::Seek(off_t offset, int whence) { DCHECK_EQ(SEEK_SET, whence); DCHECK_GE(offset, 0); DCHECK(offset == 0 || static_cast<uint64_t>(offset) < fork_.logicalSize); size_t target_block = offset / hfs_->block_size(); size_t block_count = 0; for (size_t i = 0; i < arraysize(fork_.extents); ++i) { const HFSPlusExtentDescriptor* extent = &fork_.extents[i]; if (extent->startBlock == 0 && extent->blockCount == 0) break; base::CheckedNumeric<size_t> new_block_count(block_count); new_block_count += extent->blockCount; if (!new_block_count.IsValid()) { DLOG(ERROR) << "Seek offset block count overflows"; return false; } if (target_block < new_block_count.ValueOrDie()) { if (current_extent_ != i) { read_current_extent_ = false; current_extent_ = i; } auto iterator_block_offset = base::CheckedNumeric<size_t>(block_count) * hfs_->block_size(); if (!iterator_block_offset.IsValid()) { DLOG(ERROR) << "Seek block offset overflows"; return false; } fork_logical_offset_ = offset; return offset; } block_count = new_block_count.ValueOrDie(); } return -1; }
171,717
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Cluster::GetFirst(const BlockEntry*& pFirst) const { if (m_entries_count <= 0) { long long pos; long len; const long status = Parse(pos, len); if (status < 0) //error { pFirst = NULL; return status; } if (m_entries_count <= 0) //empty cluster { pFirst = NULL; return 0; } } assert(m_entries); pFirst = m_entries[0]; assert(pFirst); return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Cluster::GetFirst(const BlockEntry*& pFirst) const
174,320
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); columns=images->columns; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1615 CWE ID: CWE-119
static PixelChannels **AcquirePixelThreadSet(const Image *images) { const Image *next; PixelChannels **pixels; register ssize_t i; size_t columns, rows; rows=MagickMax(GetImageListLength(images), (size_t) GetMagickResourceLimit(ThreadResource)); pixels=(PixelChannels **) AcquireQuantumMemory(rows,sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); columns=MaxPixelChannels; for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) rows; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(columns,sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); }
170,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GDataRootDirectory::GDataRootDirectory() : ALLOW_THIS_IN_INITIALIZER_LIST(GDataDirectory(NULL, this)), fake_search_directory_(new GDataDirectory(NULL, NULL)), largest_changestamp_(0), serialized_size_(0) { title_ = kGDataRootDirectory; SetFileNameFromTitle(); } Commit Message: gdata: Define the resource ID for the root directory Per the spec, the resource ID for the root directory is defined as "folder:root". Add the resource ID to the root directory in our file system representation so we can look up the root directory by the resource ID. BUG=127697 TEST=add unit tests Review URL: https://chromiumcodereview.appspot.com/10332253 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137928 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
GDataRootDirectory::GDataRootDirectory() : ALLOW_THIS_IN_INITIALIZER_LIST(GDataDirectory(NULL, this)), fake_search_directory_(new GDataDirectory(NULL, NULL)), largest_changestamp_(0), serialized_size_(0) { title_ = kGDataRootDirectory; SetFileNameFromTitle(); resource_id_ = kGDataRootDirectoryResourceId; // Add self to the map so the root directory can be looked up by the // resource ID. AddEntryToResourceMap(this); }
170,777
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ContentEncoding::ContentEncoding() : compression_entries_(NULL), compression_entries_end_(NULL), encryption_entries_(NULL), encryption_entries_end_(NULL), encoding_order_(0), encoding_scope_(1), encoding_type_(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
ContentEncoding::ContentEncoding() : compression_entries_(NULL), compression_entries_end_(NULL), encryption_entries_(NULL), encryption_entries_end_(NULL), encoding_order_(0), encoding_scope_(1),
174,251
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version) { zval **oid, **value, **type; char *a1, *a2, *a3, *a4, *a5, *a6, *a7; int a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len; zend_bool use_orignames = 0, suffix_keys = 0; long timeout = SNMP_DEFAULT_TIMEOUT; long retries = SNMP_DEFAULT_RETRIES; int argc = ZEND_NUM_ARGS(); struct objid_query objid_query; php_snmp_session *session; int session_less_mode = (getThis() == NULL); php_snmp_object *snmp_object; php_snmp_object glob_snmp_object; objid_query.max_repetitions = -1; objid_query.non_repeaters = 0; objid_query.valueretrieval = SNMP_G(valueretrieval); objid_query.oid_increasing_check = TRUE; if (session_less_mode) { if (version == SNMP_VERSION_3) { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "ssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc TSRMLS_CC, "ssZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "ZZZ", &oid, &type, &value) == FAILURE) { RETURN_FALSE; } } else if (st & SNMP_CMD_WALK) { if (zend_parse_parameters(argc TSRMLS_CC, "Z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) { RETURN_FALSE; } if (suffix_keys) { st |= SNMP_USE_SUFFIX_AS_KEYS; } } else if (st & SNMP_CMD_GET) { if (zend_parse_parameters(argc TSRMLS_CC, "Z|b", &oid, &use_orignames) == FAILURE) { RETURN_FALSE; } if (use_orignames) { st |= SNMP_ORIGINAL_NAMES_AS_KEYS; } } else { /* SNMP_CMD_GETNEXT */ if (zend_parse_parameters(argc TSRMLS_CC, "Z", &oid) == FAILURE) { RETURN_FALSE; } } } if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value TSRMLS_CC)) { RETURN_FALSE; } if (session_less_mode) { if (netsnmp_session_init(&session, version, a1, a2, timeout, retries TSRMLS_CC)) { efree(objid_query.vars); netsnmp_session_free(&session); RETURN_FALSE; } if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL TSRMLS_CC)) { efree(objid_query.vars); netsnmp_session_free(&session); /* Warning message sent already, just bail out */ RETURN_FALSE; } } else { zval *object = getThis(); snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); session = snmp_object->session; if (!session) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid or uninitialized SNMP object"); efree(objid_query.vars); RETURN_FALSE; } if (snmp_object->max_oids > 0) { objid_query.step = snmp_object->max_oids; if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */ objid_query.max_repetitions = snmp_object->max_oids; } } objid_query.oid_increasing_check = snmp_object->oid_increasing_check; objid_query.valueretrieval = snmp_object->valueretrieval; glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print); glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print); glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format); } if (objid_query.max_repetitions < 0) { objid_query.max_repetitions = 20; /* provide correct default value */ } php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query); efree(objid_query.vars); if (session_less_mode) { netsnmp_session_free(&session); } else { netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format); } } Commit Message: CWE ID: CWE-416
static void php_snmp(INTERNAL_FUNCTION_PARAMETERS, int st, int version) { zval **oid, **value, **type; char *a1, *a2, *a3, *a4, *a5, *a6, *a7; int a1_len, a2_len, a3_len, a4_len, a5_len, a6_len, a7_len; zend_bool use_orignames = 0, suffix_keys = 0; long timeout = SNMP_DEFAULT_TIMEOUT; long retries = SNMP_DEFAULT_RETRIES; int argc = ZEND_NUM_ARGS(); struct objid_query objid_query; php_snmp_session *session; int session_less_mode = (getThis() == NULL); php_snmp_object *snmp_object; php_snmp_object glob_snmp_object; objid_query.max_repetitions = -1; objid_query.non_repeaters = 0; objid_query.valueretrieval = SNMP_G(valueretrieval); objid_query.oid_increasing_check = TRUE; if (session_less_mode) { if (version == SNMP_VERSION_3) { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc TSRMLS_CC, "sssssssZ|ll", &a1, &a1_len, &a2, &a2_len, &a3, &a3_len, &a4, &a4_len, &a5, &a5_len, &a6, &a6_len, &a7, &a7_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "ssZZZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &type, &value, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } else { /* SNMP_CMD_GET * SNMP_CMD_GETNEXT * SNMP_CMD_WALK */ if (zend_parse_parameters(argc TSRMLS_CC, "ssZ|ll", &a1, &a1_len, &a2, &a2_len, &oid, &timeout, &retries) == FAILURE) { RETURN_FALSE; } } } } else { if (st & SNMP_CMD_SET) { if (zend_parse_parameters(argc TSRMLS_CC, "ZZZ", &oid, &type, &value) == FAILURE) { RETURN_FALSE; } } else if (st & SNMP_CMD_WALK) { if (zend_parse_parameters(argc TSRMLS_CC, "Z|bll", &oid, &suffix_keys, &(objid_query.max_repetitions), &(objid_query.non_repeaters)) == FAILURE) { RETURN_FALSE; } if (suffix_keys) { st |= SNMP_USE_SUFFIX_AS_KEYS; } } else if (st & SNMP_CMD_GET) { if (zend_parse_parameters(argc TSRMLS_CC, "Z|b", &oid, &use_orignames) == FAILURE) { RETURN_FALSE; } if (use_orignames) { st |= SNMP_ORIGINAL_NAMES_AS_KEYS; } } else { /* SNMP_CMD_GETNEXT */ if (zend_parse_parameters(argc TSRMLS_CC, "Z", &oid) == FAILURE) { RETURN_FALSE; } } } if (!php_snmp_parse_oid(getThis(), st, &objid_query, oid, type, value TSRMLS_CC)) { RETURN_FALSE; } if (session_less_mode) { if (netsnmp_session_init(&session, version, a1, a2, timeout, retries TSRMLS_CC)) { efree(objid_query.vars); netsnmp_session_free(&session); RETURN_FALSE; } if (version == SNMP_VERSION_3 && netsnmp_session_set_security(session, a3, a4, a5, a6, a7, NULL, NULL TSRMLS_CC)) { efree(objid_query.vars); netsnmp_session_free(&session); /* Warning message sent already, just bail out */ RETURN_FALSE; } } else { zval *object = getThis(); snmp_object = (php_snmp_object *)zend_object_store_get_object(object TSRMLS_CC); session = snmp_object->session; if (!session) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid or uninitialized SNMP object"); efree(objid_query.vars); RETURN_FALSE; } if (snmp_object->max_oids > 0) { objid_query.step = snmp_object->max_oids; if (objid_query.max_repetitions < 0) { /* unspecified in function call, use session-wise */ objid_query.max_repetitions = snmp_object->max_oids; } } objid_query.oid_increasing_check = snmp_object->oid_increasing_check; objid_query.valueretrieval = snmp_object->valueretrieval; glob_snmp_object.enum_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, snmp_object->enum_print); glob_snmp_object.quick_print = netsnmp_ds_get_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, snmp_object->quick_print); glob_snmp_object.oid_output_format = netsnmp_ds_get_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, snmp_object->oid_output_format); } if (objid_query.max_repetitions < 0) { objid_query.max_repetitions = 20; /* provide correct default value */ } php_snmp_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, st, session, &objid_query); efree(objid_query.vars); if (session_less_mode) { netsnmp_session_free(&session); } else { netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_PRINT_NUMERIC_ENUM, glob_snmp_object.enum_print); netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_QUICK_PRINT, glob_snmp_object.quick_print); netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, glob_snmp_object.oid_output_format); } }
164,974
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt, int is_vp7) { VP8Context *s = avctx->priv_data; int ret, i, referenced, num_jobs; enum AVDiscard skip_thresh; VP8Frame *av_uninit(curframe), *prev_frame; if (is_vp7) ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size); else ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size); if (ret < 0) goto err; prev_frame = s->framep[VP56_FRAME_CURRENT]; referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT || s->update_altref == VP56_FRAME_CURRENT; skip_thresh = !referenced ? AVDISCARD_NONREF : !s->keyframe ? AVDISCARD_NONKEY : AVDISCARD_ALL; if (avctx->skip_frame >= skip_thresh) { s->invisible = 1; memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4); goto skip_decode; } s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh; for (i = 0; i < 5; i++) if (s->frames[i].tf.f->data[0] && &s->frames[i] != prev_frame && &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) vp8_release_frame(s, &s->frames[i]); curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s); if (!s->colorspace) avctx->colorspace = AVCOL_SPC_BT470BG; if (s->fullrange) avctx->color_range = AVCOL_RANGE_JPEG; else avctx->color_range = AVCOL_RANGE_MPEG; /* Given that arithmetic probabilities are updated every frame, it's quite * likely that the values we have on a random interframe are complete * junk if we didn't start decode on a keyframe. So just don't display * anything rather than junk. */ if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] || !s->framep[VP56_FRAME_GOLDEN] || !s->framep[VP56_FRAME_GOLDEN2])) { av_log(avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n"); ret = AVERROR_INVALIDDATA; goto err; } curframe->tf.f->key_frame = s->keyframe; curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; if ((ret = vp8_alloc_frame(s, curframe, referenced)) < 0) goto err; if (s->update_altref != VP56_FRAME_NONE) s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref]; else s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2]; if (s->update_golden != VP56_FRAME_NONE) s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden]; else s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN]; if (s->update_last) s->next_framep[VP56_FRAME_PREVIOUS] = curframe; else s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS]; s->next_framep[VP56_FRAME_CURRENT] = curframe; if (avctx->codec->update_thread_context) ff_thread_finish_setup(avctx); s->linesize = curframe->tf.f->linesize[0]; s->uvlinesize = curframe->tf.f->linesize[1]; memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz)); /* Zero macroblock structures for top/top-left prediction * from outside the frame. */ if (!s->mb_layout) memset(s->macroblocks + s->mb_height * 2 - 1, 0, (s->mb_width + 1) * sizeof(*s->macroblocks)); if (!s->mb_layout && s->keyframe) memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4); memset(s->ref_count, 0, sizeof(s->ref_count)); if (s->mb_layout == 1) { if (prev_frame && s->segmentation.enabled && !s->segmentation.update_map) ff_thread_await_progress(&prev_frame->tf, 1, 0); if (is_vp7) vp7_decode_mv_mb_modes(avctx, curframe, prev_frame); else vp8_decode_mv_mb_modes(avctx, curframe, prev_frame); } if (avctx->active_thread_type == FF_THREAD_FRAME) num_jobs = 1; else num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count); s->num_jobs = num_jobs; s->curframe = curframe; s->prev_frame = prev_frame; s->mv_bounds.mv_min.y = -MARGIN; s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN; for (i = 0; i < MAX_THREADS; i++) { VP8ThreadData *td = &s->thread_data[i]; atomic_init(&td->thread_mb_pos, 0); atomic_init(&td->wait_mb_pos, INT_MAX); } if (is_vp7) avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL, num_jobs); else avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL, num_jobs); ff_thread_report_progress(&curframe->tf, INT_MAX, 0); memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4); skip_decode: if (!s->update_probabilities) s->prob[0] = s->prob[1]; if (!s->invisible) { if ((ret = av_frame_ref(data, curframe->tf.f)) < 0) return ret; *got_frame = 1; } return avpkt->size; err: memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4); return ret; } Commit Message: avcodec/webp: Always set pix_fmt Fixes: out of array access Fixes: 1434/clusterfuzz-testcase-minimized-6314998085189632 Fixes: 1435/clusterfuzz-testcase-minimized-6483783723253760 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Reviewed-by: "Ronald S. Bultje" <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt, int is_vp7) { VP8Context *s = avctx->priv_data; int ret, i, referenced, num_jobs; enum AVDiscard skip_thresh; VP8Frame *av_uninit(curframe), *prev_frame; av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVA420P || avctx->pix_fmt == AV_PIX_FMT_YUV420P); if (is_vp7) ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size); else ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size); if (ret < 0) goto err; prev_frame = s->framep[VP56_FRAME_CURRENT]; referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT || s->update_altref == VP56_FRAME_CURRENT; skip_thresh = !referenced ? AVDISCARD_NONREF : !s->keyframe ? AVDISCARD_NONKEY : AVDISCARD_ALL; if (avctx->skip_frame >= skip_thresh) { s->invisible = 1; memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4); goto skip_decode; } s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh; for (i = 0; i < 5; i++) if (s->frames[i].tf.f->data[0] && &s->frames[i] != prev_frame && &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN] && &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2]) vp8_release_frame(s, &s->frames[i]); curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s); if (!s->colorspace) avctx->colorspace = AVCOL_SPC_BT470BG; if (s->fullrange) avctx->color_range = AVCOL_RANGE_JPEG; else avctx->color_range = AVCOL_RANGE_MPEG; /* Given that arithmetic probabilities are updated every frame, it's quite * likely that the values we have on a random interframe are complete * junk if we didn't start decode on a keyframe. So just don't display * anything rather than junk. */ if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] || !s->framep[VP56_FRAME_GOLDEN] || !s->framep[VP56_FRAME_GOLDEN2])) { av_log(avctx, AV_LOG_WARNING, "Discarding interframe without a prior keyframe!\n"); ret = AVERROR_INVALIDDATA; goto err; } curframe->tf.f->key_frame = s->keyframe; curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; if ((ret = vp8_alloc_frame(s, curframe, referenced)) < 0) goto err; if (s->update_altref != VP56_FRAME_NONE) s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref]; else s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2]; if (s->update_golden != VP56_FRAME_NONE) s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden]; else s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN]; if (s->update_last) s->next_framep[VP56_FRAME_PREVIOUS] = curframe; else s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS]; s->next_framep[VP56_FRAME_CURRENT] = curframe; if (avctx->codec->update_thread_context) ff_thread_finish_setup(avctx); s->linesize = curframe->tf.f->linesize[0]; s->uvlinesize = curframe->tf.f->linesize[1]; memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz)); /* Zero macroblock structures for top/top-left prediction * from outside the frame. */ if (!s->mb_layout) memset(s->macroblocks + s->mb_height * 2 - 1, 0, (s->mb_width + 1) * sizeof(*s->macroblocks)); if (!s->mb_layout && s->keyframe) memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4); memset(s->ref_count, 0, sizeof(s->ref_count)); if (s->mb_layout == 1) { if (prev_frame && s->segmentation.enabled && !s->segmentation.update_map) ff_thread_await_progress(&prev_frame->tf, 1, 0); if (is_vp7) vp7_decode_mv_mb_modes(avctx, curframe, prev_frame); else vp8_decode_mv_mb_modes(avctx, curframe, prev_frame); } if (avctx->active_thread_type == FF_THREAD_FRAME) num_jobs = 1; else num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count); s->num_jobs = num_jobs; s->curframe = curframe; s->prev_frame = prev_frame; s->mv_bounds.mv_min.y = -MARGIN; s->mv_bounds.mv_max.y = ((s->mb_height - 1) << 6) + MARGIN; for (i = 0; i < MAX_THREADS; i++) { VP8ThreadData *td = &s->thread_data[i]; atomic_init(&td->thread_mb_pos, 0); atomic_init(&td->wait_mb_pos, INT_MAX); } if (is_vp7) avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL, num_jobs); else avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL, num_jobs); ff_thread_report_progress(&curframe->tf, INT_MAX, 0); memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4); skip_decode: if (!s->update_probabilities) s->prob[0] = s->prob[1]; if (!s->invisible) { if ((ret = av_frame_ref(data, curframe->tf.f)) < 0) return ret; *got_frame = 1; } return avpkt->size; err: memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4); return ret; }
168,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 UsbFindDevicesFunction::OnGetDevicesComplete( const std::vector<scoped_refptr<UsbDevice>>& devices) { result_.reset(new base::ListValue()); barrier_ = base::BarrierClosure( devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this)); for (const scoped_refptr<UsbDevice>& device : devices) { if (device->vendor_id() != vendor_id_ || device->product_id() != product_id_) { barrier_.Run(); } else { device->OpenInterface( interface_id_, base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this)); } } } 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
void UsbFindDevicesFunction::OnGetDevicesComplete( const std::vector<scoped_refptr<UsbDevice>>& devices) { result_.reset(new base::ListValue()); barrier_ = base::BarrierClosure( devices.size(), base::Bind(&UsbFindDevicesFunction::OpenComplete, this)); for (const scoped_refptr<UsbDevice>& device : devices) { if (device->vendor_id() != vendor_id_ || device->product_id() != product_id_) { barrier_.Run(); } else { device->Open(base::Bind(&UsbFindDevicesFunction::OnDeviceOpened, this)); } } }
171,703
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct dentry *debugfs_rename(struct dentry *old_dir, struct dentry *old_dentry, struct dentry *new_dir, const char *new_name) { int error; struct dentry *dentry = NULL, *trap; const char *old_name; trap = lock_rename(new_dir, old_dir); /* Source or destination directories don't exist? */ if (d_really_is_negative(old_dir) || d_really_is_negative(new_dir)) goto exit; /* Source does not exist, cyclic rename, or mountpoint? */ if (d_really_is_negative(old_dentry) || old_dentry == trap || d_mountpoint(old_dentry)) goto exit; dentry = lookup_one_len(new_name, new_dir, strlen(new_name)); /* Lookup failed, cyclic rename or target exists? */ if (IS_ERR(dentry) || dentry == trap || d_really_is_positive(dentry)) goto exit; old_name = fsnotify_oldname_init(old_dentry->d_name.name); error = simple_rename(d_inode(old_dir), old_dentry, d_inode(new_dir), dentry, 0); if (error) { fsnotify_oldname_free(old_name); goto exit; } d_move(old_dentry, dentry); fsnotify_move(d_inode(old_dir), d_inode(new_dir), old_name, d_is_dir(old_dentry), NULL, old_dentry); fsnotify_oldname_free(old_name); unlock_rename(new_dir, old_dir); dput(dentry); return old_dentry; exit: if (dentry && !IS_ERR(dentry)) dput(dentry); unlock_rename(new_dir, old_dir); return NULL; } Commit Message: dentry name snapshots take_dentry_name_snapshot() takes a safe snapshot of dentry name; if the name is a short one, it gets copied into caller-supplied structure, otherwise an extra reference to external name is grabbed (those are never modified). In either case the pointer to stable string is stored into the same structure. dentry must be held by the caller of take_dentry_name_snapshot(), but may be freely dropped afterwards - the snapshot will stay until destroyed by release_dentry_name_snapshot(). Intended use: struct name_snapshot s; take_dentry_name_snapshot(&s, dentry); ... access s.name ... release_dentry_name_snapshot(&s); Replaces fsnotify_oldname_...(), gets used in fsnotify to obtain the name to pass down with event. Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-362
struct dentry *debugfs_rename(struct dentry *old_dir, struct dentry *old_dentry, struct dentry *new_dir, const char *new_name) { int error; struct dentry *dentry = NULL, *trap; struct name_snapshot old_name; trap = lock_rename(new_dir, old_dir); /* Source or destination directories don't exist? */ if (d_really_is_negative(old_dir) || d_really_is_negative(new_dir)) goto exit; /* Source does not exist, cyclic rename, or mountpoint? */ if (d_really_is_negative(old_dentry) || old_dentry == trap || d_mountpoint(old_dentry)) goto exit; dentry = lookup_one_len(new_name, new_dir, strlen(new_name)); /* Lookup failed, cyclic rename or target exists? */ if (IS_ERR(dentry) || dentry == trap || d_really_is_positive(dentry)) goto exit; take_dentry_name_snapshot(&old_name, old_dentry); error = simple_rename(d_inode(old_dir), old_dentry, d_inode(new_dir), dentry, 0); if (error) { release_dentry_name_snapshot(&old_name); goto exit; } d_move(old_dentry, dentry); fsnotify_move(d_inode(old_dir), d_inode(new_dir), old_name.name, d_is_dir(old_dentry), NULL, old_dentry); release_dentry_name_snapshot(&old_name); unlock_rename(new_dir, old_dir); dput(dentry); return old_dentry; exit: if (dentry && !IS_ERR(dentry)) dput(dentry); unlock_rename(new_dir, old_dir); return NULL; }
168,262
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ixheaacd_shiftrountine_with_rnd_hq(WORD32 *qmf_real, WORD32 *qmf_imag, WORD32 *filter_states, WORD32 len, WORD32 shift) { WORD32 *filter_states_rev = filter_states + len; WORD32 treal, timag; WORD32 j; for (j = (len - 1); j >= 0; j -= 2) { WORD32 r1, r2, i1, i2; i2 = qmf_imag[j]; r2 = qmf_real[j]; r1 = *qmf_real++; i1 = *qmf_imag++; timag = ixheaacd_add32(i1, r1); timag = (ixheaacd_shl32_sat(timag, shift)); filter_states_rev[j] = timag; treal = ixheaacd_sub32(i2, r2); treal = (ixheaacd_shl32_sat(treal, shift)); filter_states[j] = treal; treal = ixheaacd_sub32(i1, r1); treal = (ixheaacd_shl32_sat(treal, shift)); *filter_states++ = treal; timag = ixheaacd_add32(i2, r2); timag = (ixheaacd_shl32_sat(timag, shift)); *filter_states_rev++ = timag; } } Commit Message: Fix for stack corruption in esbr Bug: 110769924 Test: poc from bug before/after Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e (cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a) (cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50) CWE ID: CWE-787
VOID ixheaacd_shiftrountine_with_rnd_hq(WORD32 *qmf_real, WORD32 *qmf_imag, WORD32 *filter_states, WORD32 len, WORD32 shift) { WORD32 *filter_states_rev = filter_states + len; WORD32 treal, timag; WORD32 j; for (j = (len - 1); j >= 0; j -= 2) { WORD32 r1, r2, i1, i2; i2 = qmf_imag[j]; r2 = qmf_real[j]; r1 = *qmf_real++; i1 = *qmf_imag++; timag = ixheaacd_add32_sat(i1, r1); timag = (ixheaacd_shl32_sat(timag, shift)); filter_states_rev[j] = timag; treal = ixheaacd_sub32_sat(i2, r2); treal = (ixheaacd_shl32_sat(treal, shift)); filter_states[j] = treal; treal = ixheaacd_sub32_sat(i1, r1); treal = (ixheaacd_shl32_sat(treal, shift)); *filter_states++ = treal; timag = ixheaacd_add32_sat(i2, r2); timag = (ixheaacd_shl32_sat(timag, shift)); *filter_states_rev++ = timag; } }
174,089
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 XvMCGetDRInfo(Display *dpy, XvPortID port, char **name, char **busID, int *major, int *minor, int *patchLevel, int *isLocal) { XExtDisplayInfo *info = xvmc_find_display(dpy); xvmcGetDRInfoReply rep; xvmcGetDRInfoReq *req; CARD32 magic; #ifdef HAVE_SHMAT volatile CARD32 *shMem; struct timezone here; struct timeval now; here.tz_minuteswest = 0; here.tz_dsttime = 0; #endif *name = NULL; *busID = NULL; XvMCCheckExtension (dpy, info, BadImplementation); LockDisplay (dpy); XvMCGetReq (GetDRInfo, req); req->port = port; magic = 0; req->magic = 0; #ifdef HAVE_SHMAT req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600); /* * We fill a shared memory page with a repetitive pattern. If the * X server can read this pattern, we probably have a local connection. * Note that we can trigger the remote X server to read any shared * page on the remote machine, so we shouldn't be able to guess and verify * any complicated data on those pages. Thats the explanation of this * otherwise stupid-looking pattern algorithm. */ if (req->shmKey >= 0) { shMem = (CARD32 *) shmat(req->shmKey, NULL, 0); shmctl( req->shmKey, IPC_RMID, NULL); if ( shMem ) { register volatile CARD32 *shMemC = shMem; register int i; gettimeofday( &now, &here); magic = now.tv_usec & 0x000FFFFF; req->magic = magic; i = 1024 / sizeof(CARD32); while(i--) { *shMemC++ = magic; magic = ~magic; } } else { req->shmKey = -1; } } #else req->shmKey = 0; #endif if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); #ifdef HAVE_SHMAT if ( req->shmKey >= 0) { shmdt( (const void *) shMem ); } #endif return -1; } #ifdef HAVE_SHMAT shmdt( (const void *) shMem ); #endif if (rep.length > 0) { unsigned long realSize = 0; char *tmpBuf = NULL; if ((rep.length < (INT_MAX >> 2)) && /* protect against overflow in strncpy below */ (rep.nameLen + rep.busIDLen > rep.nameLen)) { realSize = rep.length << 2; if (realSize >= (rep.nameLen + rep.busIDLen)) { tmpBuf = Xmalloc(realSize); *name = Xmalloc(rep.nameLen); *busID = Xmalloc(rep.busIDLen); } } if (*name && *busID && tmpBuf) { _XRead(dpy, tmpBuf, realSize); strncpy(*name,tmpBuf,rep.nameLen); (*name)[rep.nameLen - 1] = '\0'; strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen); (*busID)[rep.busIDLen - 1] = '\0'; XFree(tmpBuf); } else { XFree(*name); *name = NULL; XFree(*busID); *busID = NULL; XFree(tmpBuf); _XEatDataWords(dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return -1; } } UnlockDisplay (dpy); SyncHandle (); *major = rep.major; *minor = rep.minor; *patchLevel = rep.patchLevel; *isLocal = (req->shmKey > 0) ? rep.isLocal : 1; return (rep.length > 0) ? Success : BadImplementation; } Commit Message: CWE ID: CWE-119
Status XvMCGetDRInfo(Display *dpy, XvPortID port, char **name, char **busID, int *major, int *minor, int *patchLevel, int *isLocal) { XExtDisplayInfo *info = xvmc_find_display(dpy); xvmcGetDRInfoReply rep; xvmcGetDRInfoReq *req; CARD32 magic; #ifdef HAVE_SHMAT volatile CARD32 *shMem; struct timezone here; struct timeval now; here.tz_minuteswest = 0; here.tz_dsttime = 0; #endif *name = NULL; *busID = NULL; XvMCCheckExtension (dpy, info, BadImplementation); LockDisplay (dpy); XvMCGetReq (GetDRInfo, req); req->port = port; magic = 0; req->magic = 0; #ifdef HAVE_SHMAT req->shmKey = shmget(IPC_PRIVATE, 1024, IPC_CREAT | 0600); /* * We fill a shared memory page with a repetitive pattern. If the * X server can read this pattern, we probably have a local connection. * Note that we can trigger the remote X server to read any shared * page on the remote machine, so we shouldn't be able to guess and verify * any complicated data on those pages. Thats the explanation of this * otherwise stupid-looking pattern algorithm. */ if (req->shmKey >= 0) { shMem = (CARD32 *) shmat(req->shmKey, NULL, 0); shmctl( req->shmKey, IPC_RMID, NULL); if ( shMem ) { register volatile CARD32 *shMemC = shMem; register int i; gettimeofday( &now, &here); magic = now.tv_usec & 0x000FFFFF; req->magic = magic; i = 1024 / sizeof(CARD32); while(i--) { *shMemC++ = magic; magic = ~magic; } } else { req->shmKey = -1; } } #else req->shmKey = 0; #endif if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); #ifdef HAVE_SHMAT if ( req->shmKey >= 0) { shmdt( (const void *) shMem ); } #endif return -1; } #ifdef HAVE_SHMAT shmdt( (const void *) shMem ); #endif if (rep.length > 0) { unsigned long realSize = 0; char *tmpBuf = NULL; if ((rep.length < (INT_MAX >> 2)) && /* protect against overflow in strncpy below */ (rep.nameLen + rep.busIDLen > rep.nameLen)) { realSize = rep.length << 2; if (realSize >= (rep.nameLen + rep.busIDLen)) { tmpBuf = Xmalloc(realSize); *name = Xmalloc(rep.nameLen); *busID = Xmalloc(rep.busIDLen); } } if (*name && *busID && tmpBuf) { _XRead(dpy, tmpBuf, realSize); strncpy(*name,tmpBuf,rep.nameLen); (*name)[rep.nameLen == 0 ? 0 : rep.nameLen - 1] = '\0'; strncpy(*busID,tmpBuf+rep.nameLen,rep.busIDLen); (*busID)[rep.busIDLen == 0 ? 0 : rep.busIDLen - 1] = '\0'; XFree(tmpBuf); } else { XFree(*name); *name = NULL; XFree(*busID); *busID = NULL; XFree(tmpBuf); _XEatDataWords(dpy, rep.length); UnlockDisplay (dpy); SyncHandle (); return -1; } } UnlockDisplay (dpy); SyncHandle (); *major = rep.major; *minor = rep.minor; *patchLevel = rep.patchLevel; *isLocal = (req->shmKey > 0) ? rep.isLocal : 1; return (rep.length > 0) ? Success : BadImplementation; }
164,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: void APIPermissionInfo::RegisterAllPermissions( PermissionsInfo* info) { struct PermissionRegistration { APIPermission::ID id; const char* name; int flags; int l10n_message_id; PermissionMessage::ID message_id; APIPermissionConstructor constructor; } PermissionsToRegister[] = { { APIPermission::kBackground, "background" }, { APIPermission::kClipboardRead, "clipboardRead", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD, PermissionMessage::kClipboard }, { APIPermission::kClipboardWrite, "clipboardWrite" }, { APIPermission::kDeclarativeWebRequest, "declarativeWebRequest" }, { APIPermission::kDownloads, "downloads", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS, PermissionMessage::kDownloads }, { APIPermission::kExperimental, "experimental", kFlagCannotBeOptional }, { APIPermission::kGeolocation, "geolocation", kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION, PermissionMessage::kGeolocation }, { APIPermission::kNotification, "notifications" }, { APIPermission::kUnlimitedStorage, "unlimitedStorage", kFlagCannotBeOptional }, { APIPermission::kAppNotifications, "appNotifications" }, { APIPermission::kActiveTab, "activeTab" }, { APIPermission::kAlarms, "alarms" }, { APIPermission::kBookmark, "bookmarks", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS, PermissionMessage::kBookmarks }, { APIPermission::kBrowsingData, "browsingData" }, { APIPermission::kContentSettings, "contentSettings", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS, PermissionMessage::kContentSettings }, { APIPermission::kContextMenus, "contextMenus" }, { APIPermission::kCookie, "cookies" }, { APIPermission::kFileBrowserHandler, "fileBrowserHandler", kFlagCannotBeOptional }, { APIPermission::kFontSettings, "fontSettings", kFlagCannotBeOptional }, { APIPermission::kHistory, "history", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY, PermissionMessage::kBrowsingHistory }, { APIPermission::kIdle, "idle" }, { APIPermission::kInput, "input", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_INPUT, PermissionMessage::kInput }, { APIPermission::kManagement, "management", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT, PermissionMessage::kManagement }, { APIPermission::kPrivacy, "privacy", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_PRIVACY, PermissionMessage::kPrivacy }, { APIPermission::kStorage, "storage" }, { APIPermission::kSyncFileSystem, "syncFileSystem" }, { APIPermission::kTab, "tabs", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs }, { APIPermission::kTopSites, "topSites", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY, PermissionMessage::kBrowsingHistory }, { APIPermission::kTts, "tts", 0, kFlagCannotBeOptional }, { APIPermission::kTtsEngine, "ttsEngine", kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE, PermissionMessage::kTtsEngine }, { APIPermission::kWebNavigation, "webNavigation", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs }, { APIPermission::kWebRequest, "webRequest" }, { APIPermission::kWebRequestBlocking, "webRequestBlocking" }, { APIPermission::kWebView, "webview", kFlagCannotBeOptional }, { APIPermission::kBookmarkManagerPrivate, "bookmarkManagerPrivate", kFlagCannotBeOptional }, { APIPermission::kChromeosInfoPrivate, "chromeosInfoPrivate", kFlagCannotBeOptional }, { APIPermission::kFileBrowserHandlerInternal, "fileBrowserHandlerInternal", kFlagCannotBeOptional }, { APIPermission::kFileBrowserPrivate, "fileBrowserPrivate", kFlagCannotBeOptional }, { APIPermission::kManagedModePrivate, "managedModePrivate", kFlagCannotBeOptional }, { APIPermission::kMediaPlayerPrivate, "mediaPlayerPrivate", kFlagCannotBeOptional }, { APIPermission::kMetricsPrivate, "metricsPrivate", kFlagCannotBeOptional }, { APIPermission::kSystemPrivate, "systemPrivate", kFlagCannotBeOptional }, { APIPermission::kCloudPrintPrivate, "cloudPrintPrivate", kFlagCannotBeOptional }, { APIPermission::kInputMethodPrivate, "inputMethodPrivate", kFlagCannotBeOptional }, { APIPermission::kEchoPrivate, "echoPrivate", kFlagCannotBeOptional }, { APIPermission::kRtcPrivate, "rtcPrivate", kFlagCannotBeOptional }, { APIPermission::kTerminalPrivate, "terminalPrivate", kFlagCannotBeOptional }, { APIPermission::kWallpaperPrivate, "wallpaperPrivate", kFlagCannotBeOptional }, { APIPermission::kWebRequestInternal, "webRequestInternal" }, { APIPermission::kWebSocketProxyPrivate, "webSocketProxyPrivate", kFlagCannotBeOptional }, { APIPermission::kWebstorePrivate, "webstorePrivate", kFlagCannotBeOptional }, { APIPermission::kMediaGalleriesPrivate, "mediaGalleriesPrivate", kFlagCannotBeOptional }, { APIPermission::kDebugger, "debugger", kFlagImpliesFullURLAccess | kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_DEBUGGER, PermissionMessage::kDebugger }, { APIPermission::kDevtools, "devtools", kFlagImpliesFullURLAccess | kFlagCannotBeOptional }, { APIPermission::kPageCapture, "pageCapture", kFlagImpliesFullURLAccess }, { APIPermission::kTabCapture, "tabCapture", kFlagImpliesFullURLAccess }, { APIPermission::kPlugin, "plugin", kFlagImpliesFullURLAccess | kFlagImpliesFullAccess | kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS, PermissionMessage::kFullAccess }, { APIPermission::kProxy, "proxy", kFlagImpliesFullURLAccess | kFlagCannotBeOptional }, { APIPermission::kSerial, "serial", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_SERIAL, PermissionMessage::kSerial }, { APIPermission::kSocket, "socket", kFlagCannotBeOptional, 0, PermissionMessage::kNone, &::CreateAPIPermission<SocketPermission> }, { APIPermission::kAppCurrentWindowInternal, "app.currentWindowInternal" }, { APIPermission::kAppRuntime, "app.runtime" }, { APIPermission::kAppWindow, "app.window" }, { APIPermission::kAudioCapture, "audioCapture", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE, PermissionMessage::kAudioCapture }, { APIPermission::kVideoCapture, "videoCapture", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE, PermissionMessage::kVideoCapture }, { APIPermission::kFileSystem, "fileSystem" }, { APIPermission::kFileSystemWrite, "fileSystem.write", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE, PermissionMessage::kFileSystemWrite }, { APIPermission::kMediaGalleries, "mediaGalleries" }, { APIPermission::kMediaGalleriesRead, "mediaGalleries.read" }, { APIPermission::kMediaGalleriesAllAutoDetected, "mediaGalleries.allAutoDetected", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES, PermissionMessage::kMediaGalleriesAllGalleries }, { APIPermission::kPushMessaging, "pushMessaging", kFlagCannotBeOptional }, { APIPermission::kBluetooth, "bluetooth", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BLUETOOTH, PermissionMessage::kBluetooth }, { APIPermission::kBluetoothDevice, "bluetoothDevice", kFlagNone, 0, PermissionMessage::kNone, &::CreateAPIPermission<BluetoothDevicePermission> }, { APIPermission::kUsb, "usb", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_USB, PermissionMessage::kUsb }, { APIPermission::kSystemIndicator, "systemIndicator", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_SYSTEM_INDICATOR, PermissionMessage::kSystemIndicator }, { APIPermission::kPointerLock, "pointerLock" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) { const PermissionRegistration& pr = PermissionsToRegister[i]; info->RegisterPermission( pr.id, pr.name, pr.l10n_message_id, pr.message_id ? pr.message_id : PermissionMessage::kNone, pr.flags, pr.constructor); } info->RegisterAlias("unlimitedStorage", kOldUnlimitedStoragePermission); info->RegisterAlias("tabs", kWindowsPermission); } Commit Message: DIAL (Discovery and Launch protocol) extension API skeleton. This implements the skeleton for a new Chrome extension API for local device discovery. The API will first be restricted to whitelisted extensions only. The API will allow extensions to receive events from a DIAL service running within Chrome which notifies of devices being discovered on the local network. Spec available here: https://docs.google.com/a/google.com/document/d/14FI-VKWrsMG7pIy3trgM3ybnKS-o5TULkt8itiBNXlQ/edit BUG=163288 [email protected] Review URL: https://chromiumcodereview.appspot.com/11444020 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@172243 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void APIPermissionInfo::RegisterAllPermissions( PermissionsInfo* info) { struct PermissionRegistration { APIPermission::ID id; const char* name; int flags; int l10n_message_id; PermissionMessage::ID message_id; APIPermissionConstructor constructor; } PermissionsToRegister[] = { { APIPermission::kBackground, "background" }, { APIPermission::kClipboardRead, "clipboardRead", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_CLIPBOARD, PermissionMessage::kClipboard }, { APIPermission::kClipboardWrite, "clipboardWrite" }, { APIPermission::kDeclarativeWebRequest, "declarativeWebRequest" }, { APIPermission::kDownloads, "downloads", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_DOWNLOADS, PermissionMessage::kDownloads }, { APIPermission::kExperimental, "experimental", kFlagCannotBeOptional }, { APIPermission::kGeolocation, "geolocation", kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_GEOLOCATION, PermissionMessage::kGeolocation }, { APIPermission::kNotification, "notifications" }, { APIPermission::kUnlimitedStorage, "unlimitedStorage", kFlagCannotBeOptional }, { APIPermission::kAppNotifications, "appNotifications" }, { APIPermission::kActiveTab, "activeTab" }, { APIPermission::kAlarms, "alarms" }, { APIPermission::kBookmark, "bookmarks", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BOOKMARKS, PermissionMessage::kBookmarks }, { APIPermission::kBrowsingData, "browsingData" }, { APIPermission::kContentSettings, "contentSettings", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_CONTENT_SETTINGS, PermissionMessage::kContentSettings }, { APIPermission::kContextMenus, "contextMenus" }, { APIPermission::kCookie, "cookies" }, { APIPermission::kFileBrowserHandler, "fileBrowserHandler", kFlagCannotBeOptional }, { APIPermission::kFontSettings, "fontSettings", kFlagCannotBeOptional }, { APIPermission::kHistory, "history", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY, PermissionMessage::kBrowsingHistory }, { APIPermission::kIdle, "idle" }, { APIPermission::kInput, "input", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_INPUT, PermissionMessage::kInput }, { APIPermission::kManagement, "management", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_MANAGEMENT, PermissionMessage::kManagement }, { APIPermission::kPrivacy, "privacy", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_PRIVACY, PermissionMessage::kPrivacy }, { APIPermission::kStorage, "storage" }, { APIPermission::kSyncFileSystem, "syncFileSystem" }, { APIPermission::kTab, "tabs", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs }, { APIPermission::kTopSites, "topSites", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BROWSING_HISTORY, PermissionMessage::kBrowsingHistory }, { APIPermission::kTts, "tts", 0, kFlagCannotBeOptional }, { APIPermission::kTtsEngine, "ttsEngine", kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_TTS_ENGINE, PermissionMessage::kTtsEngine }, { APIPermission::kWebNavigation, "webNavigation", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_TABS, PermissionMessage::kTabs }, { APIPermission::kWebRequest, "webRequest" }, { APIPermission::kWebRequestBlocking, "webRequestBlocking" }, { APIPermission::kWebView, "webview", kFlagCannotBeOptional }, { APIPermission::kBookmarkManagerPrivate, "bookmarkManagerPrivate", kFlagCannotBeOptional }, { APIPermission::kChromeosInfoPrivate, "chromeosInfoPrivate", kFlagCannotBeOptional }, { APIPermission::kDial, "dial", kFlagCannotBeOptional }, { APIPermission::kFileBrowserHandlerInternal, "fileBrowserHandlerInternal", kFlagCannotBeOptional }, { APIPermission::kFileBrowserPrivate, "fileBrowserPrivate", kFlagCannotBeOptional }, { APIPermission::kManagedModePrivate, "managedModePrivate", kFlagCannotBeOptional }, { APIPermission::kMediaPlayerPrivate, "mediaPlayerPrivate", kFlagCannotBeOptional }, { APIPermission::kMetricsPrivate, "metricsPrivate", kFlagCannotBeOptional }, { APIPermission::kSystemPrivate, "systemPrivate", kFlagCannotBeOptional }, { APIPermission::kCloudPrintPrivate, "cloudPrintPrivate", kFlagCannotBeOptional }, { APIPermission::kInputMethodPrivate, "inputMethodPrivate", kFlagCannotBeOptional }, { APIPermission::kEchoPrivate, "echoPrivate", kFlagCannotBeOptional }, { APIPermission::kRtcPrivate, "rtcPrivate", kFlagCannotBeOptional }, { APIPermission::kTerminalPrivate, "terminalPrivate", kFlagCannotBeOptional }, { APIPermission::kWallpaperPrivate, "wallpaperPrivate", kFlagCannotBeOptional }, { APIPermission::kWebRequestInternal, "webRequestInternal" }, { APIPermission::kWebSocketProxyPrivate, "webSocketProxyPrivate", kFlagCannotBeOptional }, { APIPermission::kWebstorePrivate, "webstorePrivate", kFlagCannotBeOptional }, { APIPermission::kMediaGalleriesPrivate, "mediaGalleriesPrivate", kFlagCannotBeOptional }, { APIPermission::kDebugger, "debugger", kFlagImpliesFullURLAccess | kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_DEBUGGER, PermissionMessage::kDebugger }, { APIPermission::kDevtools, "devtools", kFlagImpliesFullURLAccess | kFlagCannotBeOptional }, { APIPermission::kPageCapture, "pageCapture", kFlagImpliesFullURLAccess }, { APIPermission::kTabCapture, "tabCapture", kFlagImpliesFullURLAccess }, { APIPermission::kPlugin, "plugin", kFlagImpliesFullURLAccess | kFlagImpliesFullAccess | kFlagCannotBeOptional, IDS_EXTENSION_PROMPT_WARNING_FULL_ACCESS, PermissionMessage::kFullAccess }, { APIPermission::kProxy, "proxy", kFlagImpliesFullURLAccess | kFlagCannotBeOptional }, { APIPermission::kSerial, "serial", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_SERIAL, PermissionMessage::kSerial }, { APIPermission::kSocket, "socket", kFlagCannotBeOptional, 0, PermissionMessage::kNone, &::CreateAPIPermission<SocketPermission> }, { APIPermission::kAppCurrentWindowInternal, "app.currentWindowInternal" }, { APIPermission::kAppRuntime, "app.runtime" }, { APIPermission::kAppWindow, "app.window" }, { APIPermission::kAudioCapture, "audioCapture", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_AUDIO_CAPTURE, PermissionMessage::kAudioCapture }, { APIPermission::kVideoCapture, "videoCapture", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_VIDEO_CAPTURE, PermissionMessage::kVideoCapture }, { APIPermission::kFileSystem, "fileSystem" }, { APIPermission::kFileSystemWrite, "fileSystem.write", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_FILE_SYSTEM_WRITE, PermissionMessage::kFileSystemWrite }, { APIPermission::kMediaGalleries, "mediaGalleries" }, { APIPermission::kMediaGalleriesRead, "mediaGalleries.read" }, { APIPermission::kMediaGalleriesAllAutoDetected, "mediaGalleries.allAutoDetected", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_ALL_GALLERIES, PermissionMessage::kMediaGalleriesAllGalleries }, { APIPermission::kPushMessaging, "pushMessaging", kFlagCannotBeOptional }, { APIPermission::kBluetooth, "bluetooth", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_BLUETOOTH, PermissionMessage::kBluetooth }, { APIPermission::kBluetoothDevice, "bluetoothDevice", kFlagNone, 0, PermissionMessage::kNone, &::CreateAPIPermission<BluetoothDevicePermission> }, { APIPermission::kUsb, "usb", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_USB, PermissionMessage::kUsb }, { APIPermission::kSystemIndicator, "systemIndicator", kFlagNone, IDS_EXTENSION_PROMPT_WARNING_SYSTEM_INDICATOR, PermissionMessage::kSystemIndicator }, { APIPermission::kPointerLock, "pointerLock" }, }; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(PermissionsToRegister); ++i) { const PermissionRegistration& pr = PermissionsToRegister[i]; info->RegisterPermission( pr.id, pr.name, pr.l10n_message_id, pr.message_id ? pr.message_id : PermissionMessage::kNone, pr.flags, pr.constructor); } info->RegisterAlias("unlimitedStorage", kOldUnlimitedStoragePermission); info->RegisterAlias("tabs", kWindowsPermission); }
171,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 int efx_ethtool_set_ringparam(struct net_device *net_dev, struct ethtool_ringparam *ring) { struct efx_nic *efx = netdev_priv(net_dev); if (ring->rx_mini_pending || ring->rx_jumbo_pending || ring->rx_pending > EFX_MAX_DMAQ_SIZE || ring->tx_pending > EFX_MAX_DMAQ_SIZE) return -EINVAL; if (ring->rx_pending < EFX_MIN_RING_SIZE || ring->tx_pending < EFX_MIN_RING_SIZE) { netif_err(efx, drv, efx->net_dev, "TX and RX queues cannot be smaller than %ld\n", EFX_MIN_RING_SIZE); return -EINVAL; } return efx_realloc_channels(efx, ring->rx_pending, ring->tx_pending); } Commit Message: sfc: Fix maximum number of TSO segments and minimum TX queue size [ Upstream commit 7e6d06f0de3f74ca929441add094518ae332257c ] Currently an skb requiring TSO may not fit within a minimum-size TX queue. The TX queue selected for the skb may stall and trigger the TX watchdog repeatedly (since the problem skb will be retried after the TX reset). This issue is designated as CVE-2012-3412. Set the maximum number of TSO segments for our devices to 100. This should make no difference to behaviour unless the actual MSS is less than about 700. Increase the minimum TX queue size accordingly to allow for 2 worst-case skbs, so that there will definitely be space to add an skb after we wake a queue. To avoid invalidating existing configurations, change efx_ethtool_set_ringparam() to fix up values that are too small rather than returning -EINVAL. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> Signed-off-by: Ben Hutchings <[email protected]> CWE ID: CWE-189
static int efx_ethtool_set_ringparam(struct net_device *net_dev, struct ethtool_ringparam *ring) { struct efx_nic *efx = netdev_priv(net_dev); u32 txq_entries; if (ring->rx_mini_pending || ring->rx_jumbo_pending || ring->rx_pending > EFX_MAX_DMAQ_SIZE || ring->tx_pending > EFX_MAX_DMAQ_SIZE) return -EINVAL; if (ring->rx_pending < EFX_RXQ_MIN_ENT) { netif_err(efx, drv, efx->net_dev, "RX queues cannot be smaller than %u\n", EFX_RXQ_MIN_ENT); return -EINVAL; } txq_entries = max(ring->tx_pending, EFX_TXQ_MIN_ENT(efx)); if (txq_entries != ring->tx_pending) netif_warn(efx, drv, efx->net_dev, "increasing TX queue size to minimum of %u\n", txq_entries); return efx_realloc_channels(efx, ring->rx_pending, txq_entries); }
165,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameLoader::StopAllLoaders() { if (frame_->GetDocument()->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; if (in_stop_all_loaders_) return; in_stop_all_loaders_ = true; for (Frame* child = frame_->Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->Loader().StopAllLoaders(); } frame_->GetDocument()->CancelParsing(); if (document_loader_) document_loader_->Fetcher()->StopFetching(); if (!protect_provisional_loader_) DetachDocumentLoader(provisional_document_loader_); frame_->GetNavigationScheduler().Cancel(); if (document_loader_ && !document_loader_->SentDidFinishLoad()) { document_loader_->LoadFailed( ResourceError::CancelledError(document_loader_->Url())); } in_stop_all_loaders_ = false; TakeObjectSnapshot(); } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <[email protected]> Commit-Queue: Nate Chapin <[email protected]> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362
void FrameLoader::StopAllLoaders() { if (frame_->GetDocument()->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; if (in_stop_all_loaders_) return; AutoReset<bool> in_stop_all_loaders(&in_stop_all_loaders_, true); for (Frame* child = frame_->Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->Loader().StopAllLoaders(); } frame_->GetDocument()->CancelParsing(); if (document_loader_) document_loader_->StopLoading(); if (!protect_provisional_loader_) DetachDocumentLoader(provisional_document_loader_); frame_->GetNavigationScheduler().Cancel(); DidFinishNavigation(); TakeObjectSnapshot(); }
171,852
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: standard_info_part1(standard_display *dp, png_structp pp, png_infop pi) { if (png_get_bit_depth(pp, pi) != dp->bit_depth) png_error(pp, "validate: bit depth changed"); if (png_get_color_type(pp, pi) != dp->colour_type) png_error(pp, "validate: color type changed"); if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE) png_error(pp, "validate: filter type changed"); if (png_get_interlace_type(pp, pi) != dp->interlace_type) png_error(pp, "validate: interlacing changed"); if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE) png_error(pp, "validate: compression type changed"); dp->w = png_get_image_width(pp, pi); if (dp->w != standard_width(pp, dp->id)) png_error(pp, "validate: image width changed"); dp->h = png_get_image_height(pp, pi); if (dp->h != standard_height(pp, dp->id)) png_error(pp, "validate: image height changed"); /* Record (but don't check at present) the input sBIT according to the colour * type information. */ { png_color_8p sBIT = 0; if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT) { int sBIT_invalid = 0; if (sBIT == 0) png_error(pp, "validate: unexpected png_get_sBIT result"); if (dp->colour_type & PNG_COLOR_MASK_COLOR) { if (sBIT->red == 0 || sBIT->red > dp->bit_depth) sBIT_invalid = 1; else dp->red_sBIT = sBIT->red; if (sBIT->green == 0 || sBIT->green > dp->bit_depth) sBIT_invalid = 1; else dp->green_sBIT = sBIT->green; if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth) sBIT_invalid = 1; else dp->blue_sBIT = sBIT->blue; } else /* !COLOR */ { if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth) sBIT_invalid = 1; else dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray; } /* All 8 bits in tRNS for a palette image are significant - see the * spec. */ if (dp->colour_type & PNG_COLOR_MASK_ALPHA) { if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth) sBIT_invalid = 1; else dp->alpha_sBIT = sBIT->alpha; } if (sBIT_invalid) png_error(pp, "validate: sBIT value out of range"); } } /* Important: this is validating the value *before* any transforms have been * put in place. It doesn't matter for the standard tests, where there are * no transforms, but it does for other tests where rowbytes may change after * png_read_update_info. */ if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id)) png_error(pp, "validate: row size changed"); /* Validate the colour type 3 palette (this can be present on other color * types.) */ standard_palette_validate(dp, pp, pi); /* In any case always check for a tranparent color (notice that the * colour type 3 case must not give a successful return on the get_tRNS call * with these arguments!) */ { png_color_16p trans_color = 0; if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS) { if (trans_color == 0) png_error(pp, "validate: unexpected png_get_tRNS (color) result"); switch (dp->colour_type) { case 0: dp->transparent.red = dp->transparent.green = dp->transparent.blue = trans_color->gray; dp->is_transparent = 1; break; case 2: dp->transparent.red = trans_color->red; dp->transparent.green = trans_color->green; dp->transparent.blue = trans_color->blue; dp->is_transparent = 1; break; case 3: /* Not expected because it should result in the array case * above. */ png_error(pp, "validate: unexpected png_get_tRNS result"); break; default: png_error(pp, "validate: invalid tRNS chunk with alpha image"); } } } /* Read the number of passes - expected to match the value used when * creating the image (interlaced or not). This has the side effect of * turning on interlace handling (if do_interlace is not set.) */ dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type); if (!dp->do_interlace && dp->npasses != png_set_interlace_handling(pp)) png_error(pp, "validate: file changed interlace type"); /* Caller calls png_read_update_info or png_start_read_image now, then calls * part2. */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
standard_info_part1(standard_display *dp, png_structp pp, png_infop pi) { if (png_get_bit_depth(pp, pi) != dp->bit_depth) png_error(pp, "validate: bit depth changed"); if (png_get_color_type(pp, pi) != dp->colour_type) png_error(pp, "validate: color type changed"); if (png_get_filter_type(pp, pi) != PNG_FILTER_TYPE_BASE) png_error(pp, "validate: filter type changed"); if (png_get_interlace_type(pp, pi) != dp->interlace_type) png_error(pp, "validate: interlacing changed"); if (png_get_compression_type(pp, pi) != PNG_COMPRESSION_TYPE_BASE) png_error(pp, "validate: compression type changed"); dp->w = png_get_image_width(pp, pi); if (dp->w != standard_width(pp, dp->id)) png_error(pp, "validate: image width changed"); dp->h = png_get_image_height(pp, pi); if (dp->h != standard_height(pp, dp->id)) png_error(pp, "validate: image height changed"); /* Record (but don't check at present) the input sBIT according to the colour * type information. */ { png_color_8p sBIT = 0; if (png_get_sBIT(pp, pi, &sBIT) & PNG_INFO_sBIT) { int sBIT_invalid = 0; if (sBIT == 0) png_error(pp, "validate: unexpected png_get_sBIT result"); if (dp->colour_type & PNG_COLOR_MASK_COLOR) { if (sBIT->red == 0 || sBIT->red > dp->bit_depth) sBIT_invalid = 1; else dp->red_sBIT = sBIT->red; if (sBIT->green == 0 || sBIT->green > dp->bit_depth) sBIT_invalid = 1; else dp->green_sBIT = sBIT->green; if (sBIT->blue == 0 || sBIT->blue > dp->bit_depth) sBIT_invalid = 1; else dp->blue_sBIT = sBIT->blue; } else /* !COLOR */ { if (sBIT->gray == 0 || sBIT->gray > dp->bit_depth) sBIT_invalid = 1; else dp->blue_sBIT = dp->green_sBIT = dp->red_sBIT = sBIT->gray; } /* All 8 bits in tRNS for a palette image are significant - see the * spec. */ if (dp->colour_type & PNG_COLOR_MASK_ALPHA) { if (sBIT->alpha == 0 || sBIT->alpha > dp->bit_depth) sBIT_invalid = 1; else dp->alpha_sBIT = sBIT->alpha; } if (sBIT_invalid) png_error(pp, "validate: sBIT value out of range"); } } /* Important: this is validating the value *before* any transforms have been * put in place. It doesn't matter for the standard tests, where there are * no transforms, but it does for other tests where rowbytes may change after * png_read_update_info. */ if (png_get_rowbytes(pp, pi) != standard_rowsize(pp, dp->id)) png_error(pp, "validate: row size changed"); /* Validate the colour type 3 palette (this can be present on other color * types.) */ standard_palette_validate(dp, pp, pi); /* In any case always check for a tranparent color (notice that the * colour type 3 case must not give a successful return on the get_tRNS call * with these arguments!) */ { png_color_16p trans_color = 0; if (png_get_tRNS(pp, pi, 0, 0, &trans_color) & PNG_INFO_tRNS) { if (trans_color == 0) png_error(pp, "validate: unexpected png_get_tRNS (color) result"); switch (dp->colour_type) { case 0: dp->transparent.red = dp->transparent.green = dp->transparent.blue = trans_color->gray; dp->has_tRNS = 1; break; case 2: dp->transparent.red = trans_color->red; dp->transparent.green = trans_color->green; dp->transparent.blue = trans_color->blue; dp->has_tRNS = 1; break; case 3: /* Not expected because it should result in the array case * above. */ png_error(pp, "validate: unexpected png_get_tRNS result"); break; default: png_error(pp, "validate: invalid tRNS chunk with alpha image"); } } } /* Read the number of passes - expected to match the value used when * creating the image (interlaced or not). This has the side effect of * turning on interlace handling (if do_interlace is not set.) */ dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type); if (!dp->do_interlace) { # ifdef PNG_READ_INTERLACING_SUPPORTED if (dp->npasses != png_set_interlace_handling(pp)) png_error(pp, "validate: file changed interlace type"); # else /* !READ_INTERLACING */ /* This should never happen: the relevant tests (!do_interlace) should * not be run. */ if (dp->npasses > 1) png_error(pp, "validate: no libpng interlace support"); # endif /* !READ_INTERLACING */ } /* Caller calls png_read_update_info or png_start_read_image now, then calls * part2. */ }
173,698
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TabStripGtk::TabDetachedAt(TabContents* contents, int index) { GenerateIdealBounds(); StartRemoveTabAnimation(index, contents->web_contents()); GetTabAt(index)->set_closing(true); } 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 TabStripGtk::TabDetachedAt(TabContents* contents, int index) { void TabStripGtk::TabDetachedAt(WebContents* contents, int index) { GenerateIdealBounds(); StartRemoveTabAnimation(index, contents); GetTabAt(index)->set_closing(true); }
171,516
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; scoped_refptr<base::RefCountedBytes> data_bytes = GetDataFromHandle(params.metafile_data_handle, params.data_size); DCHECK(data_bytes); print_preview_ui->SetPrintPreviewDataForIndex(page_number, std::move(data_bytes)); print_preview_ui->OnDidPreviewPage(page_number, params.preview_request_id); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. [email protected] BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
void PrintPreviewMessageHandler::OnDidPreviewPage( const PrintHostMsg_DidPreviewPage_Params& params) { int page_number = params.page_number; if (page_number < FIRST_PAGE_INDEX || !params.data_size) return; PrintPreviewUI* print_preview_ui = GetPrintPreviewUI(); if (!print_preview_ui) return; if (IsOopifEnabled() && print_preview_ui->source_is_modifiable()) { auto* client = PrintCompositeClient::FromWebContents(web_contents()); DCHECK(client); // Use utility process to convert skia metafile to pdf. client->DoComposite( params.metafile_data_handle, params.data_size, base::BindOnce(&PrintPreviewMessageHandler::OnCompositePdfPageDone, weak_ptr_factory_.GetWeakPtr(), params.page_number, params.preview_request_id)); } else { NotifyUIPreviewPageReady( page_number, params.preview_request_id, GetDataFromHandle(params.metafile_data_handle, params.data_size)); } }
171,888
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GestureSequence::PinchUpdate(const TouchEvent& event, const GesturePoint& point, Gestures* gestures) { DCHECK(state_ == GS_PINCH); float distance = points_[0].Distance(points_[1]); if (abs(distance - pinch_distance_current_) < kMinimumPinchUpdateDistance) { if (!points_[0].DidScroll(event, kMinimumDistanceForPinchScroll) || !points_[1].DidScroll(event, kMinimumDistanceForPinchScroll)) return false; gfx::Point center = points_[0].last_touch_position().Middle( points_[1].last_touch_position()); AppendScrollGestureUpdate(point, center, gestures); } else { AppendPinchGestureUpdate(points_[0], points_[1], distance / pinch_distance_current_, gestures); pinch_distance_current_ = distance; } return true; } Commit Message: Add setters for the aura gesture recognizer constants. BUG=113227 TEST=none Review URL: http://codereview.chromium.org/9372040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@122586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
bool GestureSequence::PinchUpdate(const TouchEvent& event, const GesturePoint& point, Gestures* gestures) { DCHECK(state_ == GS_PINCH); float distance = points_[0].Distance(points_[1]); if (abs(distance - pinch_distance_current_) < GestureConfiguration::minimum_pinch_update_distance_in_pixels()) { if (!points_[0].DidScroll(event, GestureConfiguration::minimum_distance_for_pinch_scroll_in_pixels()) || !points_[1].DidScroll(event, GestureConfiguration::minimum_distance_for_pinch_scroll_in_pixels())) return false; gfx::Point center = points_[0].last_touch_position().Middle( points_[1].last_touch_position()); AppendScrollGestureUpdate(point, center, gestures); } else { AppendPinchGestureUpdate(points_[0], points_[1], distance / pinch_distance_current_, gestures); pinch_distance_current_ = distance; } return true; }
171,047
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DestroySkImageOnOriginalThread( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper, std::unique_ptr<gpu::SyncToken> sync_token) { if (context_provider_wrapper && image->isValid( context_provider_wrapper->ContextProvider()->GetGrContext())) { if (sync_token->HasData()) { context_provider_wrapper->ContextProvider() ->ContextGL() ->WaitSyncTokenCHROMIUM(sync_token->GetData()); } image->getTexture()->textureParamsModified(); } } 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 <[email protected]> Reviewed-by: Jeremy Roman <[email protected]> Commit-Queue: Fernando Serboncini <[email protected]> Cr-Commit-Position: refs/heads/master@{#604427} CWE ID: CWE-119
void DestroySkImageOnOriginalThread( sk_sp<SkImage> image, base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper, std::unique_ptr<gpu::SyncToken> sync_token) { if (context_provider_wrapper && image->isValid( context_provider_wrapper->ContextProvider()->GetGrContext())) { if (sync_token->HasData()) { context_provider_wrapper->ContextProvider() ->ContextGL() ->WaitSyncTokenCHROMIUM(sync_token->GetData()); } image->getTexture()->textureParamsModified(); } image.reset(); }
172,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry, const u8 *obj, size_t objlen, int depth) { void *parm = entry->parm; int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj, size_t nobjlen, int ndepth); size_t *len = (size_t *) entry->arg; int r = 0; callback_func = parm; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n", depth, depth, "", entry->name, sc_dump_hex(obj, objlen > 16 ? 16 : objlen), objlen > 16 ? "..." : ""); switch (entry->type) { case SC_ASN1_STRUCT: if (parm != NULL) r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj, objlen, NULL, NULL, 0, depth + 1); break; case SC_ASN1_NULL: break; case SC_ASN1_BOOLEAN: if (parm != NULL) { if (objlen != 1) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n", objlen); r = SC_ERROR_INVALID_ASN1_OBJECT; } else *((int *) parm) = obj[0] ? 1 : 0; } break; case SC_ASN1_INTEGER: case SC_ASN1_ENUMERATED: if (parm != NULL) { r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm); sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "", entry->name, *((int *) entry->parm)); } break; case SC_ASN1_BIT_STRING_NI: case SC_ASN1_BIT_STRING: if (parm != NULL) { int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0; assert(len != NULL); if (objlen < 1) { r = SC_ERROR_INVALID_ASN1_OBJECT; break; } if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen-1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen-1; parm = *buf; } r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert); if (r >= 0) { *len = r; r = 0; } } break; case SC_ASN1_BIT_FIELD: if (parm != NULL) r = decode_bit_field(obj, objlen, (u8 *) parm, *len); break; case SC_ASN1_OCTET_STRING: if (parm != NULL) { size_t c; assert(len != NULL); /* Strip off padding zero */ if ((entry->flags & SC_ASN1_UNSIGNED) && obj[0] == 0x00 && objlen > 1) { objlen--; obj++; } /* Allocate buffer if needed */ if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_GENERALIZEDTIME: if (parm != NULL) { size_t c; assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_OBJECT: if (parm != NULL) r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm); break; case SC_ASN1_PRINTABLESTRING: case SC_ASN1_UTF8STRING: if (parm != NULL) { assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen+1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen+1; parm = *buf; } r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len); if (entry->flags & SC_ASN1_ALLOC) { *len -= 1; } } break; case SC_ASN1_PATH: if (entry->parm != NULL) r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth); break; case SC_ASN1_PKCS15_ID: if (entry->parm != NULL) { struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm; size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen; memcpy(id->value, obj, c); id->len = c; } break; case SC_ASN1_PKCS15_OBJECT: if (entry->parm != NULL) r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth); break; case SC_ASN1_ALGORITHM_ID: if (entry->parm != NULL) r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth); break; case SC_ASN1_SE_INFO: if (entry->parm != NULL) r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth); break; case SC_ASN1_CALLBACK: if (entry->parm != NULL) r = callback_func(ctx, entry->arg, obj, objlen, depth); break; default: sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type); return SC_ERROR_INVALID_ASN1_OBJECT; } if (r) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name, sc_strerror(r)); return r; } entry->flags |= SC_ASN1_PRESENT; return 0; } Commit Message: Fixed out of bounds access in ASN.1 Octet string Credit to OSS-Fuzz CWE ID: CWE-119
static int asn1_decode_entry(sc_context_t *ctx,struct sc_asn1_entry *entry, const u8 *obj, size_t objlen, int depth) { void *parm = entry->parm; int (*callback_func)(sc_context_t *nctx, void *arg, const u8 *nobj, size_t nobjlen, int ndepth); size_t *len = (size_t *) entry->arg; int r = 0; callback_func = parm; sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s', raw data:%s%s\n", depth, depth, "", entry->name, sc_dump_hex(obj, objlen > 16 ? 16 : objlen), objlen > 16 ? "..." : ""); switch (entry->type) { case SC_ASN1_STRUCT: if (parm != NULL) r = asn1_decode(ctx, (struct sc_asn1_entry *) parm, obj, objlen, NULL, NULL, 0, depth + 1); break; case SC_ASN1_NULL: break; case SC_ASN1_BOOLEAN: if (parm != NULL) { if (objlen != 1) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 object length: %"SC_FORMAT_LEN_SIZE_T"u\n", objlen); r = SC_ERROR_INVALID_ASN1_OBJECT; } else *((int *) parm) = obj[0] ? 1 : 0; } break; case SC_ASN1_INTEGER: case SC_ASN1_ENUMERATED: if (parm != NULL) { r = sc_asn1_decode_integer(obj, objlen, (int *) entry->parm); sc_debug(ctx, SC_LOG_DEBUG_ASN1, "%*.*sdecoding '%s' returned %d\n", depth, depth, "", entry->name, *((int *) entry->parm)); } break; case SC_ASN1_BIT_STRING_NI: case SC_ASN1_BIT_STRING: if (parm != NULL) { int invert = entry->type == SC_ASN1_BIT_STRING ? 1 : 0; assert(len != NULL); if (objlen < 1) { r = SC_ERROR_INVALID_ASN1_OBJECT; break; } if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen-1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen-1; parm = *buf; } r = decode_bit_string(obj, objlen, (u8 *) parm, *len, invert); if (r >= 0) { *len = r; r = 0; } } break; case SC_ASN1_BIT_FIELD: if (parm != NULL) r = decode_bit_field(obj, objlen, (u8 *) parm, *len); break; case SC_ASN1_OCTET_STRING: if (parm != NULL) { size_t c; assert(len != NULL); /* Strip off padding zero */ if ((entry->flags & SC_ASN1_UNSIGNED) && objlen > 1 && obj[0] == 0x00) { objlen--; obj++; } /* Allocate buffer if needed */ if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_GENERALIZEDTIME: if (parm != NULL) { size_t c; assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } c = *len = objlen; parm = *buf; } else c = objlen > *len ? *len : objlen; memcpy(parm, obj, c); *len = c; } break; case SC_ASN1_OBJECT: if (parm != NULL) r = sc_asn1_decode_object_id(obj, objlen, (struct sc_object_id *) parm); break; case SC_ASN1_PRINTABLESTRING: case SC_ASN1_UTF8STRING: if (parm != NULL) { assert(len != NULL); if (entry->flags & SC_ASN1_ALLOC) { u8 **buf = (u8 **) parm; *buf = malloc(objlen+1); if (*buf == NULL) { r = SC_ERROR_OUT_OF_MEMORY; break; } *len = objlen+1; parm = *buf; } r = sc_asn1_decode_utf8string(obj, objlen, (u8 *) parm, len); if (entry->flags & SC_ASN1_ALLOC) { *len -= 1; } } break; case SC_ASN1_PATH: if (entry->parm != NULL) r = asn1_decode_path(ctx, obj, objlen, (sc_path_t *) parm, depth); break; case SC_ASN1_PKCS15_ID: if (entry->parm != NULL) { struct sc_pkcs15_id *id = (struct sc_pkcs15_id *) parm; size_t c = objlen > sizeof(id->value) ? sizeof(id->value) : objlen; memcpy(id->value, obj, c); id->len = c; } break; case SC_ASN1_PKCS15_OBJECT: if (entry->parm != NULL) r = asn1_decode_p15_object(ctx, obj, objlen, (struct sc_asn1_pkcs15_object *) parm, depth); break; case SC_ASN1_ALGORITHM_ID: if (entry->parm != NULL) r = sc_asn1_decode_algorithm_id(ctx, obj, objlen, (struct sc_algorithm_id *) parm, depth); break; case SC_ASN1_SE_INFO: if (entry->parm != NULL) r = asn1_decode_se_info(ctx, obj, objlen, (sc_pkcs15_sec_env_info_t ***)entry->parm, len, depth); break; case SC_ASN1_CALLBACK: if (entry->parm != NULL) r = callback_func(ctx, entry->arg, obj, objlen, depth); break; default: sc_debug(ctx, SC_LOG_DEBUG_ASN1, "invalid ASN.1 type: %d\n", entry->type); return SC_ERROR_INVALID_ASN1_OBJECT; } if (r) { sc_debug(ctx, SC_LOG_DEBUG_ASN1, "decoding of ASN.1 object '%s' failed: %s\n", entry->name, sc_strerror(r)); return r; } entry->flags |= SC_ASN1_PRESENT; return 0; }
169,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) { unsigned short type, size, len; /* If resumed session or no custom extensions nothing to do */ if (s->hit || s->cert->srv_ext.meths_count == 0) return 1; if (data >= limit - 2) return 1; n2s(data, len); if (data > limit - len) return 1; while (data <= limit - 4) { n2s(data, type); n2s(data, size); if (data + size > limit) return 1; if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) return 0; data += size; } return 1; } Commit Message: CWE ID: CWE-190
static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) { unsigned short type, size, len; /* If resumed session or no custom extensions nothing to do */ if (s->hit || s->cert->srv_ext.meths_count == 0) return 1; if (limit - data <= 2) return 1; n2s(data, len); if (limit - data < len) return 1; while (limit - data >= 4) { n2s(data, type); n2s(data, size); if (limit - data < size) return 1; if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) return 0; data += size; } return 1; }
165,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ReportPreconnectAccuracy( const PreconnectStats& stats, const std::map<GURL, OriginRequestSummary>& requests) { if (stats.requests_stats.empty()) return; int preresolve_hits_count = 0; int preresolve_misses_count = 0; int preconnect_hits_count = 0; int preconnect_misses_count = 0; for (const auto& request_stats : stats.requests_stats) { bool hit = requests.find(request_stats.origin) != requests.end(); bool preconnect = request_stats.was_preconnected; preresolve_hits_count += hit; preresolve_misses_count += !hit; preconnect_hits_count += preconnect && hit; preconnect_misses_count += preconnect && !hit; } int total_preresolves = preresolve_hits_count + preresolve_misses_count; int total_preconnects = preconnect_hits_count + preconnect_misses_count; DCHECK_EQ(static_cast<int>(stats.requests_stats.size()), preresolve_hits_count + preresolve_misses_count); DCHECK_GT(total_preresolves, 0); size_t preresolve_hits_percentage = (100 * preresolve_hits_count) / total_preresolves; if (total_preconnects > 0) { size_t preconnect_hits_percentage = (100 * preconnect_hits_count) / total_preconnects; UMA_HISTOGRAM_PERCENTAGE( internal::kLoadingPredictorPreconnectHitsPercentage, preconnect_hits_percentage); } UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage, preresolve_hits_percentage); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount, total_preresolves); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount, total_preconnects); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void ReportPreconnectAccuracy( const PreconnectStats& stats, const std::map<url::Origin, OriginRequestSummary>& requests) { if (stats.requests_stats.empty()) return; int preresolve_hits_count = 0; int preresolve_misses_count = 0; int preconnect_hits_count = 0; int preconnect_misses_count = 0; for (const auto& request_stats : stats.requests_stats) { bool hit = requests.find(request_stats.origin) != requests.end(); bool preconnect = request_stats.was_preconnected; preresolve_hits_count += hit; preresolve_misses_count += !hit; preconnect_hits_count += preconnect && hit; preconnect_misses_count += preconnect && !hit; } int total_preresolves = preresolve_hits_count + preresolve_misses_count; int total_preconnects = preconnect_hits_count + preconnect_misses_count; DCHECK_EQ(static_cast<int>(stats.requests_stats.size()), preresolve_hits_count + preresolve_misses_count); DCHECK_GT(total_preresolves, 0); size_t preresolve_hits_percentage = (100 * preresolve_hits_count) / total_preresolves; if (total_preconnects > 0) { size_t preconnect_hits_percentage = (100 * preconnect_hits_count) / total_preconnects; UMA_HISTOGRAM_PERCENTAGE( internal::kLoadingPredictorPreconnectHitsPercentage, preconnect_hits_percentage); } UMA_HISTOGRAM_PERCENTAGE(internal::kLoadingPredictorPreresolveHitsPercentage, preresolve_hits_percentage); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreresolveCount, total_preresolves); UMA_HISTOGRAM_COUNTS_100(internal::kLoadingPredictorPreconnectCount, total_preconnects); }
172,372
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cipso_v4_sock_setattr(struct sock *sk, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr) { int ret_val = -EPERM; unsigned char *buf = NULL; u32 buf_len; u32 opt_len; struct ip_options *opt = NULL; struct inet_sock *sk_inet; struct inet_connection_sock *sk_conn; /* In the case of sock_create_lite(), the sock->sk field is not * defined yet but it is not a problem as the only users of these * "lite" PF_INET sockets are functions which do an accept() call * afterwards so we will label the socket as part of the accept(). */ if (sk == NULL) return 0; /* We allocate the maximum CIPSO option size here so we are probably * being a little wasteful, but it makes our life _much_ easier later * on and after all we are only talking about 40 bytes. */ buf_len = CIPSO_V4_OPT_LEN_MAX; buf = kmalloc(buf_len, GFP_ATOMIC); if (buf == NULL) { ret_val = -ENOMEM; goto socket_setattr_failure; } ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr); if (ret_val < 0) goto socket_setattr_failure; buf_len = ret_val; /* We can't use ip_options_get() directly because it makes a call to * ip_options_get_alloc() which allocates memory with GFP_KERNEL and * we won't always have CAP_NET_RAW even though we _always_ want to * set the IPOPT_CIPSO option. */ opt_len = (buf_len + 3) & ~3; opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC); if (opt == NULL) { ret_val = -ENOMEM; goto socket_setattr_failure; } memcpy(opt->__data, buf, buf_len); opt->optlen = opt_len; opt->cipso = sizeof(struct iphdr); kfree(buf); buf = NULL; sk_inet = inet_sk(sk); if (sk_inet->is_icsk) { sk_conn = inet_csk(sk); if (sk_inet->opt) sk_conn->icsk_ext_hdr_len -= sk_inet->opt->optlen; sk_conn->icsk_ext_hdr_len += opt->optlen; sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie); } opt = xchg(&sk_inet->opt, opt); kfree(opt); return 0; socket_setattr_failure: kfree(buf); kfree(opt); return ret_val; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
int cipso_v4_sock_setattr(struct sock *sk, const struct cipso_v4_doi *doi_def, const struct netlbl_lsm_secattr *secattr) { int ret_val = -EPERM; unsigned char *buf = NULL; u32 buf_len; u32 opt_len; struct ip_options_rcu *old, *opt = NULL; struct inet_sock *sk_inet; struct inet_connection_sock *sk_conn; /* In the case of sock_create_lite(), the sock->sk field is not * defined yet but it is not a problem as the only users of these * "lite" PF_INET sockets are functions which do an accept() call * afterwards so we will label the socket as part of the accept(). */ if (sk == NULL) return 0; /* We allocate the maximum CIPSO option size here so we are probably * being a little wasteful, but it makes our life _much_ easier later * on and after all we are only talking about 40 bytes. */ buf_len = CIPSO_V4_OPT_LEN_MAX; buf = kmalloc(buf_len, GFP_ATOMIC); if (buf == NULL) { ret_val = -ENOMEM; goto socket_setattr_failure; } ret_val = cipso_v4_genopt(buf, buf_len, doi_def, secattr); if (ret_val < 0) goto socket_setattr_failure; buf_len = ret_val; /* We can't use ip_options_get() directly because it makes a call to * ip_options_get_alloc() which allocates memory with GFP_KERNEL and * we won't always have CAP_NET_RAW even though we _always_ want to * set the IPOPT_CIPSO option. */ opt_len = (buf_len + 3) & ~3; opt = kzalloc(sizeof(*opt) + opt_len, GFP_ATOMIC); if (opt == NULL) { ret_val = -ENOMEM; goto socket_setattr_failure; } memcpy(opt->opt.__data, buf, buf_len); opt->opt.optlen = opt_len; opt->opt.cipso = sizeof(struct iphdr); kfree(buf); buf = NULL; sk_inet = inet_sk(sk); old = rcu_dereference_protected(sk_inet->inet_opt, sock_owned_by_user(sk)); if (sk_inet->is_icsk) { sk_conn = inet_csk(sk); if (old) sk_conn->icsk_ext_hdr_len -= old->opt.optlen; sk_conn->icsk_ext_hdr_len += opt->opt.optlen; sk_conn->icsk_sync_mss(sk, sk_conn->icsk_pmtu_cookie); } rcu_assign_pointer(sk_inet->inet_opt, opt); if (old) call_rcu(&old->rcu, opt_kfree_rcu); return 0; socket_setattr_failure: kfree(buf); kfree(opt); return ret_val; }
165,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SyncTest::TriggerSetSyncTabs() { ASSERT_TRUE(ServerSupportsErrorTriggering()); std::string path = "chromiumsync/synctabs"; ui_test_utils::NavigateToURL(browser(), sync_server_.GetURL(path)); ASSERT_EQ("Sync Tabs", UTF16ToASCII(browser()->GetSelectedWebContents()->GetTitle())); } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncTest::TriggerSetSyncTabs() {
170,790
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int http_read_header(URLContext *h, int *new_location) { HTTPContext *s = h->priv_data; char line[MAX_URL_SIZE]; int err = 0; s->chunksize = -1; for (;;) { if ((err = http_get_line(s, line, sizeof(line))) < 0) return err; av_log(h, AV_LOG_TRACE, "header='%s'\n", line); err = process_line(h, line, s->line_count, new_location); if (err < 0) return err; if (err == 0) break; s->line_count++; } if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000) h->is_streamed = 1; /* we can in fact _not_ seek */ cookie_string(s->cookie_dict, &s->cookies); av_dict_free(&s->cookie_dict); return err; } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119
static int http_read_header(URLContext *h, int *new_location) { HTTPContext *s = h->priv_data; char line[MAX_URL_SIZE]; int err = 0; s->chunksize = UINT64_MAX; for (;;) { if ((err = http_get_line(s, line, sizeof(line))) < 0) return err; av_log(h, AV_LOG_TRACE, "header='%s'\n", line); err = process_line(h, line, s->line_count, new_location); if (err < 0) return err; if (err == 0) break; s->line_count++; } if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000) h->is_streamed = 1; /* we can in fact _not_ seek */ cookie_string(s->cookie_dict, &s->cookies); av_dict_free(&s->cookie_dict); return err; }
168,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentWriter::setDecoder(TextResourceDecoder* decoder) { m_decoder = decoder; } Commit Message: Remove DocumentWriter::setDecoder as a grep of WebKit shows no callers https://bugs.webkit.org/show_bug.cgi?id=67803 Reviewed by Adam Barth. Smells like dead code. * loader/DocumentWriter.cpp: * loader/DocumentWriter.h: git-svn-id: svn://svn.chromium.org/blink/trunk@94800 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void DocumentWriter::setDecoder(TextResourceDecoder* decoder)
170,318
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CSSStyleSheet::CanAccessRules() const { if (enable_rule_access_for_inspector_) return true; if (is_inline_stylesheet_) return true; KURL base_url = contents_->BaseURL(); if (base_url.IsEmpty()) return true; Document* document = OwnerDocument(); if (!document) return true; if (document->GetSecurityOrigin()->CanReadContent(base_url)) return true; if (allow_rule_access_from_origin_ && document->GetSecurityOrigin()->CanAccess( allow_rule_access_from_origin_.get())) { return true; } return false; } Commit Message: Disallow access to opaque CSS responses. Bug: 848786 Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec Reviewed-on: https://chromium-review.googlesource.com/1088335 Reviewed-by: Kouhei Ueno <[email protected]> Commit-Queue: Matt Falkenhagen <[email protected]> Cr-Commit-Position: refs/heads/master@{#565537} CWE ID: CWE-200
bool CSSStyleSheet::CanAccessRules() const { if (enable_rule_access_for_inspector_) return true; // Opaque responses should never be accessible, mod DevTools. See comments for // IsOpaqueResponseFromServiceWorker(). if (contents_->IsOpaqueResponseFromServiceWorker()) return false; if (is_inline_stylesheet_) return true; KURL base_url = contents_->BaseURL(); if (base_url.IsEmpty()) return true; Document* document = OwnerDocument(); if (!document) return true; if (document->GetSecurityOrigin()->CanReadContent(base_url)) return true; if (allow_rule_access_from_origin_ && document->GetSecurityOrigin()->CanAccess( allow_rule_access_from_origin_.get())) { return true; } return false; }
173,153
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long mkvparser::UnserializeUInt( IMkvReader* pReader, long long pos, long long size) { assert(pReader); assert(pos >= 0); if ((size <= 0) || (size > 8)) return E_FILE_FORMAT_INVALID; long long result = 0; for (long long i = 0; i < size; ++i) { unsigned char b; const long status = pReader->Read(pos, 1, &b); if (status < 0) return status; result <<= 8; result |= b; ++pos; } return result; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long mkvparser::UnserializeUInt( if ((size_ != 4) && (size_ != 8)) return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); unsigned char buf[8]; const int status = pReader->Read(pos, size, buf); if (status < 0) // error return status; if (size == 4) { union { float f; unsigned long ff; }; ff = 0; for (int i = 0;;) { ff |= buf[i]; if (++i >= 4) break; ff <<= 8; } result = f; } else { assert(size == 8); union { double d; unsigned long long dd; }; dd = 0; for (int i = 0;;) { dd |= buf[i]; if (++i >= 8) break; dd <<= 8; } result = d; } return 0; }
174,450
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); } Commit Message: http://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=26861 CWE ID: CWE-399
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) w * h * pixel_size; if (SeekBlob(image,offset,SEEK_CUR) < 0) break; w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
170,122
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserProcessMainImpl::Shutdown() { if (state_ != STATE_STARTED) { CHECK_NE(state_, STATE_SHUTTING_DOWN); return; MessagePump::Get()->Stop(); WebContentsUnloader::GetInstance()->Shutdown(); if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } browser_main_runner_->Shutdown(); browser_main_runner_.reset(); if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } browser_main_runner_->Shutdown(); browser_main_runner_.reset(); exit_manager_.reset(); main_delegate_.reset(); platform_delegate_.reset(); state_ = STATE_SHUTDOWN; } BrowserProcessMain::BrowserProcessMain() {} BrowserProcessMain::~BrowserProcessMain() {} ProcessModel BrowserProcessMain::GetProcessModelOverrideFromEnv() { static bool g_initialized = false; static ProcessModel g_process_model = PROCESS_MODEL_UNDEFINED; if (g_initialized) { return g_process_model; } g_initialized = true; std::unique_ptr<base::Environment> env = base::Environment::Create(); if (IsEnvironmentOptionEnabled("SINGLE_PROCESS", env.get())) { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else { std::string model = GetEnvironmentOption("PROCESS_MODEL", env.get()); if (!model.empty()) { if (model == "multi-process") { g_process_model = PROCESS_MODEL_MULTI_PROCESS; } else if (model == "single-process") { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else if (model == "process-per-site-instance") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE_INSTANCE; } else if (model == "process-per-view") { g_process_model = PROCESS_MODEL_PROCESS_PER_VIEW; } else if (model == "process-per-site") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE; } else if (model == "site-per-process") { g_process_model = PROCESS_MODEL_SITE_PER_PROCESS; } else { LOG(WARNING) << "Invalid process mode: " << model; } } } return g_process_model; } BrowserProcessMain* BrowserProcessMain::GetInstance() { static BrowserProcessMainImpl g_instance; return &g_instance; } } // namespace oxide Commit Message: CWE ID: CWE-20
void BrowserProcessMainImpl::Shutdown() { if (state_ != STATE_STARTED) { CHECK_NE(state_, STATE_SHUTTING_DOWN); return; MessagePump::Get()->Stop(); browser_main_runner_->Shutdown(); browser_main_runner_.reset(); if (process_model_ != PROCESS_MODEL_SINGLE_PROCESS) { BrowserContext::AssertNoContextsExist(); } browser_main_runner_->Shutdown(); browser_main_runner_.reset(); exit_manager_.reset(); main_delegate_.reset(); platform_delegate_.reset(); state_ = STATE_SHUTDOWN; } BrowserProcessMain::BrowserProcessMain() {} BrowserProcessMain::~BrowserProcessMain() {} ProcessModel BrowserProcessMain::GetProcessModelOverrideFromEnv() { static bool g_initialized = false; static ProcessModel g_process_model = PROCESS_MODEL_UNDEFINED; if (g_initialized) { return g_process_model; } g_initialized = true; std::unique_ptr<base::Environment> env = base::Environment::Create(); if (IsEnvironmentOptionEnabled("SINGLE_PROCESS", env.get())) { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else { std::string model = GetEnvironmentOption("PROCESS_MODEL", env.get()); if (!model.empty()) { if (model == "multi-process") { g_process_model = PROCESS_MODEL_MULTI_PROCESS; } else if (model == "single-process") { g_process_model = PROCESS_MODEL_SINGLE_PROCESS; } else if (model == "process-per-site-instance") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE_INSTANCE; } else if (model == "process-per-view") { g_process_model = PROCESS_MODEL_PROCESS_PER_VIEW; } else if (model == "process-per-site") { g_process_model = PROCESS_MODEL_PROCESS_PER_SITE; } else if (model == "site-per-process") { g_process_model = PROCESS_MODEL_SITE_PER_PROCESS; } else { LOG(WARNING) << "Invalid process mode: " << model; } } } return g_process_model; } BrowserProcessMain* BrowserProcessMain::GetInstance() { static BrowserProcessMainImpl g_instance; return &g_instance; } } // namespace oxide
165,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len) { const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp; u_int group, nsrcs, ngroups; u_int i, j; /* Minimum len is 8 */ if (len < 8) { ND_PRINT((ndo," [invalid len %d]", len)); return; } ND_TCHECK(icp->icmp6_data16[1]); ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]); ND_PRINT((ndo,", %d group record(s)", ngroups)); if (ndo->ndo_vflag > 0) { /* Print the group records */ group = 8; for (i = 0; i < ngroups; i++) { /* type(1) + auxlen(1) + numsrc(2) + grp(16) */ if (len < group + 20) { ND_PRINT((ndo," [invalid number of groups]")); return; } ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr)); ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4]))); ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]", bp[group]))); nsrcs = (bp[group + 2] << 8) + bp[group + 3]; /* Check the number of sources and print them */ if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) { ND_PRINT((ndo," [invalid number of sources %d]", nsrcs)); return; } if (ndo->ndo_vflag == 1) ND_PRINT((ndo,", %d source(s)", nsrcs)); else { /* Print the sources */ ND_PRINT((ndo," {")); for (j = 0; j < nsrcs; j++) { ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)], sizeof(struct in6_addr)); ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)]))); } ND_PRINT((ndo," }")); } /* Next group record */ group += 20 + nsrcs * sizeof(struct in6_addr); ND_PRINT((ndo,"]")); } } return; trunc: ND_PRINT((ndo,"[|icmp6]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len) { const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp; u_int group, nsrcs, ngroups; u_int i, j; /* Minimum len is 8 */ if (len < 8) { ND_PRINT((ndo," [invalid len %d]", len)); return; } ND_TCHECK(icp->icmp6_data16[1]); ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]); ND_PRINT((ndo,", %d group record(s)", ngroups)); if (ndo->ndo_vflag > 0) { /* Print the group records */ group = 8; for (i = 0; i < ngroups; i++) { /* type(1) + auxlen(1) + numsrc(2) + grp(16) */ if (len < group + 20) { ND_PRINT((ndo," [invalid number of groups]")); return; } ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr)); ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4]))); ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]", bp[group]))); nsrcs = (bp[group + 2] << 8) + bp[group + 3]; /* Check the number of sources and print them */ if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) { ND_PRINT((ndo," [invalid number of sources %d]", nsrcs)); return; } if (ndo->ndo_vflag == 1) ND_PRINT((ndo,", %d source(s)", nsrcs)); else { /* Print the sources */ ND_PRINT((ndo," {")); for (j = 0; j < nsrcs; j++) { ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)], sizeof(struct in6_addr)); ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)]))); } ND_PRINT((ndo," }")); } /* Next group record */ group += 20 + nsrcs * sizeof(struct in6_addr); ND_PRINT((ndo,"]")); } } return; trunc: ND_PRINT((ndo, "%s", mldv2_tstr)); return; }
169,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[]) { int i; int port_tmp; for(i=1; i<argc; i++){ if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config-file")){ if(i<argc-1){ db->config_file = argv[i+1]; if(config__read(db, config, false)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open configuration file."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -c argument given, but no config file specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon")){ config->daemon = true; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){ print_usage(); return MOSQ_ERR_INVAL; }else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i<argc-1){ port_tmp = atoi(argv[i+1]); if(port_tmp<1 || port_tmp>65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp); return MOSQ_ERR_INVAL; }else{ if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } config->default_listener.port = port_tmp; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -p argument given, but no port specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ db->verbose = true; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); print_usage(); return MOSQ_ERR_INVAL; } } if(config->listener_count == 0 #ifdef WITH_TLS || config->default_listener.cafile || config->default_listener.capath || config->default_listener.certfile || config->default_listener.keyfile || config->default_listener.ciphers || config->default_listener.psk_hint || config->default_listener.require_certificate || config->default_listener.crlfile || config->default_listener.use_identity_as_username || config->default_listener.use_subject_as_username #endif || config->default_listener.use_username_as_clientid || config->default_listener.host || config->default_listener.port || config->default_listener.max_connections != -1 || config->default_listener.mount_point || config->default_listener.protocol != mp_mqtt || config->default_listener.socket_domain || config->default_listener.security_options.password_file || config->default_listener.security_options.psk_file || config->default_listener.security_options.auth_plugin_config_count || config->default_listener.security_options.allow_anonymous != -1 ){ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } memset(&config->listeners[config->listener_count-1], 0, sizeof(struct mosquitto__listener)); if(config->default_listener.port){ config->listeners[config->listener_count-1].port = config->default_listener.port; }else{ config->listeners[config->listener_count-1].port = 1883; } if(config->default_listener.host){ config->listeners[config->listener_count-1].host = config->default_listener.host; }else{ config->listeners[config->listener_count-1].host = NULL; } if(config->default_listener.mount_point){ config->listeners[config->listener_count-1].mount_point = config->default_listener.mount_point; }else{ config->listeners[config->listener_count-1].mount_point = NULL; } config->listeners[config->listener_count-1].max_connections = config->default_listener.max_connections; config->listeners[config->listener_count-1].protocol = config->default_listener.protocol; config->listeners[config->listener_count-1].socket_domain = config->default_listener.socket_domain; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].socks = NULL; config->listeners[config->listener_count-1].sock_count = 0; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].use_username_as_clientid = config->default_listener.use_username_as_clientid; #ifdef WITH_TLS config->listeners[config->listener_count-1].tls_version = config->default_listener.tls_version; config->listeners[config->listener_count-1].cafile = config->default_listener.cafile; config->listeners[config->listener_count-1].capath = config->default_listener.capath; config->listeners[config->listener_count-1].certfile = config->default_listener.certfile; config->listeners[config->listener_count-1].keyfile = config->default_listener.keyfile; config->listeners[config->listener_count-1].ciphers = config->default_listener.ciphers; config->listeners[config->listener_count-1].psk_hint = config->default_listener.psk_hint; config->listeners[config->listener_count-1].require_certificate = config->default_listener.require_certificate; config->listeners[config->listener_count-1].ssl_ctx = NULL; config->listeners[config->listener_count-1].crlfile = config->default_listener.crlfile; config->listeners[config->listener_count-1].use_identity_as_username = config->default_listener.use_identity_as_username; config->listeners[config->listener_count-1].use_subject_as_username = config->default_listener.use_subject_as_username; #endif config->listeners[config->listener_count-1].security_options.password_file = config->default_listener.security_options.password_file; config->listeners[config->listener_count-1].security_options.psk_file = config->default_listener.security_options.psk_file; config->listeners[config->listener_count-1].security_options.auth_plugin_configs = config->default_listener.security_options.auth_plugin_configs; config->listeners[config->listener_count-1].security_options.auth_plugin_config_count = config->default_listener.security_options.auth_plugin_config_count; config->listeners[config->listener_count-1].security_options.allow_anonymous = config->default_listener.security_options.allow_anonymous; } /* Default to drop to mosquitto user if we are privileged and no user specified. */ if(!config->user){ config->user = "mosquitto"; } if(db->verbose){ config->log_type = INT_MAX; } return config__check(config); } Commit Message: Fix acl_file being ignore for default listener if with per_listener_settings Close #1073. Thanks to Jef Driesen. Bug: https://github.com/eclipse/mosquitto/issues/1073 CWE ID:
int config__parse_args(struct mosquitto_db *db, struct mosquitto__config *config, int argc, char *argv[]) { int i; int port_tmp; for(i=1; i<argc; i++){ if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--config-file")){ if(i<argc-1){ db->config_file = argv[i+1]; if(config__read(db, config, false)){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Unable to open configuration file."); return MOSQ_ERR_INVAL; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -c argument given, but no config file specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--daemon")){ config->daemon = true; }else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")){ print_usage(); return MOSQ_ERR_INVAL; }else if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){ if(i<argc-1){ port_tmp = atoi(argv[i+1]); if(port_tmp<1 || port_tmp>65535){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Invalid port specified (%d).", port_tmp); return MOSQ_ERR_INVAL; }else{ if(config->default_listener.port){ log__printf(NULL, MOSQ_LOG_WARNING, "Warning: Default listener port specified multiple times. Only the latest will be used."); } config->default_listener.port = port_tmp; } }else{ log__printf(NULL, MOSQ_LOG_ERR, "Error: -p argument given, but no port specified."); return MOSQ_ERR_INVAL; } i++; }else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){ db->verbose = true; }else{ fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]); print_usage(); return MOSQ_ERR_INVAL; } } if(config->listener_count == 0 #ifdef WITH_TLS || config->default_listener.cafile || config->default_listener.capath || config->default_listener.certfile || config->default_listener.keyfile || config->default_listener.ciphers || config->default_listener.psk_hint || config->default_listener.require_certificate || config->default_listener.crlfile || config->default_listener.use_identity_as_username || config->default_listener.use_subject_as_username #endif || config->default_listener.use_username_as_clientid || config->default_listener.host || config->default_listener.port || config->default_listener.max_connections != -1 || config->default_listener.mount_point || config->default_listener.protocol != mp_mqtt || config->default_listener.socket_domain || config->default_listener.security_options.password_file || config->default_listener.security_options.psk_file || config->default_listener.security_options.auth_plugin_config_count || config->default_listener.security_options.allow_anonymous != -1 ){ config->listener_count++; config->listeners = mosquitto__realloc(config->listeners, sizeof(struct mosquitto__listener)*config->listener_count); if(!config->listeners){ log__printf(NULL, MOSQ_LOG_ERR, "Error: Out of memory."); return MOSQ_ERR_NOMEM; } memset(&config->listeners[config->listener_count-1], 0, sizeof(struct mosquitto__listener)); if(config->default_listener.port){ config->listeners[config->listener_count-1].port = config->default_listener.port; }else{ config->listeners[config->listener_count-1].port = 1883; } if(config->default_listener.host){ config->listeners[config->listener_count-1].host = config->default_listener.host; }else{ config->listeners[config->listener_count-1].host = NULL; } if(config->default_listener.mount_point){ config->listeners[config->listener_count-1].mount_point = config->default_listener.mount_point; }else{ config->listeners[config->listener_count-1].mount_point = NULL; } config->listeners[config->listener_count-1].max_connections = config->default_listener.max_connections; config->listeners[config->listener_count-1].protocol = config->default_listener.protocol; config->listeners[config->listener_count-1].socket_domain = config->default_listener.socket_domain; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].socks = NULL; config->listeners[config->listener_count-1].sock_count = 0; config->listeners[config->listener_count-1].client_count = 0; config->listeners[config->listener_count-1].use_username_as_clientid = config->default_listener.use_username_as_clientid; #ifdef WITH_TLS config->listeners[config->listener_count-1].tls_version = config->default_listener.tls_version; config->listeners[config->listener_count-1].cafile = config->default_listener.cafile; config->listeners[config->listener_count-1].capath = config->default_listener.capath; config->listeners[config->listener_count-1].certfile = config->default_listener.certfile; config->listeners[config->listener_count-1].keyfile = config->default_listener.keyfile; config->listeners[config->listener_count-1].ciphers = config->default_listener.ciphers; config->listeners[config->listener_count-1].psk_hint = config->default_listener.psk_hint; config->listeners[config->listener_count-1].require_certificate = config->default_listener.require_certificate; config->listeners[config->listener_count-1].ssl_ctx = NULL; config->listeners[config->listener_count-1].crlfile = config->default_listener.crlfile; config->listeners[config->listener_count-1].use_identity_as_username = config->default_listener.use_identity_as_username; config->listeners[config->listener_count-1].use_subject_as_username = config->default_listener.use_subject_as_username; #endif config->listeners[config->listener_count-1].security_options.acl_file = config->default_listener.security_options.acl_file; config->listeners[config->listener_count-1].security_options.password_file = config->default_listener.security_options.password_file; config->listeners[config->listener_count-1].security_options.psk_file = config->default_listener.security_options.psk_file; config->listeners[config->listener_count-1].security_options.auth_plugin_configs = config->default_listener.security_options.auth_plugin_configs; config->listeners[config->listener_count-1].security_options.auth_plugin_config_count = config->default_listener.security_options.auth_plugin_config_count; config->listeners[config->listener_count-1].security_options.allow_anonymous = config->default_listener.security_options.allow_anonymous; } /* Default to drop to mosquitto user if we are privileged and no user specified. */ if(!config->user){ config->user = "mosquitto"; } if(db->verbose){ config->log_type = INT_MAX; } return config__check(config); }
168,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SecurityHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { host_ = frame_host; if (enabled_ && host_) AttachToRenderFrameHost(); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void SecurityHandler::SetRenderer(RenderProcessHost* process_host, void SecurityHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { host_ = frame_host; if (enabled_ && host_) AttachToRenderFrameHost(); }
172,765
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const { ParaNdis_CheckSumVerifyFlat(IpHeader, EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum, __FUNCTION__); } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20
void CNB::DoIPHdrCSO(PVOID IpHeader, ULONG EthPayloadLength) const { ParaNdis_CheckSumVerifyFlat(IpHeader, EthPayloadLength, pcrIpChecksum | pcrFixIPChecksum, FALSE, __FUNCTION__); }
170,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BluetoothOptionsHandler::RequestConfirmation( chromeos::BluetoothDevice* device, int passkey) { } Commit Message: Implement methods for pairing of bluetooth devices. BUG=chromium:100392,chromium:102139 TEST= Review URL: http://codereview.chromium.org/8495018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109094 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void BluetoothOptionsHandler::RequestConfirmation( chromeos::BluetoothDevice* device, int passkey) { DictionaryValue params; params.SetString("pairing", "bluetoothConfirmPasskey"); params.SetInteger("passkey", passkey); SendDeviceNotification(device, &params); }
170,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mkvparser::ParseElementHeader( IMkvReader* pReader, long long& pos, long long stop, long long& id, long long& size) { if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; //consume length of size if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; //success } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long mkvparser::ParseElementHeader( long len; id = ReadUInt(pReader, pos, len); if (id < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume id if ((stop >= 0) && (pos >= stop)) return E_FILE_FORMAT_INVALID; size = ReadUInt(pReader, pos, len); if (size < 0) return E_FILE_FORMAT_INVALID; pos += len; // consume length of size // pos now designates payload if ((stop >= 0) && ((pos + size) > stop)) return E_FILE_FORMAT_INVALID; return 0; // success }
174,424
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jffs2_do_setattr (struct inode *inode, struct iattr *iattr) { struct jffs2_full_dnode *old_metadata, *new_metadata; struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb); struct jffs2_raw_inode *ri; union jffs2_device_node dev; unsigned char *mdata = NULL; int mdatalen = 0; unsigned int ivalid; uint32_t alloclen; int ret; D1(printk(KERN_DEBUG "jffs2_setattr(): ino #%lu\n", inode->i_ino)); ret = inode_change_ok(inode, iattr); if (ret) return ret; /* Special cases - we don't want more than one data node for these types on the medium at any time. So setattr /* Special cases - we don't want more than one data node for these types on the medium at any time. So setattr must read the original data associated with the node (i.e. the device numbers or the target name) and write it out again with the appropriate data attached */ if (S_ISBLK(inode->i_mode) || S_ISCHR(inode->i_mode)) { /* For these, we don't actually need to read the old node */ mdatalen = jffs2_encode_dev(&dev, inode->i_rdev); mdata = (char *)&dev; D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of kdev_t\n", mdatalen)); } else if (S_ISLNK(inode->i_mode)) { down(&f->sem); mdatalen = f->metadata->size; mdata = kmalloc(f->metadata->size, GFP_USER); if (!mdata) { up(&f->sem); return -ENOMEM; } ret = jffs2_read_dnode(c, f, f->metadata, mdata, 0, mdatalen); if (ret) { up(&f->sem); kfree(mdata); return ret; } up(&f->sem); D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of symlink target\n", mdatalen)); } ri = jffs2_alloc_raw_inode(); if (!ri) { if (S_ISLNK(inode->i_mode)) kfree(mdata); return -ENOMEM; } ret = jffs2_reserve_space(c, sizeof(*ri) + mdatalen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE); if (ret) { jffs2_free_raw_inode(ri); if (S_ISLNK(inode->i_mode & S_IFMT)) kfree(mdata); return ret; } down(&f->sem); ivalid = iattr->ia_valid; ri->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); ri->nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE); ri->totlen = cpu_to_je32(sizeof(*ri) + mdatalen); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->ino = cpu_to_je32(inode->i_ino); ri->version = cpu_to_je32(++f->highest_version); ri->uid = cpu_to_je16((ivalid & ATTR_UID)?iattr->ia_uid:inode->i_uid); ri->gid = cpu_to_je16((ivalid & ATTR_GID)?iattr->ia_gid:inode->i_gid); if (ivalid & ATTR_MODE) if (iattr->ia_mode & S_ISGID && !in_group_p(je16_to_cpu(ri->gid)) && !capable(CAP_FSETID)) ri->mode = cpu_to_jemode(iattr->ia_mode & ~S_ISGID); else ri->mode = cpu_to_jemode(iattr->ia_mode); else ri->mode = cpu_to_jemode(inode->i_mode); ri->isize = cpu_to_je32((ivalid & ATTR_SIZE)?iattr->ia_size:inode->i_size); ri->atime = cpu_to_je32(I_SEC((ivalid & ATTR_ATIME)?iattr->ia_atime:inode->i_atime)); ri->mtime = cpu_to_je32(I_SEC((ivalid & ATTR_MTIME)?iattr->ia_mtime:inode->i_mtime)); ri->ctime = cpu_to_je32(I_SEC((ivalid & ATTR_CTIME)?iattr->ia_ctime:inode->i_ctime)); ri->offset = cpu_to_je32(0); ri->csize = ri->dsize = cpu_to_je32(mdatalen); ri->compr = JFFS2_COMPR_NONE; if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { /* It's an extension. Make it a hole node */ ri->compr = JFFS2_COMPR_ZERO; ri->dsize = cpu_to_je32(iattr->ia_size - inode->i_size); ri->offset = cpu_to_je32(inode->i_size); } ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); if (mdatalen) ri->data_crc = cpu_to_je32(crc32(0, mdata, mdatalen)); else ri->data_crc = cpu_to_je32(0); new_metadata = jffs2_write_dnode(c, f, ri, mdata, mdatalen, ALLOC_NORMAL); if (S_ISLNK(inode->i_mode)) kfree(mdata); if (IS_ERR(new_metadata)) { jffs2_complete_reservation(c); jffs2_free_raw_inode(ri); up(&f->sem); return PTR_ERR(new_metadata); } /* It worked. Update the inode */ inode->i_atime = ITIME(je32_to_cpu(ri->atime)); inode->i_ctime = ITIME(je32_to_cpu(ri->ctime)); inode->i_mtime = ITIME(je32_to_cpu(ri->mtime)); inode->i_mode = jemode_to_cpu(ri->mode); inode->i_uid = je16_to_cpu(ri->uid); inode->i_gid = je16_to_cpu(ri->gid); old_metadata = f->metadata; if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) jffs2_truncate_fragtree (c, &f->fragtree, iattr->ia_size); if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { jffs2_add_full_dnode_to_inode(c, f, new_metadata); inode->i_size = iattr->ia_size; f->metadata = NULL; } else { f->metadata = new_metadata; } if (old_metadata) { jffs2_mark_node_obsolete(c, old_metadata->raw); jffs2_free_full_dnode(old_metadata); } jffs2_free_raw_inode(ri); up(&f->sem); jffs2_complete_reservation(c); /* We have to do the vmtruncate() without f->sem held, since some pages may be locked and waiting for it in readpage(). We are protected from a simultaneous write() extending i_size back past iattr->ia_size, because do_truncate() holds the generic inode semaphore. */ if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) vmtruncate(inode, iattr->ia_size); return 0; } Commit Message: CWE ID: CWE-264
static int jffs2_do_setattr (struct inode *inode, struct iattr *iattr) int jffs2_do_setattr (struct inode *inode, struct iattr *iattr) { struct jffs2_full_dnode *old_metadata, *new_metadata; struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb); struct jffs2_raw_inode *ri; union jffs2_device_node dev; unsigned char *mdata = NULL; int mdatalen = 0; unsigned int ivalid; uint32_t alloclen; int ret; D1(printk(KERN_DEBUG "jffs2_setattr(): ino #%lu\n", inode->i_ino)); /* Special cases - we don't want more than one data node for these types on the medium at any time. So setattr /* Special cases - we don't want more than one data node for these types on the medium at any time. So setattr must read the original data associated with the node (i.e. the device numbers or the target name) and write it out again with the appropriate data attached */ if (S_ISBLK(inode->i_mode) || S_ISCHR(inode->i_mode)) { /* For these, we don't actually need to read the old node */ mdatalen = jffs2_encode_dev(&dev, inode->i_rdev); mdata = (char *)&dev; D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of kdev_t\n", mdatalen)); } else if (S_ISLNK(inode->i_mode)) { down(&f->sem); mdatalen = f->metadata->size; mdata = kmalloc(f->metadata->size, GFP_USER); if (!mdata) { up(&f->sem); return -ENOMEM; } ret = jffs2_read_dnode(c, f, f->metadata, mdata, 0, mdatalen); if (ret) { up(&f->sem); kfree(mdata); return ret; } up(&f->sem); D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of symlink target\n", mdatalen)); } ri = jffs2_alloc_raw_inode(); if (!ri) { if (S_ISLNK(inode->i_mode)) kfree(mdata); return -ENOMEM; } ret = jffs2_reserve_space(c, sizeof(*ri) + mdatalen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE); if (ret) { jffs2_free_raw_inode(ri); if (S_ISLNK(inode->i_mode & S_IFMT)) kfree(mdata); return ret; } down(&f->sem); ivalid = iattr->ia_valid; ri->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); ri->nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE); ri->totlen = cpu_to_je32(sizeof(*ri) + mdatalen); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->ino = cpu_to_je32(inode->i_ino); ri->version = cpu_to_je32(++f->highest_version); ri->uid = cpu_to_je16((ivalid & ATTR_UID)?iattr->ia_uid:inode->i_uid); ri->gid = cpu_to_je16((ivalid & ATTR_GID)?iattr->ia_gid:inode->i_gid); if (ivalid & ATTR_MODE) if (iattr->ia_mode & S_ISGID && !in_group_p(je16_to_cpu(ri->gid)) && !capable(CAP_FSETID)) ri->mode = cpu_to_jemode(iattr->ia_mode & ~S_ISGID); else ri->mode = cpu_to_jemode(iattr->ia_mode); else ri->mode = cpu_to_jemode(inode->i_mode); ri->isize = cpu_to_je32((ivalid & ATTR_SIZE)?iattr->ia_size:inode->i_size); ri->atime = cpu_to_je32(I_SEC((ivalid & ATTR_ATIME)?iattr->ia_atime:inode->i_atime)); ri->mtime = cpu_to_je32(I_SEC((ivalid & ATTR_MTIME)?iattr->ia_mtime:inode->i_mtime)); ri->ctime = cpu_to_je32(I_SEC((ivalid & ATTR_CTIME)?iattr->ia_ctime:inode->i_ctime)); ri->offset = cpu_to_je32(0); ri->csize = ri->dsize = cpu_to_je32(mdatalen); ri->compr = JFFS2_COMPR_NONE; if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { /* It's an extension. Make it a hole node */ ri->compr = JFFS2_COMPR_ZERO; ri->dsize = cpu_to_je32(iattr->ia_size - inode->i_size); ri->offset = cpu_to_je32(inode->i_size); } ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); if (mdatalen) ri->data_crc = cpu_to_je32(crc32(0, mdata, mdatalen)); else ri->data_crc = cpu_to_je32(0); new_metadata = jffs2_write_dnode(c, f, ri, mdata, mdatalen, ALLOC_NORMAL); if (S_ISLNK(inode->i_mode)) kfree(mdata); if (IS_ERR(new_metadata)) { jffs2_complete_reservation(c); jffs2_free_raw_inode(ri); up(&f->sem); return PTR_ERR(new_metadata); } /* It worked. Update the inode */ inode->i_atime = ITIME(je32_to_cpu(ri->atime)); inode->i_ctime = ITIME(je32_to_cpu(ri->ctime)); inode->i_mtime = ITIME(je32_to_cpu(ri->mtime)); inode->i_mode = jemode_to_cpu(ri->mode); inode->i_uid = je16_to_cpu(ri->uid); inode->i_gid = je16_to_cpu(ri->gid); old_metadata = f->metadata; if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) jffs2_truncate_fragtree (c, &f->fragtree, iattr->ia_size); if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { jffs2_add_full_dnode_to_inode(c, f, new_metadata); inode->i_size = iattr->ia_size; f->metadata = NULL; } else { f->metadata = new_metadata; } if (old_metadata) { jffs2_mark_node_obsolete(c, old_metadata->raw); jffs2_free_full_dnode(old_metadata); } jffs2_free_raw_inode(ri); up(&f->sem); jffs2_complete_reservation(c); /* We have to do the vmtruncate() without f->sem held, since some pages may be locked and waiting for it in readpage(). We are protected from a simultaneous write() extending i_size back past iattr->ia_size, because do_truncate() holds the generic inode semaphore. */ if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) vmtruncate(inode, iattr->ia_size); return 0; }
164,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { InitializeConfig(); SetMode(GET_PARAM(1)); set_cpu_used_ = GET_PARAM(2); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { InitializeConfig(); SetMode(encoding_mode_); if (encoding_mode_ != ::libvpx_test::kRealTime) { cfg_.g_lag_in_frames = 25; cfg_.rc_end_usage = VPX_VBR; } else { cfg_.g_lag_in_frames = 0; cfg_.rc_end_usage = VPX_CBR; } } virtual void BeginPassHook(unsigned int /*pass*/) { min_psnr_ = kMaxPSNR; }
174,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppControllerImpl::GetApps( mojom::AppController::GetAppsCallback callback) { std::vector<chromeos::kiosk_next_home::mojom::AppPtr> app_list; app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { app_list.push_back(CreateAppPtr(update)); }); std::move(callback).Run(std::move(app_list)); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <[email protected]> Commit-Queue: Lucas Tenório <[email protected]> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void AppControllerImpl::GetApps( void AppControllerService::GetApps( mojom::AppController::GetAppsCallback callback) { std::vector<chromeos::kiosk_next_home::mojom::AppPtr> app_list; app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { app_list.push_back(CreateAppPtr(update)); }); std::move(callback).Run(std::move(app_list)); }
172,082
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppListController::Init(Profile* initial_profile) { if (win8::IsSingleWindowMetroMode()) return; PrefService* prefs = g_browser_process->local_state(); if (prefs->HasPrefPath(prefs::kRestartWithAppList) && prefs->GetBoolean(prefs::kRestartWithAppList)) { prefs->SetBoolean(prefs::kRestartWithAppList, false); AppListController::GetInstance()-> ShowAppListDuringModeSwitch(initial_profile); } AppListController::GetInstance(); ScheduleWarmup(); MigrateAppLauncherEnabledPref(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList)) EnableAppList(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList)) DisableAppList(); } Commit Message: Upgrade old app host to new app launcher on startup This patch is a continuation of https://codereview.chromium.org/16805002/. BUG=248825 Review URL: https://chromiumcodereview.appspot.com/17022015 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209604 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AppListController::Init(Profile* initial_profile) { if (win8::IsSingleWindowMetroMode()) return; PrefService* prefs = g_browser_process->local_state(); if (prefs->HasPrefPath(prefs::kRestartWithAppList) && prefs->GetBoolean(prefs::kRestartWithAppList)) { prefs->SetBoolean(prefs::kRestartWithAppList, false); AppListController::GetInstance()-> ShowAppListDuringModeSwitch(initial_profile); } // Migrate from legacy app launcher if we are on a non-canary and non-chromium // build. #if defined(GOOGLE_CHROME_BUILD) if (!InstallUtil::IsChromeSxSProcess() && !chrome_launcher_support::GetAnyAppHostPath().empty()) { chrome_launcher_support::InstallationState state = chrome_launcher_support::GetAppLauncherInstallationState(); if (state == chrome_launcher_support::NOT_INSTALLED) { // If app_host.exe is found but can't be located in the registry, // skip the migration as this is likely a developer build. return; } else if (state == chrome_launcher_support::INSTALLED_AT_SYSTEM_LEVEL) { chrome_launcher_support::UninstallLegacyAppLauncher( chrome_launcher_support::SYSTEM_LEVEL_INSTALLATION); } else if (state == chrome_launcher_support::INSTALLED_AT_USER_LEVEL) { chrome_launcher_support::UninstallLegacyAppLauncher( chrome_launcher_support::USER_LEVEL_INSTALLATION); } EnableAppList(); } #endif AppListController::GetInstance(); ScheduleWarmup(); MigrateAppLauncherEnabledPref(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableAppList)) EnableAppList(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableAppList)) DisableAppList(); }
171,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { log_err(ctx, "Cannot define %s in a keymap file\n", xkb_file_type_to_string(file->file_type)); continue; } if (files[file->file_type]) { log_err(ctx, "More than one %s section in keymap file; " "All sections after the first ignored\n", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, "Required section %s missing from keymap\n", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, "Compiling %s \"%s\"\n", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, "Failed to compile %s\n", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); } Commit Message: xkbcomp: fix crash when parsing an xkb_geometry section xkb_geometry sections are ignored; previously the had done so by returning NULL for the section's XkbFile, however some sections of the code do not expect this. Instead, create an XkbFile for it, it will never be processes and discarded later. Caught with the afl fuzzer. Signed-off-by: Ran Benita <[email protected]> CWE ID: CWE-476
CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge) { bool ok; XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL }; enum xkb_file_type type; struct xkb_context *ctx = keymap->ctx; /* Collect section files and check for duplicates. */ for (file = (XkbFile *) file->defs; file; file = (XkbFile *) file->common.next) { if (file->file_type < FIRST_KEYMAP_FILE_TYPE || file->file_type > LAST_KEYMAP_FILE_TYPE) { if (file->file_type == FILE_TYPE_GEOMETRY) { log_vrb(ctx, 1, "Geometry sections are not supported; ignoring\n"); } else { log_err(ctx, "Cannot define %s in a keymap file\n", xkb_file_type_to_string(file->file_type)); } continue; } if (files[file->file_type]) { log_err(ctx, "More than one %s section in keymap file; " "All sections after the first ignored\n", xkb_file_type_to_string(file->file_type)); continue; } files[file->file_type] = file; } /* * Check that all required section were provided. * Report everything before failing. */ ok = true; for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { if (files[type] == NULL) { log_err(ctx, "Required section %s missing from keymap\n", xkb_file_type_to_string(type)); ok = false; } } if (!ok) return false; /* Compile sections. */ for (type = FIRST_KEYMAP_FILE_TYPE; type <= LAST_KEYMAP_FILE_TYPE; type++) { log_dbg(ctx, "Compiling %s \"%s\"\n", xkb_file_type_to_string(type), files[type]->name); ok = compile_file_fns[type](files[type], keymap, merge); if (!ok) { log_err(ctx, "Failed to compile %s\n", xkb_file_type_to_string(type)); return false; } } return UpdateDerivedKeymapFields(keymap); }
169,095
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Document::InitContentSecurityPolicy( ContentSecurityPolicy* csp, const ContentSecurityPolicy* policy_to_inherit, const ContentSecurityPolicy* previous_document_csp) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); if (policy_to_inherit) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } else { if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); policy_to_inherit = inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); } } if (!policy_to_inherit) policy_to_inherit = previous_document_csp; if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (policy_to_inherit && IsPluginDocument()) GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); } Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener Spec PR: https://github.com/w3c/webappsec-csp/pull/358 Bug: 905301, 894228, 836148 Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a Reviewed-on: https://chromium-review.googlesource.com/c/1314633 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Mike West <[email protected]> Cr-Commit-Position: refs/heads/master@{#610850} CWE ID: CWE-20
void Document::InitContentSecurityPolicy( void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp, const Document* origin_document) { SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); GetContentSecurityPolicy()->BindToExecutionContext(this); ContentSecurityPolicy* policy_to_inherit = nullptr; if (origin_document) policy_to_inherit = origin_document->GetContentSecurityPolicy(); // We should inherit the navigation initiator CSP if the document is loaded // using a local-scheme url. if (policy_to_inherit && (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || url_.ProtocolIs("blob") || url_.ProtocolIs("filesystem"))) { GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); } if (IsPluginDocument()) { // TODO(andypaicu): This should inherit the origin document's plugin types // but because this could be a OOPIF document it might not have access. // In this situation we fallback on using the parent/opener. if (origin_document) { GetContentSecurityPolicy()->CopyPluginTypesFrom( origin_document->GetContentSecurityPolicy()); } else if (frame_) { Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() : frame_->Client()->Opener(); if (inherit_from && frame_ != inherit_from) { DCHECK(inherit_from->GetSecurityContext() && inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); GetContentSecurityPolicy()->CopyPluginTypesFrom( inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); } } } }
173,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void add_param_to_argv(char *parsestart, int line) { int quote_open = 0, escaped = 0, param_len = 0; char param_buffer[1024], *curchar; /* After fighting with strtok enough, here's now * a 'real' parser. According to Rusty I'm now no } else { param_buffer[param_len++] = *curchar; for (curchar = parsestart; *curchar; curchar++) { if (quote_open) { if (escaped) { param_buffer[param_len++] = *curchar; escaped = 0; continue; } else if (*curchar == '\\') { } switch (*curchar) { quote_open = 0; *curchar = '"'; } else { param_buffer[param_len++] = *curchar; continue; } } else { continue; } break; default: /* regular character, copy to buffer */ param_buffer[param_len++] = *curchar; if (param_len >= sizeof(param_buffer)) xtables_error(PARAMETER_PROBLEM, case ' ': case '\t': case '\n': if (!param_len) { /* two spaces? */ continue; } break; default: /* regular character, copy to buffer */ param_buffer[param_len++] = *curchar; if (param_len >= sizeof(param_buffer)) xtables_error(PARAMETER_PROBLEM, "Parameter too long!"); continue; } param_buffer[param_len] = '\0'; /* check if table name specified */ if ((param_buffer[0] == '-' && param_buffer[1] != '-' && strchr(param_buffer, 't')) || (!strncmp(param_buffer, "--t", 3) && !strncmp(param_buffer, "--table", strlen(param_buffer)))) { xtables_error(PARAMETER_PROBLEM, "The -t option (seen in line %u) cannot be used in %s.\n", line, xt_params->program_name); } add_argv(param_buffer, 0); param_len = 0; } Commit Message: CWE ID: CWE-119
void add_param_to_argv(char *parsestart, int line) { int quote_open = 0, escaped = 0; struct xt_param_buf param = {}; char *curchar; /* After fighting with strtok enough, here's now * a 'real' parser. According to Rusty I'm now no } else { param_buffer[param_len++] = *curchar; for (curchar = parsestart; *curchar; curchar++) { if (quote_open) { if (escaped) { add_param(&param, curchar); escaped = 0; continue; } else if (*curchar == '\\') { } switch (*curchar) { quote_open = 0; *curchar = '"'; } else { add_param(&param, curchar); continue; } } else { continue; } break; default: /* regular character, copy to buffer */ param_buffer[param_len++] = *curchar; if (param_len >= sizeof(param_buffer)) xtables_error(PARAMETER_PROBLEM, case ' ': case '\t': case '\n': if (!param.len) { /* two spaces? */ continue; } break; default: /* regular character, copy to buffer */ add_param(&param, curchar); continue; } param.buffer[param.len] = '\0'; /* check if table name specified */ if ((param.buffer[0] == '-' && param.buffer[1] != '-' && strchr(param.buffer, 't')) || (!strncmp(param.buffer, "--t", 3) && !strncmp(param.buffer, "--table", strlen(param.buffer)))) { xtables_error(PARAMETER_PROBLEM, "The -t option (seen in line %u) cannot be used in %s.\n", line, xt_params->program_name); } add_argv(param.buffer, 0); param.len = 0; }
164,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const { return GetTime(pChapters, m_start_timecode); } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const
174,355
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: kdc_process_s4u2self_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_const_principal client_princ, krb5_const_principal header_srv_princ, krb5_boolean issuing_referral, const krb5_db_entry *server, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_timestamp kdc_time, krb5_pa_s4u_x509_user **s4u_x509_user, krb5_db_entry **princ_ptr, const char **status) { krb5_error_code code; krb5_boolean is_local_tgt; krb5_pa_data *pa_data; int flags; krb5_db_entry *princ; *princ_ptr = NULL; pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_S4U_X509_USER); if (pa_data != NULL) { code = kdc_process_s4u_x509_user(kdc_context, request, pa_data, tgs_subkey, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else { pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_FOR_USER); if (pa_data != NULL) { code = kdc_process_for_user(kdc_active_realm, pa_data, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else return 0; } /* * We need to compare the client name in the TGT with the requested * server name. Supporting server name aliases without assuming a * global name service makes this difficult to do. * * The comparison below handles the following cases (note that the * term "principal name" below excludes the realm). * * (1) The requested service is a host-based service with two name * components, in which case we assume the principal name to * contain sufficient qualifying information. The realm is * ignored for the purpose of comparison. * * (2) The requested service name is an enterprise principal name: * the service principal name is compared with the unparsed * form of the client name (including its realm). * * (3) The requested service is some other name type: an exact * match is required. * * An alternative would be to look up the server once again with * FLAG_CANONICALIZE | FLAG_CLIENT_REFERRALS_ONLY set, do an exact * match between the returned name and client_princ. However, this * assumes that the client set FLAG_CANONICALIZE when requesting * the TGT and that we have a global name service. */ flags = 0; switch (krb5_princ_type(kdc_context, request->server)) { case KRB5_NT_SRV_HST: /* (1) */ if (krb5_princ_size(kdc_context, request->server) == 2) flags |= KRB5_PRINCIPAL_COMPARE_IGNORE_REALM; break; case KRB5_NT_ENTERPRISE_PRINCIPAL: /* (2) */ flags |= KRB5_PRINCIPAL_COMPARE_ENTERPRISE; break; default: /* (3) */ break; } if (!krb5_principal_compare_flags(kdc_context, request->server, client_princ, flags)) { *status = "INVALID_S4U2SELF_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error code */ } /* * Protocol transition is mutually exclusive with renew/forward/etc * as well as user-to-user and constrained delegation. This check * is also made in validate_as_request(). * * We can assert from this check that the header ticket was a TGT, as * that is validated previously in validate_tgs_request(). */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KRB5KDC_ERR_BADOPTION; } /* * Valid S4U2Self requests can occur in the following combinations: * * (1) local TGT, local user, local server * (2) cross TGT, local user, issuing referral * (3) cross TGT, non-local user, issuing referral * (4) cross TGT, non-local user, local server * * The first case is for a single-realm S4U2Self scenario; the second, * third, and fourth cases are for the initial, intermediate (if any), and * final cross-realm requests in a multi-realm scenario. */ is_local_tgt = !is_cross_tgs_principal(header_srv_princ); if (is_local_tgt && issuing_referral) { /* The requesting server appears to no longer exist, and we found * a referral instead. Treat this as a server lookup failure. */ *status = "LOOKING_UP_SERVER"; return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; } /* * Do not attempt to lookup principals in foreign realms. */ if (is_local_principal(kdc_active_realm, (*s4u_x509_user)->user_id.user)) { krb5_db_entry no_server; krb5_pa_data **e_data = NULL; if (!is_local_tgt && !issuing_referral) { /* A local server should not need a cross-realm TGT to impersonate * a local principal. */ *status = "NOT_CROSS_REALM_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error */ } code = krb5_db_get_principal(kdc_context, (*s4u_x509_user)->user_id.user, KRB5_KDB_FLAG_INCLUDE_PAC, &princ); if (code == KRB5_KDB_NOENTRY) { *status = "UNKNOWN_S4U2SELF_PRINCIPAL"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } else if (code) { *status = "LOOKING_UP_S4U2SELF_PRINCIPAL"; return code; /* caller can free for_user */ } memset(&no_server, 0, sizeof(no_server)); code = validate_as_request(kdc_active_realm, request, *princ, no_server, kdc_time, status, &e_data); if (code) { krb5_db_free_principal(kdc_context, princ); krb5_free_pa_data(kdc_context, e_data); return code; } *princ_ptr = princ; } else if (is_local_tgt) { /* * The server is asking to impersonate a principal from another realm, * using a local TGT. It should instead ask that principal's realm and * follow referrals back to us. */ *status = "S4U2SELF_CLIENT_NOT_OURS"; return KRB5KDC_ERR_POLICY; /* match Windows error */ } return 0; } Commit Message: Ignore password attributes for S4U2Self requests For consistency with Windows KDCs, allow protocol transition to work even if the password has expired or needs changing. Also, when looking up an enterprise principal with an AS request, treat ERR_KEY_EXP as confirmation that the client is present in the realm. [[email protected]: added comment in kdc_process_s4u2self_req(); edited commit message] ticket: 8763 (new) tags: pullup target_version: 1.17 CWE ID: CWE-617
kdc_process_s4u2self_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, krb5_const_principal client_princ, krb5_const_principal header_srv_princ, krb5_boolean issuing_referral, const krb5_db_entry *server, krb5_keyblock *tgs_subkey, krb5_keyblock *tgs_session, krb5_timestamp kdc_time, krb5_pa_s4u_x509_user **s4u_x509_user, krb5_db_entry **princ_ptr, const char **status) { krb5_error_code code; krb5_boolean is_local_tgt; krb5_pa_data *pa_data; int flags; krb5_db_entry *princ; *princ_ptr = NULL; pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_S4U_X509_USER); if (pa_data != NULL) { code = kdc_process_s4u_x509_user(kdc_context, request, pa_data, tgs_subkey, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else { pa_data = krb5int_find_pa_data(kdc_context, request->padata, KRB5_PADATA_FOR_USER); if (pa_data != NULL) { code = kdc_process_for_user(kdc_active_realm, pa_data, tgs_session, s4u_x509_user, status); if (code != 0) return code; } else return 0; } /* * We need to compare the client name in the TGT with the requested * server name. Supporting server name aliases without assuming a * global name service makes this difficult to do. * * The comparison below handles the following cases (note that the * term "principal name" below excludes the realm). * * (1) The requested service is a host-based service with two name * components, in which case we assume the principal name to * contain sufficient qualifying information. The realm is * ignored for the purpose of comparison. * * (2) The requested service name is an enterprise principal name: * the service principal name is compared with the unparsed * form of the client name (including its realm). * * (3) The requested service is some other name type: an exact * match is required. * * An alternative would be to look up the server once again with * FLAG_CANONICALIZE | FLAG_CLIENT_REFERRALS_ONLY set, do an exact * match between the returned name and client_princ. However, this * assumes that the client set FLAG_CANONICALIZE when requesting * the TGT and that we have a global name service. */ flags = 0; switch (krb5_princ_type(kdc_context, request->server)) { case KRB5_NT_SRV_HST: /* (1) */ if (krb5_princ_size(kdc_context, request->server) == 2) flags |= KRB5_PRINCIPAL_COMPARE_IGNORE_REALM; break; case KRB5_NT_ENTERPRISE_PRINCIPAL: /* (2) */ flags |= KRB5_PRINCIPAL_COMPARE_ENTERPRISE; break; default: /* (3) */ break; } if (!krb5_principal_compare_flags(kdc_context, request->server, client_princ, flags)) { *status = "INVALID_S4U2SELF_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error code */ } /* * Protocol transition is mutually exclusive with renew/forward/etc * as well as user-to-user and constrained delegation. This check * is also made in validate_as_request(). * * We can assert from this check that the header ticket was a TGT, as * that is validated previously in validate_tgs_request(). */ if (request->kdc_options & AS_INVALID_OPTIONS) { *status = "INVALID AS OPTIONS"; return KRB5KDC_ERR_BADOPTION; } /* * Valid S4U2Self requests can occur in the following combinations: * * (1) local TGT, local user, local server * (2) cross TGT, local user, issuing referral * (3) cross TGT, non-local user, issuing referral * (4) cross TGT, non-local user, local server * * The first case is for a single-realm S4U2Self scenario; the second, * third, and fourth cases are for the initial, intermediate (if any), and * final cross-realm requests in a multi-realm scenario. */ is_local_tgt = !is_cross_tgs_principal(header_srv_princ); if (is_local_tgt && issuing_referral) { /* The requesting server appears to no longer exist, and we found * a referral instead. Treat this as a server lookup failure. */ *status = "LOOKING_UP_SERVER"; return KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN; } /* * Do not attempt to lookup principals in foreign realms. */ if (is_local_principal(kdc_active_realm, (*s4u_x509_user)->user_id.user)) { krb5_db_entry no_server; krb5_pa_data **e_data = NULL; if (!is_local_tgt && !issuing_referral) { /* A local server should not need a cross-realm TGT to impersonate * a local principal. */ *status = "NOT_CROSS_REALM_REQUEST"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; /* match Windows error */ } code = krb5_db_get_principal(kdc_context, (*s4u_x509_user)->user_id.user, KRB5_KDB_FLAG_INCLUDE_PAC, &princ); if (code == KRB5_KDB_NOENTRY) { *status = "UNKNOWN_S4U2SELF_PRINCIPAL"; return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; } else if (code) { *status = "LOOKING_UP_S4U2SELF_PRINCIPAL"; return code; /* caller can free for_user */ } memset(&no_server, 0, sizeof(no_server)); /* Ignore password expiration and needchange attributes (as Windows * does), since S4U2Self is not password authentication. */ princ->pw_expiration = 0; clear(princ->attributes, KRB5_KDB_REQUIRES_PWCHANGE); code = validate_as_request(kdc_active_realm, request, *princ, no_server, kdc_time, status, &e_data); if (code) { krb5_db_free_principal(kdc_context, princ); krb5_free_pa_data(kdc_context, e_data); return code; } *princ_ptr = princ; } else if (is_local_tgt) { /* * The server is asking to impersonate a principal from another realm, * using a local TGT. It should instead ask that principal's realm and * follow referrals back to us. */ *status = "S4U2SELF_CLIENT_NOT_OURS"; return KRB5KDC_ERR_POLICY; /* match Windows error */ } return 0; }
168,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InspectorClientImpl::clearBrowserCookies() { if (WebDevToolsAgentImpl* agent = devToolsAgent()) agent->clearBrowserCookies(); } Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser. BUG=366585 Review URL: https://codereview.chromium.org/251183005 git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void InspectorClientImpl::clearBrowserCookies()
171,347
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 scsi_cmd_blk_ioctl(struct block_device *bd, fmode_t mode, unsigned int cmd, void __user *arg) { return scsi_cmd_ioctl(bd->bd_disk->queue, bd->bd_disk, mode, cmd, arg); } Commit Message: block: fail SCSI passthrough ioctls on partition devices Linux allows executing the SG_IO ioctl on a partition or LVM volume, and will pass the command to the underlying block device. This is well-known, but it is also a large security problem when (via Unix permissions, ACLs, SELinux or a combination thereof) a program or user needs to be granted access only to part of the disk. This patch lets partitions forward a small set of harmless ioctls; others are logged with printk so that we can see which ioctls are actually sent. In my tests only CDROM_GET_CAPABILITY actually occurred. Of course it was being sent to a (partition on a) hard disk, so it would have failed with ENOTTY and the patch isn't changing anything in practice. Still, I'm treating it specially to avoid spamming the logs. In principle, this restriction should include programs running with CAP_SYS_RAWIO. If for example I let a program access /dev/sda2 and /dev/sdb, it still should not be able to read/write outside the boundaries of /dev/sda2 independent of the capabilities. However, for now programs with CAP_SYS_RAWIO will still be allowed to send the ioctls. Their actions will still be logged. This patch does not affect the non-libata IDE driver. That driver however already tests for bd != bd->bd_contains before issuing some ioctl; it could be restricted further to forbid these ioctls even for programs running with CAP_SYS_ADMIN/CAP_SYS_RAWIO. Cc: [email protected] Cc: Jens Axboe <[email protected]> Cc: James Bottomley <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> [ Make it also print the command name when warning - Linus ] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
int scsi_cmd_blk_ioctl(struct block_device *bd, fmode_t mode, unsigned int cmd, void __user *arg) { int ret; ret = scsi_verify_blk_ioctl(bd, cmd); if (ret < 0) return ret; return scsi_cmd_ioctl(bd->bd_disk->queue, bd->bd_disk, mode, cmd, arg); }
169,889
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; in->data[plane] && plane < 4; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; in->data[plane] && plane < 4; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); } Commit Message: avfilter: fix plane validity checks Fixes out of array accesses Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVFilterContext *ctx = inlink->dst; BoxBlurContext *s = ctx->priv; AVFilterLink *outlink = inlink->dst->outputs[0]; AVFrame *out; int plane; int cw = FF_CEIL_RSHIFT(inlink->w, s->hsub), ch = FF_CEIL_RSHIFT(in->height, s->vsub); int w[4] = { inlink->w, cw, cw, inlink->w }; int h[4] = { in->height, ch, ch, in->height }; out = ff_get_video_buffer(outlink, outlink->w, outlink->h); if (!out) { av_frame_free(&in); return AVERROR(ENOMEM); } av_frame_copy_props(out, in); for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) hblur(out->data[plane], out->linesize[plane], in ->data[plane], in ->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); for (plane = 0; plane < 4 && in->data[plane] && in->linesize[plane]; plane++) vblur(out->data[plane], out->linesize[plane], out->data[plane], out->linesize[plane], w[plane], h[plane], s->radius[plane], s->power[plane], s->temp); av_frame_free(&in); return ff_filter_frame(outlink, out); }
165,997
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int sysMapBlockFile(FILE* mapf, MemMapping* pMap) { char block_dev[PATH_MAX+1]; size_t size; unsigned int blksize; unsigned int blocks; unsigned int range_count; unsigned int i; if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) { LOGW("failed to read block device from header\n"); return -1; } for (i = 0; i < sizeof(block_dev); ++i) { if (block_dev[i] == '\n') { block_dev[i] = 0; break; } } if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) { LOGW("failed to parse block map header\n"); return -1; } blocks = ((size-1) / blksize) + 1; pMap->range_count = range_count; pMap->ranges = malloc(range_count * sizeof(MappedRange)); memset(pMap->ranges, 0, range_count * sizeof(MappedRange)); unsigned char* reserve; reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); if (reserve == MAP_FAILED) { LOGW("failed to reserve address space: %s\n", strerror(errno)); return -1; } pMap->ranges[range_count-1].addr = reserve; pMap->ranges[range_count-1].length = blocks * blksize; int fd = open(block_dev, O_RDONLY); if (fd < 0) { LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno)); return -1; } unsigned char* next = reserve; for (i = 0; i < range_count; ++i) { int start, end; if (fscanf(mapf, "%d %d\n", &start, &end) != 2) { LOGW("failed to parse range %d in block map\n", i); return -1; } void* addr = mmap64(next, (end-start)*blksize, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize); if (addr == MAP_FAILED) { LOGW("failed to map block %d: %s\n", i, strerror(errno)); return -1; } pMap->ranges[i].addr = addr; pMap->ranges[i].length = (end-start)*blksize; next += pMap->ranges[i].length; } pMap->addr = reserve; pMap->length = size; LOGI("mmapped %d ranges\n", range_count); return 0; } Commit Message: Fix integer overflows in recovery procedure. Bug: 26960931 Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf (cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b) CWE ID: CWE-189
static int sysMapBlockFile(FILE* mapf, MemMapping* pMap) { char block_dev[PATH_MAX+1]; size_t size; unsigned int blksize; size_t blocks; unsigned int range_count; unsigned int i; if (fgets(block_dev, sizeof(block_dev), mapf) == NULL) { LOGW("failed to read block device from header\n"); return -1; } for (i = 0; i < sizeof(block_dev); ++i) { if (block_dev[i] == '\n') { block_dev[i] = 0; break; } } if (fscanf(mapf, "%zu %u\n%u\n", &size, &blksize, &range_count) != 3) { LOGW("failed to parse block map header\n"); return -1; } if (blksize != 0) { blocks = ((size-1) / blksize) + 1; } if (size == 0 || blksize == 0 || blocks > SIZE_MAX / blksize || range_count == 0) { LOGE("invalid data in block map file: size %zu, blksize %u, range_count %u\n", size, blksize, range_count); return -1; } pMap->range_count = range_count; pMap->ranges = calloc(range_count, sizeof(MappedRange)); if (pMap->ranges == NULL) { LOGE("calloc(%u, %zu) failed: %s\n", range_count, sizeof(MappedRange), strerror(errno)); return -1; } unsigned char* reserve; reserve = mmap64(NULL, blocks * blksize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); if (reserve == MAP_FAILED) { LOGW("failed to reserve address space: %s\n", strerror(errno)); free(pMap->ranges); return -1; } int fd = open(block_dev, O_RDONLY); if (fd < 0) { LOGW("failed to open block device %s: %s\n", block_dev, strerror(errno)); munmap(reserve, blocks * blksize); free(pMap->ranges); return -1; } unsigned char* next = reserve; size_t remaining_size = blocks * blksize; bool success = true; for (i = 0; i < range_count; ++i) { size_t start, end; if (fscanf(mapf, "%zu %zu\n", &start, &end) != 2) { LOGW("failed to parse range %d in block map\n", i); success = false; break; } size_t length = (end - start) * blksize; if (end <= start || (end - start) > SIZE_MAX / blksize || length > remaining_size) { LOGE("unexpected range in block map: %zu %zu\n", start, end); success = false; break; } void* addr = mmap64(next, length, PROT_READ, MAP_PRIVATE | MAP_FIXED, fd, ((off64_t)start)*blksize); if (addr == MAP_FAILED) { LOGW("failed to map block %d: %s\n", i, strerror(errno)); success = false; break; } pMap->ranges[i].addr = addr; pMap->ranges[i].length = length; next += length; remaining_size -= length; } if (success && remaining_size != 0) { LOGE("ranges in block map are invalid: remaining_size = %zu\n", remaining_size); success = false; } if (!success) { close(fd); munmap(reserve, blocks * blksize); free(pMap->ranges); return -1; } close(fd); pMap->addr = reserve; pMap->length = size; LOGI("mmapped %d ranges\n", range_count); return 0; }
173,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m); size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) len = sizeof(p->s) - 1; while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } } Commit Message: Correctly compute the truncated pascal string size (Francisco Alonso and Jan Kaluza at RedHat) CWE ID: CWE-119
mconvert(struct magic_set *ms, struct magic *m, int flip) { union VALUETYPE *p = &ms->ms_value; uint8_t type; switch (type = cvt_flip(m->type, flip)) { case FILE_BYTE: cvt_8(p, m); return 1; case FILE_SHORT: cvt_16(p, m); return 1; case FILE_LONG: case FILE_DATE: case FILE_LDATE: cvt_32(p, m); return 1; case FILE_QUAD: case FILE_QDATE: case FILE_QLDATE: case FILE_QWDATE: cvt_64(p, m); return 1; case FILE_STRING: case FILE_BESTRING16: case FILE_LESTRING16: { /* Null terminate and eat *trailing* return */ p->s[sizeof(p->s) - 1] = '\0'; return 1; } case FILE_PSTRING: { size_t sz = file_pstring_length_size(m); char *ptr1 = p->s, *ptr2 = ptr1 + sz; size_t len = file_pstring_get_length(m, ptr1); if (len >= sizeof(p->s)) { /* * The size of the pascal string length (sz) * is 1, 2, or 4. We need at least 1 byte for NUL * termination, but we've already truncated the * string by p->s, so we need to deduct sz. */ len = sizeof(p->s) - sz; } while (len--) *ptr1++ = *ptr2++; *ptr1 = '\0'; return 1; } case FILE_BESHORT: p->h = (short)((p->hs[0]<<8)|(p->hs[1])); cvt_16(p, m); return 1; case FILE_BELONG: case FILE_BEDATE: case FILE_BELDATE: p->l = (int32_t) ((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3])); if (type == FILE_BELONG) cvt_32(p, m); return 1; case FILE_BEQUAD: case FILE_BEQDATE: case FILE_BEQLDATE: case FILE_BEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7])); if (type == FILE_BEQUAD) cvt_64(p, m); return 1; case FILE_LESHORT: p->h = (short)((p->hs[1]<<8)|(p->hs[0])); cvt_16(p, m); return 1; case FILE_LELONG: case FILE_LEDATE: case FILE_LELDATE: p->l = (int32_t) ((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0])); if (type == FILE_LELONG) cvt_32(p, m); return 1; case FILE_LEQUAD: case FILE_LEQDATE: case FILE_LEQLDATE: case FILE_LEQWDATE: p->q = (uint64_t) (((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0])); if (type == FILE_LEQUAD) cvt_64(p, m); return 1; case FILE_MELONG: case FILE_MEDATE: case FILE_MELDATE: p->l = (int32_t) ((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2])); if (type == FILE_MELONG) cvt_32(p, m); return 1; case FILE_FLOAT: cvt_float(p, m); return 1; case FILE_BEFLOAT: p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)| ((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]); cvt_float(p, m); return 1; case FILE_LEFLOAT: p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)| ((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]); cvt_float(p, m); return 1; case FILE_DOUBLE: cvt_double(p, m); return 1; case FILE_BEDOUBLE: p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)| ((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)| ((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)| ((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]); cvt_double(p, m); return 1; case FILE_LEDOUBLE: p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)| ((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)| ((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)| ((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]); cvt_double(p, m); return 1; case FILE_REGEX: case FILE_SEARCH: case FILE_DEFAULT: case FILE_CLEAR: case FILE_NAME: case FILE_USE: return 1; default: file_magerror(ms, "invalid type %d in mconvert()", m->type); return 0; } }
166,367
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PassRefPtrWillBeRawPtr<File> DOMFileSystemSync::createFile(const FileEntrySync* fileEntry, ExceptionState& exceptionState) { KURL fileSystemURL = createFileSystemURL(fileEntry); RefPtrWillBeRawPtr<CreateFileHelper::CreateFileResult> result(CreateFileHelper::CreateFileResult::create()); fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, CreateFileHelper::create(result, fileEntry->name(), fileSystemURL, type())); if (result->m_failed) { exceptionState.throwDOMException(result->m_code, "Could not create '" + fileEntry->name() + "'."); return nullptr; } return result->m_file.get(); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
PassRefPtrWillBeRawPtr<File> DOMFileSystemSync::createFile(const FileEntrySync* fileEntry, ExceptionState& exceptionState) { KURL fileSystemURL = createFileSystemURL(fileEntry); CreateFileHelper::CreateFileResult* result(CreateFileHelper::CreateFileResult::create()); fileSystem()->createSnapshotFileAndReadMetadata(fileSystemURL, CreateFileHelper::create(result, fileEntry->name(), fileSystemURL, type())); if (result->m_failed) { exceptionState.throwDOMException(result->m_code, "Could not create '" + fileEntry->name() + "'."); return nullptr; } return result->m_file.get(); }
171,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DECLAREcpFunc(cpContig2SeparateByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); /* unpack channels */ for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = ((uint8*)inbuf) + s; outp = (uint8*)outbuf; for (n = imagewidth; n-- > 0;) { *outp++ = *inp; inp += spp; } if (TIFFWriteScanline(out, outbuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } Commit Message: * tools/tiffcp.c: error out cleanly in cpContig2SeparateByRow and cpSeparate2ContigByRow if BitsPerSample != 8 to avoid heap based overflow. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2656 and http://bugzilla.maptools.org/show_bug.cgi?id=2657 CWE ID: CWE-119
DECLAREcpFunc(cpContig2SeparateByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; uint16 bps = 0; (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); if( bps != 8 ) { TIFFError(TIFFFileName(in), "Error, can only handle BitsPerSample=8 in %s", "cpContig2SeparateByRow"); return 0; } inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); /* unpack channels */ for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = ((uint8*)inbuf) + s; outp = (uint8*)outbuf; for (n = imagewidth; n-- > 0;) { *outp++ = *inp; inp += spp; } if (TIFFWriteScanline(out, outbuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; }
168,412
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserCommandController::TabDetachedAt(TabContents* contents, int index) { RemoveInterstitialObservers(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 BrowserCommandController::TabDetachedAt(TabContents* contents, int index) { void BrowserCommandController::TabDetachedAt(WebContents* contents, int index) { RemoveInterstitialObservers(contents); }
171,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } }
167,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameHostImpl::RegisterMojoInterfaces() { #if !defined(OS_ANDROID) registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create)); #endif // !defined(OS_ANDROID) PermissionControllerImpl* permission_controller = PermissionControllerImpl::FromBrowserContext( GetProcess()->GetBrowserContext()); if (delegate_) { auto* geolocation_context = delegate_->GetGeolocationContext(); if (geolocation_context) { geolocation_service_.reset(new GeolocationServiceImpl( geolocation_context, permission_controller, this)); registry_->AddInterface( base::Bind(&GeolocationServiceImpl::Bind, base::Unretained(geolocation_service_.get()))); } } registry_->AddInterface<device::mojom::WakeLock>(base::Bind( &RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this))); #if defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebNfc)) { registry_->AddInterface<device::mojom::NFC>(base::Bind( &RenderFrameHostImpl::BindNFCRequest, base::Unretained(this))); } #endif if (!permission_service_context_) permission_service_context_.reset(new PermissionServiceContext(this)); registry_->AddInterface( base::Bind(&PermissionServiceContext::CreateService, base::Unretained(permission_service_context_.get()))); registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest, base::Unretained(this))); registry_->AddInterface( base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this))); registry_->AddInterface(base::Bind( base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService), base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this))); registry_->AddInterface<media::mojom::InterfaceFactory>( base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebSocket, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateDedicatedWorkerHostFactory, base::Unretained(this))); registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create, process_->GetID(), routing_id_)); registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create)); registry_->AddInterface<device::mojom::VRService>(base::Bind( &WebvrServiceProvider::BindWebvrService, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this))); if (BrowserMainLoop::GetInstance()) { MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); registry_->AddInterface( base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); registry_->AddInterface( base::BindRepeating( &RenderFrameHostImpl::CreateMediaStreamDispatcherHost, base::Unretained(this), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } #if BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind, GetProcess()->GetID(), GetRoutingID())); #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::BindRepeating( &KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this))); registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create)); #if !defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebAuth)) { registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest, base::Unretained(this))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWebAuthTestingAPI)) { auto* environment_singleton = ScopedVirtualAuthenticatorEnvironment::GetInstance(); registry_->AddInterface(base::BindRepeating( &ScopedVirtualAuthenticatorEnvironment::AddBinding, base::Unretained(environment_singleton))); } } #endif // !defined(OS_ANDROID) sensor_provider_proxy_.reset( new SensorProviderProxyImpl(permission_controller, this)); registry_->AddInterface( base::Bind(&SensorProviderProxyImpl::Bind, base::Unretained(sensor_provider_proxy_.get()))); media::VideoDecodePerfHistory::SaveCallback save_stats_cb; if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) { save_stats_cb = GetSiteInstance() ->GetBrowserContext() ->GetVideoDecodePerfHistory() ->GetSaveCallback(); } registry_->AddInterface(base::BindRepeating( &media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(), base::BindRepeating( &RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource, base::Unretained(delegate_)), std::move(save_stats_cb))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( cc::switches::kEnableGpuBenchmarking)) { registry_->AddInterface( base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr())); } registry_->AddInterface(base::BindRepeating( &QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface( base::BindRepeating(SpeechRecognitionDispatcherHost::Create, GetProcess()->GetID(), routing_id_), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); file_system_manager_.reset(new FileSystemManagerImpl( GetProcess()->GetID(), routing_id_, GetProcess()->GetStoragePartition()->GetFileSystemContext(), ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext()))); registry_->AddInterface( base::BindRepeating(&FileSystemManagerImpl::BindRequest, base::Unretained(file_system_manager_.get())), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); if (Portal::IsEnabled()) { registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create), base::Unretained(this))); } registry_->AddInterface(base::BindRepeating( &BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create)); registry_->AddInterface( base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create, base::Unretained(this))); } Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame. Instead of having RenderFrameHost own a single MSDH to handle all requests from a frame, MSDH objects will be owned by a strong binding. A consequence of this is that an additional requester ID is added to requests to MediaStreamManager, so that an MSDH is able to cancel only requests generated by it. In practice, MSDH will continue to be per frame in most cases since each frame normally makes a single request for an MSDH object. This fixes a lifetime issue caused by the IO thread executing tasks after the RenderFrameHost dies. Drive-by: Fix some minor lint issues. Bug: 912520 Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516 Reviewed-on: https://chromium-review.googlesource.com/c/1369799 Reviewed-by: Emircan Uysaler <[email protected]> Reviewed-by: Ken Buchanan <[email protected]> Reviewed-by: Olga Sharonova <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#616347} CWE ID: CWE-189
void RenderFrameHostImpl::RegisterMojoInterfaces() { #if !defined(OS_ANDROID) registry_->AddInterface(base::Bind(&InstalledAppProviderImplDefault::Create)); #endif // !defined(OS_ANDROID) PermissionControllerImpl* permission_controller = PermissionControllerImpl::FromBrowserContext( GetProcess()->GetBrowserContext()); if (delegate_) { auto* geolocation_context = delegate_->GetGeolocationContext(); if (geolocation_context) { geolocation_service_.reset(new GeolocationServiceImpl( geolocation_context, permission_controller, this)); registry_->AddInterface( base::Bind(&GeolocationServiceImpl::Bind, base::Unretained(geolocation_service_.get()))); } } registry_->AddInterface<device::mojom::WakeLock>(base::Bind( &RenderFrameHostImpl::BindWakeLockRequest, base::Unretained(this))); #if defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebNfc)) { registry_->AddInterface<device::mojom::NFC>(base::Bind( &RenderFrameHostImpl::BindNFCRequest, base::Unretained(this))); } #endif if (!permission_service_context_) permission_service_context_.reset(new PermissionServiceContext(this)); registry_->AddInterface( base::Bind(&PermissionServiceContext::CreateService, base::Unretained(permission_service_context_.get()))); registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindPresentationServiceRequest, base::Unretained(this))); registry_->AddInterface( base::Bind(&MediaSessionServiceImpl::Create, base::Unretained(this))); registry_->AddInterface(base::Bind( base::IgnoreResult(&RenderFrameHostImpl::CreateWebBluetoothService), base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebUsbService, base::Unretained(this))); registry_->AddInterface<media::mojom::InterfaceFactory>( base::Bind(&RenderFrameHostImpl::BindMediaInterfaceFactoryRequest, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateWebSocket, base::Unretained(this))); registry_->AddInterface(base::BindRepeating( &RenderFrameHostImpl::CreateDedicatedWorkerHostFactory, base::Unretained(this))); registry_->AddInterface(base::Bind(&SharedWorkerConnectorImpl::Create, process_->GetID(), routing_id_)); registry_->AddInterface(base::BindRepeating(&device::GamepadMonitor::Create)); registry_->AddInterface<device::mojom::VRService>(base::Bind( &WebvrServiceProvider::BindWebvrService, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioInputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::BindRepeating(&RenderFrameHostImpl::CreateAudioOutputStreamFactory, base::Unretained(this))); registry_->AddInterface( base::Bind(&CreateFrameResourceCoordinator, base::Unretained(this))); if (BrowserMainLoop::GetInstance()) { MediaStreamManager* media_stream_manager = BrowserMainLoop::GetInstance()->media_stream_manager(); registry_->AddInterface( base::Bind(&MediaDevicesDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); registry_->AddInterface( base::BindRepeating(&MediaStreamDispatcherHost::Create, GetProcess()->GetID(), GetRoutingID(), base::Unretained(media_stream_manager)), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); } #if BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::Bind(&RemoterFactoryImpl::Bind, GetProcess()->GetID(), GetRoutingID())); #endif // BUILDFLAG(ENABLE_MEDIA_REMOTING) registry_->AddInterface(base::BindRepeating( &KeyboardLockServiceImpl::CreateMojoService, base::Unretained(this))); registry_->AddInterface(base::Bind(&ImageCaptureImpl::Create)); #if !defined(OS_ANDROID) if (base::FeatureList::IsEnabled(features::kWebAuth)) { registry_->AddInterface( base::Bind(&RenderFrameHostImpl::BindAuthenticatorRequest, base::Unretained(this))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableWebAuthTestingAPI)) { auto* environment_singleton = ScopedVirtualAuthenticatorEnvironment::GetInstance(); registry_->AddInterface(base::BindRepeating( &ScopedVirtualAuthenticatorEnvironment::AddBinding, base::Unretained(environment_singleton))); } } #endif // !defined(OS_ANDROID) sensor_provider_proxy_.reset( new SensorProviderProxyImpl(permission_controller, this)); registry_->AddInterface( base::Bind(&SensorProviderProxyImpl::Bind, base::Unretained(sensor_provider_proxy_.get()))); media::VideoDecodePerfHistory::SaveCallback save_stats_cb; if (GetSiteInstance()->GetBrowserContext()->GetVideoDecodePerfHistory()) { save_stats_cb = GetSiteInstance() ->GetBrowserContext() ->GetVideoDecodePerfHistory() ->GetSaveCallback(); } registry_->AddInterface(base::BindRepeating( &media::MediaMetricsProvider::Create, frame_tree_node_->IsMainFrame(), base::BindRepeating( &RenderFrameHostDelegate::GetUkmSourceIdForLastCommittedSource, base::Unretained(delegate_)), std::move(save_stats_cb))); if (base::CommandLine::ForCurrentProcess()->HasSwitch( cc::switches::kEnableGpuBenchmarking)) { registry_->AddInterface( base::Bind(&InputInjectorImpl::Create, weak_ptr_factory_.GetWeakPtr())); } registry_->AddInterface(base::BindRepeating( &QuotaDispatcherHost::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface( base::BindRepeating(SpeechRecognitionDispatcherHost::Create, GetProcess()->GetID(), routing_id_), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); file_system_manager_.reset(new FileSystemManagerImpl( GetProcess()->GetID(), routing_id_, GetProcess()->GetStoragePartition()->GetFileSystemContext(), ChromeBlobStorageContext::GetFor(GetProcess()->GetBrowserContext()))); registry_->AddInterface( base::BindRepeating(&FileSystemManagerImpl::BindRequest, base::Unretained(file_system_manager_.get())), base::CreateSingleThreadTaskRunnerWithTraits({BrowserThread::IO})); if (Portal::IsEnabled()) { registry_->AddInterface(base::BindRepeating(IgnoreResult(&Portal::Create), base::Unretained(this))); } registry_->AddInterface(base::BindRepeating( &BackgroundFetchServiceImpl::CreateForFrame, GetProcess(), routing_id_)); registry_->AddInterface(base::BindRepeating(&ContactsManagerImpl::Create)); registry_->AddInterface( base::BindRepeating(&FileChooserImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&AudioContextManagerImpl::Create, base::Unretained(this))); registry_->AddInterface(base::BindRepeating(&WakeLockServiceImpl::Create, base::Unretained(this))); }
173,090
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0644); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static int store_asoundrc(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_ASOUNDRC_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0644); fclose(fp); } if (asprintf(&src, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { /* coverity[toctou] */ char* rp = realpath(src, NULL); if (!rp) { fprintf(stderr, "Error: Cannot access %s\n", src); exit(1); } if (strncmp(rp, cfg.homedir, strlen(cfg.homedir)) != 0) { fprintf(stderr, "Error: .asoundrc is a symbolic link pointing to a file outside home directory\n"); exit(1); } free(rp); } copy_file_as_user(src, dest, getuid(), getgid(), 0644); fs_logger2("clone", dest); return 1; // file copied } return 0; }
170,094
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: usage(void) { fprintf(stderr, "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" " [-t life] [command [arg ...]]\n" " ssh-agent [-c | -s] -k\n"); exit(1); } Commit Message: add a whitelist of paths from which ssh-agent will load (via ssh-pkcs11-helper) a PKCS#11 module; ok markus@ CWE ID: CWE-426
usage(void) { fprintf(stderr, "usage: ssh-agent [-c | -s] [-Dd] [-a bind_address] [-E fingerprint_hash]\n" " [-P pkcs11_whitelist] [-t life] [command [arg ...]]\n" " ssh-agent [-c | -s] -k\n"); exit(1); }
168,665
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Segment::AppendCluster(Cluster* pCluster) { assert(pCluster); assert(pCluster->m_index >= 0); const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); const long idx = pCluster->m_index; assert(idx == m_clusterCount); if (count >= size) { const long n = (size <= 0) ? 2048 : 2 * size; Cluster** const qq = new Cluster* [n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } if (m_clusterPreloadCount > 0) { assert(m_clusters); Cluster** const p = m_clusters + m_clusterCount; assert(*p); assert((*p)->m_index < 0); Cluster** q = p + m_clusterPreloadCount; assert(q < (m_clusters + size)); for (;;) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; if (q == p) break; } } m_clusters[idx] = pCluster; ++m_clusterCount; } 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
void Segment::AppendCluster(Cluster* pCluster) { bool Segment::AppendCluster(Cluster* pCluster) { if (pCluster == NULL || pCluster->m_index < 0) return false; const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; const long idx = pCluster->m_index; if (size < count || idx != m_clusterCount) return false; if (count >= size) { const long n = (size <= 0) ? 2048 : 2 * size; Cluster** const qq = new (std::nothrow) Cluster*[n]; if (qq == NULL) return false; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } if (m_clusterPreloadCount > 0) { Cluster** const p = m_clusters + m_clusterCount; if (*p == NULL || (*p)->m_index >= 0) return false; Cluster** q = p + m_clusterPreloadCount; if (q >= (m_clusters + size)) return false; for (;;) { Cluster** const qq = q - 1; if ((*qq)->m_index >= 0) return false; *q = *qq; q = qq; if (q == p) break; } } m_clusters[idx] = pCluster; ++m_clusterCount; return true; }
173,801
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 inet_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct inet_protosw *answer; struct inet_sock *inet; struct proto *answer_prot; unsigned char answer_flags; int try_loading_module = 0; int err; sock->state = SS_UNCONNECTED; /* Look for the requested type/protocol pair. */ lookup_protocol: err = -ESOCKTNOSUPPORT; rcu_read_lock(); list_for_each_entry_rcu(answer, &inetsw[sock->type], list) { err = 0; /* Check the non-wild match. */ if (protocol == answer->protocol) { if (protocol != IPPROTO_IP) break; } else { /* Check for the two wild cases. */ if (IPPROTO_IP == protocol) { protocol = answer->protocol; break; } if (IPPROTO_IP == answer->protocol) break; } err = -EPROTONOSUPPORT; } if (unlikely(err)) { if (try_loading_module < 2) { rcu_read_unlock(); /* * Be more specific, e.g. net-pf-2-proto-132-type-1 * (net-pf-PF_INET-proto-IPPROTO_SCTP-type-SOCK_STREAM) */ if (++try_loading_module == 1) request_module("net-pf-%d-proto-%d-type-%d", PF_INET, protocol, sock->type); /* * Fall back to generic, e.g. net-pf-2-proto-132 * (net-pf-PF_INET-proto-IPPROTO_SCTP) */ else request_module("net-pf-%d-proto-%d", PF_INET, protocol); goto lookup_protocol; } else goto out_rcu_unlock; } err = -EPERM; if (sock->type == SOCK_RAW && !kern && !ns_capable(net->user_ns, CAP_NET_RAW)) goto out_rcu_unlock; sock->ops = answer->ops; answer_prot = answer->prot; answer_flags = answer->flags; rcu_read_unlock(); WARN_ON(!answer_prot->slab); err = -ENOBUFS; sk = sk_alloc(net, PF_INET, GFP_KERNEL, answer_prot, kern); if (!sk) goto out; err = 0; if (INET_PROTOSW_REUSE & answer_flags) sk->sk_reuse = SK_CAN_REUSE; inet = inet_sk(sk); inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0; inet->nodefrag = 0; if (SOCK_RAW == sock->type) { inet->inet_num = protocol; if (IPPROTO_RAW == protocol) inet->hdrincl = 1; } if (net->ipv4.sysctl_ip_no_pmtu_disc) inet->pmtudisc = IP_PMTUDISC_DONT; else inet->pmtudisc = IP_PMTUDISC_WANT; inet->inet_id = 0; sock_init_data(sock, sk); sk->sk_destruct = inet_sock_destruct; sk->sk_protocol = protocol; sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv; inet->uc_ttl = -1; inet->mc_loop = 1; inet->mc_ttl = 1; inet->mc_all = 1; inet->mc_index = 0; inet->mc_list = NULL; inet->rcv_tos = 0; sk_refcnt_debug_inc(sk); if (inet->inet_num) { /* It assumes that any protocol which allows * the user to assign a number at socket * creation time automatically * shares. */ inet->inet_sport = htons(inet->inet_num); /* Add to protocol hash chains. */ sk->sk_prot->hash(sk); } if (sk->sk_prot->init) { err = sk->sk_prot->init(sk); if (err) sk_common_release(sk); } out: return err; out_rcu_unlock: rcu_read_unlock(); goto out; } Commit Message: net: add validation for the socket syscall protocol argument 郭永刚 reported that one could simply crash the kernel as root by using a simple program: int socket_fd; struct sockaddr_in addr; addr.sin_port = 0; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_family = 10; socket_fd = socket(10,3,0x40000000); connect(socket_fd , &addr,16); AF_INET, AF_INET6 sockets actually only support 8-bit protocol identifiers. inet_sock's skc_protocol field thus is sized accordingly, thus larger protocol identifiers simply cut off the higher bits and store a zero in the protocol fields. This could lead to e.g. NULL function pointer because as a result of the cut off inet_num is zero and we call down to inet_autobind, which is NULL for raw sockets. kernel: Call Trace: kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70 kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80 kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110 kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80 kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200 kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10 kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89 I found no particular commit which introduced this problem. CVE: CVE-2015-8543 Cc: Cong Wang <[email protected]> Reported-by: 郭永刚 <[email protected]> Signed-off-by: Hannes Frederic Sowa <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int inet_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct inet_protosw *answer; struct inet_sock *inet; struct proto *answer_prot; unsigned char answer_flags; int try_loading_module = 0; int err; if (protocol < 0 || protocol >= IPPROTO_MAX) return -EINVAL; sock->state = SS_UNCONNECTED; /* Look for the requested type/protocol pair. */ lookup_protocol: err = -ESOCKTNOSUPPORT; rcu_read_lock(); list_for_each_entry_rcu(answer, &inetsw[sock->type], list) { err = 0; /* Check the non-wild match. */ if (protocol == answer->protocol) { if (protocol != IPPROTO_IP) break; } else { /* Check for the two wild cases. */ if (IPPROTO_IP == protocol) { protocol = answer->protocol; break; } if (IPPROTO_IP == answer->protocol) break; } err = -EPROTONOSUPPORT; } if (unlikely(err)) { if (try_loading_module < 2) { rcu_read_unlock(); /* * Be more specific, e.g. net-pf-2-proto-132-type-1 * (net-pf-PF_INET-proto-IPPROTO_SCTP-type-SOCK_STREAM) */ if (++try_loading_module == 1) request_module("net-pf-%d-proto-%d-type-%d", PF_INET, protocol, sock->type); /* * Fall back to generic, e.g. net-pf-2-proto-132 * (net-pf-PF_INET-proto-IPPROTO_SCTP) */ else request_module("net-pf-%d-proto-%d", PF_INET, protocol); goto lookup_protocol; } else goto out_rcu_unlock; } err = -EPERM; if (sock->type == SOCK_RAW && !kern && !ns_capable(net->user_ns, CAP_NET_RAW)) goto out_rcu_unlock; sock->ops = answer->ops; answer_prot = answer->prot; answer_flags = answer->flags; rcu_read_unlock(); WARN_ON(!answer_prot->slab); err = -ENOBUFS; sk = sk_alloc(net, PF_INET, GFP_KERNEL, answer_prot, kern); if (!sk) goto out; err = 0; if (INET_PROTOSW_REUSE & answer_flags) sk->sk_reuse = SK_CAN_REUSE; inet = inet_sk(sk); inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0; inet->nodefrag = 0; if (SOCK_RAW == sock->type) { inet->inet_num = protocol; if (IPPROTO_RAW == protocol) inet->hdrincl = 1; } if (net->ipv4.sysctl_ip_no_pmtu_disc) inet->pmtudisc = IP_PMTUDISC_DONT; else inet->pmtudisc = IP_PMTUDISC_WANT; inet->inet_id = 0; sock_init_data(sock, sk); sk->sk_destruct = inet_sock_destruct; sk->sk_protocol = protocol; sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv; inet->uc_ttl = -1; inet->mc_loop = 1; inet->mc_ttl = 1; inet->mc_all = 1; inet->mc_index = 0; inet->mc_list = NULL; inet->rcv_tos = 0; sk_refcnt_debug_inc(sk); if (inet->inet_num) { /* It assumes that any protocol which allows * the user to assign a number at socket * creation time automatically * shares. */ inet->inet_sport = htons(inet->inet_num); /* Add to protocol hash chains. */ sk->sk_prot->hash(sk); } if (sk->sk_prot->init) { err = sk->sk_prot->init(sk); if (err) sk_common_release(sk); } out: return err; out_rcu_unlock: rcu_read_unlock(); goto out; }
166,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AppCache::InitializeWithDatabaseRecords( const AppCacheDatabase::CacheRecord& cache_record, const std::vector<AppCacheDatabase::EntryRecord>& entries, const std::vector<AppCacheDatabase::NamespaceRecord>& intercepts, const std::vector<AppCacheDatabase::NamespaceRecord>& fallbacks, const std::vector<AppCacheDatabase::OnlineWhiteListRecord>& whitelists) { DCHECK(cache_id_ == cache_record.cache_id); online_whitelist_all_ = cache_record.online_wildcard; update_time_ = cache_record.update_time; for (size_t i = 0; i < entries.size(); ++i) { const AppCacheDatabase::EntryRecord& entry = entries.at(i); AddEntry(entry.url, AppCacheEntry(entry.flags, entry.response_id, entry.response_size)); } DCHECK(cache_size_ == cache_record.cache_size); for (size_t i = 0; i < intercepts.size(); ++i) intercept_namespaces_.push_back(intercepts.at(i).namespace_); for (size_t i = 0; i < fallbacks.size(); ++i) fallback_namespaces_.push_back(fallbacks.at(i).namespace_); std::sort(intercept_namespaces_.begin(), intercept_namespaces_.end(), SortNamespacesByLength); std::sort(fallback_namespaces_.begin(), fallback_namespaces_.end(), SortNamespacesByLength); for (size_t i = 0; i < whitelists.size(); ++i) { const AppCacheDatabase::OnlineWhiteListRecord& record = whitelists.at(i); online_whitelist_namespaces_.push_back( AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE, record.namespace_url, GURL(), record.is_pattern)); } } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void AppCache::InitializeWithDatabaseRecords( const AppCacheDatabase::CacheRecord& cache_record, const std::vector<AppCacheDatabase::EntryRecord>& entries, const std::vector<AppCacheDatabase::NamespaceRecord>& intercepts, const std::vector<AppCacheDatabase::NamespaceRecord>& fallbacks, const std::vector<AppCacheDatabase::OnlineWhiteListRecord>& whitelists) { DCHECK_EQ(cache_id_, cache_record.cache_id); online_whitelist_all_ = cache_record.online_wildcard; update_time_ = cache_record.update_time; for (size_t i = 0; i < entries.size(); ++i) { const AppCacheDatabase::EntryRecord& entry = entries.at(i); AddEntry(entry.url, AppCacheEntry(entry.flags, entry.response_id, entry.response_size, entry.padding_size)); } DCHECK_EQ(cache_size_, cache_record.cache_size); DCHECK_EQ(padding_size_, cache_record.padding_size); for (size_t i = 0; i < intercepts.size(); ++i) intercept_namespaces_.push_back(intercepts.at(i).namespace_); for (size_t i = 0; i < fallbacks.size(); ++i) fallback_namespaces_.push_back(fallbacks.at(i).namespace_); std::sort(intercept_namespaces_.begin(), intercept_namespaces_.end(), SortNamespacesByLength); std::sort(fallback_namespaces_.begin(), fallback_namespaces_.end(), SortNamespacesByLength); for (size_t i = 0; i < whitelists.size(); ++i) { const AppCacheDatabase::OnlineWhiteListRecord& record = whitelists.at(i); online_whitelist_namespaces_.push_back( AppCacheNamespace(APPCACHE_NETWORK_NAMESPACE, record.namespace_url, GURL(), record.is_pattern)); } }
172,970
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *suhosin_decrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key, char **where TSRMLS_DC) { char buffer[4096]; char buffer2[4096]; int o_name_len = name_len; char *buf = buffer, *buf2 = buffer2, *d, *d_url; int l; if (name_len > sizeof(buffer)-2) { buf = estrndup(name, name_len); } else { memcpy(buf, name, name_len); buf[name_len] = 0; } name_len = php_url_decode(buf, name_len); normalize_varname(buf); name_len = strlen(buf); if (SUHOSIN_G(cookie_plainlist)) { if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) { decrypt_return_plain: if (buf != buffer) { efree(buf); } memcpy(*where, name, o_name_len); *where += o_name_len; **where = '='; *where +=1; memcpy(*where, value, value_len); *where += value_len; return *where; } } else if (SUHOSIN_G(cookie_cryptlist)) { if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) { goto decrypt_return_plain; } } if (strlen(value) <= sizeof(buffer2)-2) { memcpy(buf2, value, value_len); buf2[value_len] = 0; } else { buf2 = estrndup(value, value_len); } value_len = php_url_decode(buf2, value_len); d = suhosin_decrypt_string(buf2, value_len, buf, name_len, key, &l, SUHOSIN_G(cookie_checkraddr) TSRMLS_CC); if (d == NULL) { goto skip_cookie; } d_url = php_url_encode(d, l, &l); efree(d); memcpy(*where, name, o_name_len); *where += o_name_len; **where = '=';*where += 1; memcpy(*where, d_url, l); *where += l; efree(d_url); skip_cookie: if (buf != buffer) { efree(buf); } if (buf2 != buffer2) { efree(buf2); } return *where; } Commit Message: Fixed stack based buffer overflow in transparent cookie encryption (see separate advisory) CWE ID: CWE-119
char *suhosin_decrypt_single_cookie(char *name, int name_len, char *value, int value_len, char *key, char **where TSRMLS_DC) { int o_name_len = name_len; char *buf, *buf2, *d, *d_url; int l; buf = estrndup(name, name_len); name_len = php_url_decode(buf, name_len); normalize_varname(buf); name_len = strlen(buf); if (SUHOSIN_G(cookie_plainlist)) { if (zend_hash_exists(SUHOSIN_G(cookie_plainlist), buf, name_len+1)) { decrypt_return_plain: efree(buf); memcpy(*where, name, o_name_len); *where += o_name_len; **where = '='; *where +=1; memcpy(*where, value, value_len); *where += value_len; return *where; } } else if (SUHOSIN_G(cookie_cryptlist)) { if (!zend_hash_exists(SUHOSIN_G(cookie_cryptlist), buf, name_len+1)) { goto decrypt_return_plain; } } buf2 = estrndup(value, value_len); value_len = php_url_decode(buf2, value_len); d = suhosin_decrypt_string(buf2, value_len, buf, name_len, key, &l, SUHOSIN_G(cookie_checkraddr) TSRMLS_CC); if (d == NULL) { goto skip_cookie; } d_url = php_url_encode(d, l, &l); efree(d); memcpy(*where, name, o_name_len); *where += o_name_len; **where = '=';*where += 1; memcpy(*where, d_url, l); *where += l; efree(d_url); skip_cookie: efree(buf); efree(buf2); return *where; }
165,649
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) static double outlog(const png_modifier *pm, int in_depth, int out_depth) { /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) * and so must be adjusted for low bit depth grayscale: */ if (out_depth <= 8) { if (pm->log8 == 0) /* switched off */ return 256; if (out_depth < 8) return pm->log8 / 255 * ((1<<out_depth)-1); return pm->log8; } if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16) { if (pm->log16 == 0) return 65536; return pm->log16; } /* This is the case where the value was calculated at 8-bit precision then * scaled to 16 bits. */ if (pm->log8 == 0) return 65536; return pm->log8 * 257; }
173,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssize_t qib_write(struct file *fp, const char __user *data, size_t count, loff_t *off) { const struct qib_cmd __user *ucmd; struct qib_ctxtdata *rcd; const void __user *src; size_t consumed, copy = 0; struct qib_cmd cmd; ssize_t ret = 0; void *dest; if (count < sizeof(cmd.type)) { ret = -EINVAL; goto bail; } ucmd = (const struct qib_cmd __user *) data; if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) { ret = -EFAULT; goto bail; } consumed = sizeof(cmd.type); switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: case QIB_CMD_USER_INIT: copy = sizeof(cmd.cmd.user_info); dest = &cmd.cmd.user_info; src = &ucmd->cmd.user_info; break; case QIB_CMD_RECV_CTRL: copy = sizeof(cmd.cmd.recv_ctrl); dest = &cmd.cmd.recv_ctrl; src = &ucmd->cmd.recv_ctrl; break; case QIB_CMD_CTXT_INFO: copy = sizeof(cmd.cmd.ctxt_info); dest = &cmd.cmd.ctxt_info; src = &ucmd->cmd.ctxt_info; break; case QIB_CMD_TID_UPDATE: case QIB_CMD_TID_FREE: copy = sizeof(cmd.cmd.tid_info); dest = &cmd.cmd.tid_info; src = &ucmd->cmd.tid_info; break; case QIB_CMD_SET_PART_KEY: copy = sizeof(cmd.cmd.part_key); dest = &cmd.cmd.part_key; src = &ucmd->cmd.part_key; break; case QIB_CMD_DISARM_BUFS: case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */ copy = 0; src = NULL; dest = NULL; break; case QIB_CMD_POLL_TYPE: copy = sizeof(cmd.cmd.poll_type); dest = &cmd.cmd.poll_type; src = &ucmd->cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: copy = sizeof(cmd.cmd.armlaunch_ctrl); dest = &cmd.cmd.armlaunch_ctrl; src = &ucmd->cmd.armlaunch_ctrl; break; case QIB_CMD_SDMA_INFLIGHT: copy = sizeof(cmd.cmd.sdma_inflight); dest = &cmd.cmd.sdma_inflight; src = &ucmd->cmd.sdma_inflight; break; case QIB_CMD_SDMA_COMPLETE: copy = sizeof(cmd.cmd.sdma_complete); dest = &cmd.cmd.sdma_complete; src = &ucmd->cmd.sdma_complete; break; case QIB_CMD_ACK_EVENT: copy = sizeof(cmd.cmd.event_mask); dest = &cmd.cmd.event_mask; src = &ucmd->cmd.event_mask; break; default: ret = -EINVAL; goto bail; } if (copy) { if ((count - consumed) < copy) { ret = -EINVAL; goto bail; } if (copy_from_user(dest, src, copy)) { ret = -EFAULT; goto bail; } consumed += copy; } rcd = ctxt_fp(fp); if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) { ret = -EINVAL; goto bail; } switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: ret = qib_assign_ctxt(fp, &cmd.cmd.user_info); if (ret) goto bail; break; case QIB_CMD_USER_INIT: ret = qib_do_user_init(fp, &cmd.cmd.user_info); if (ret) goto bail; ret = qib_get_base_info(fp, (void __user *) (unsigned long) cmd.cmd.user_info.spu_base_info, cmd.cmd.user_info.spu_base_info_size); break; case QIB_CMD_RECV_CTRL: ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl); break; case QIB_CMD_CTXT_INFO: ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *) (unsigned long) cmd.cmd.ctxt_info); break; case QIB_CMD_TID_UPDATE: ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info); break; case QIB_CMD_TID_FREE: ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info); break; case QIB_CMD_SET_PART_KEY: ret = qib_set_part_key(rcd, cmd.cmd.part_key); break; case QIB_CMD_DISARM_BUFS: (void)qib_disarm_piobufs_ifneeded(rcd); ret = disarm_req_delay(rcd); break; case QIB_CMD_PIOAVAILUPD: qib_force_pio_avail_update(rcd->dd); break; case QIB_CMD_POLL_TYPE: rcd->poll_type = cmd.cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl); break; case QIB_CMD_SDMA_INFLIGHT: ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_inflight); break; case QIB_CMD_SDMA_COMPLETE: ret = qib_sdma_get_complete(rcd->ppd, user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_complete); break; case QIB_CMD_ACK_EVENT: ret = qib_user_event_ack(rcd, subctxt_fp(fp), cmd.cmd.event_mask); break; } if (ret >= 0) ret = consumed; bail: return ret; } Commit Message: IB/security: Restrict use of the write() interface The drivers/infiniband stack uses write() as a replacement for bi-directional ioctl(). This is not safe. There are ways to trigger write calls that result in the return structure that is normally written to user space being shunted off to user specified kernel memory instead. For the immediate repair, detect and deny suspicious accesses to the write API. For long term, update the user space libraries and the kernel API to something that doesn't present the same security vulnerabilities (likely a structured ioctl() interface). The impacted uAPI interfaces are generally only available if hardware from drivers/infiniband is installed in the system. Reported-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Signed-off-by: Jason Gunthorpe <[email protected]> [ Expanded check to all known write() entry points ] Cc: [email protected] Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-264
static ssize_t qib_write(struct file *fp, const char __user *data, size_t count, loff_t *off) { const struct qib_cmd __user *ucmd; struct qib_ctxtdata *rcd; const void __user *src; size_t consumed, copy = 0; struct qib_cmd cmd; ssize_t ret = 0; void *dest; if (WARN_ON_ONCE(!ib_safe_file_access(fp))) return -EACCES; if (count < sizeof(cmd.type)) { ret = -EINVAL; goto bail; } ucmd = (const struct qib_cmd __user *) data; if (copy_from_user(&cmd.type, &ucmd->type, sizeof(cmd.type))) { ret = -EFAULT; goto bail; } consumed = sizeof(cmd.type); switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: case QIB_CMD_USER_INIT: copy = sizeof(cmd.cmd.user_info); dest = &cmd.cmd.user_info; src = &ucmd->cmd.user_info; break; case QIB_CMD_RECV_CTRL: copy = sizeof(cmd.cmd.recv_ctrl); dest = &cmd.cmd.recv_ctrl; src = &ucmd->cmd.recv_ctrl; break; case QIB_CMD_CTXT_INFO: copy = sizeof(cmd.cmd.ctxt_info); dest = &cmd.cmd.ctxt_info; src = &ucmd->cmd.ctxt_info; break; case QIB_CMD_TID_UPDATE: case QIB_CMD_TID_FREE: copy = sizeof(cmd.cmd.tid_info); dest = &cmd.cmd.tid_info; src = &ucmd->cmd.tid_info; break; case QIB_CMD_SET_PART_KEY: copy = sizeof(cmd.cmd.part_key); dest = &cmd.cmd.part_key; src = &ucmd->cmd.part_key; break; case QIB_CMD_DISARM_BUFS: case QIB_CMD_PIOAVAILUPD: /* force an update of PIOAvail reg */ copy = 0; src = NULL; dest = NULL; break; case QIB_CMD_POLL_TYPE: copy = sizeof(cmd.cmd.poll_type); dest = &cmd.cmd.poll_type; src = &ucmd->cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: copy = sizeof(cmd.cmd.armlaunch_ctrl); dest = &cmd.cmd.armlaunch_ctrl; src = &ucmd->cmd.armlaunch_ctrl; break; case QIB_CMD_SDMA_INFLIGHT: copy = sizeof(cmd.cmd.sdma_inflight); dest = &cmd.cmd.sdma_inflight; src = &ucmd->cmd.sdma_inflight; break; case QIB_CMD_SDMA_COMPLETE: copy = sizeof(cmd.cmd.sdma_complete); dest = &cmd.cmd.sdma_complete; src = &ucmd->cmd.sdma_complete; break; case QIB_CMD_ACK_EVENT: copy = sizeof(cmd.cmd.event_mask); dest = &cmd.cmd.event_mask; src = &ucmd->cmd.event_mask; break; default: ret = -EINVAL; goto bail; } if (copy) { if ((count - consumed) < copy) { ret = -EINVAL; goto bail; } if (copy_from_user(dest, src, copy)) { ret = -EFAULT; goto bail; } consumed += copy; } rcd = ctxt_fp(fp); if (!rcd && cmd.type != QIB_CMD_ASSIGN_CTXT) { ret = -EINVAL; goto bail; } switch (cmd.type) { case QIB_CMD_ASSIGN_CTXT: ret = qib_assign_ctxt(fp, &cmd.cmd.user_info); if (ret) goto bail; break; case QIB_CMD_USER_INIT: ret = qib_do_user_init(fp, &cmd.cmd.user_info); if (ret) goto bail; ret = qib_get_base_info(fp, (void __user *) (unsigned long) cmd.cmd.user_info.spu_base_info, cmd.cmd.user_info.spu_base_info_size); break; case QIB_CMD_RECV_CTRL: ret = qib_manage_rcvq(rcd, subctxt_fp(fp), cmd.cmd.recv_ctrl); break; case QIB_CMD_CTXT_INFO: ret = qib_ctxt_info(fp, (struct qib_ctxt_info __user *) (unsigned long) cmd.cmd.ctxt_info); break; case QIB_CMD_TID_UPDATE: ret = qib_tid_update(rcd, fp, &cmd.cmd.tid_info); break; case QIB_CMD_TID_FREE: ret = qib_tid_free(rcd, subctxt_fp(fp), &cmd.cmd.tid_info); break; case QIB_CMD_SET_PART_KEY: ret = qib_set_part_key(rcd, cmd.cmd.part_key); break; case QIB_CMD_DISARM_BUFS: (void)qib_disarm_piobufs_ifneeded(rcd); ret = disarm_req_delay(rcd); break; case QIB_CMD_PIOAVAILUPD: qib_force_pio_avail_update(rcd->dd); break; case QIB_CMD_POLL_TYPE: rcd->poll_type = cmd.cmd.poll_type; break; case QIB_CMD_ARMLAUNCH_CTRL: rcd->dd->f_set_armlaunch(rcd->dd, cmd.cmd.armlaunch_ctrl); break; case QIB_CMD_SDMA_INFLIGHT: ret = qib_sdma_get_inflight(user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_inflight); break; case QIB_CMD_SDMA_COMPLETE: ret = qib_sdma_get_complete(rcd->ppd, user_sdma_queue_fp(fp), (u32 __user *) (unsigned long) cmd.cmd.sdma_complete); break; case QIB_CMD_ACK_EVENT: ret = qib_user_event_ack(rcd, subctxt_fp(fp), cmd.cmd.event_mask); break; } if (ret >= 0) ret = consumed; bail: return ret; }
167,241
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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* Track::GetCodecId() const { return m_info.codecId; } 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* Track::GetCodecId() const
174,293
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB); std::vector<RTCRtpReceiver*> removed_receivers; for (auto it = handler_->rtp_receivers_.begin(); it != handler_->rtp_receivers_.end(); ++it) { if (ReceiverWasRemoved(*(*it), states.transceiver_states)) removed_receivers.push_back(it->get()); } for (auto& transceiver_state : states.transceiver_states) { if (ReceiverWasAdded(transceiver_state)) { handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState()); } } for (auto* removed_receiver : removed_receivers) { handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId( removed_receiver->state().webrtc_receiver().get())); } } Commit Message: Check weak pointers in RTCPeerConnectionHandler::WebRtcSetDescriptionObserverImpl Bug: 912074 Change-Id: I8ba86751f5d5bf12db51520f985ef0d3dae63ed8 Reviewed-on: https://chromium-review.googlesource.com/c/1411916 Commit-Queue: Guido Urdaneta <[email protected]> Reviewed-by: Henrik Boström <[email protected]> Cr-Commit-Position: refs/heads/master@{#622945} CWE ID: CWE-416
void ProcessStateChangesPlanB(WebRtcSetDescriptionObserver::States states) { DCHECK_EQ(sdp_semantics_, webrtc::SdpSemantics::kPlanB); if (!handler_) return; std::vector<RTCRtpReceiver*> removed_receivers; for (auto it = handler_->rtp_receivers_.begin(); it != handler_->rtp_receivers_.end(); ++it) { if (ReceiverWasRemoved(*(*it), states.transceiver_states)) removed_receivers.push_back(it->get()); } for (auto& transceiver_state : states.transceiver_states) { if (handler_ && ReceiverWasAdded(transceiver_state)) { // |handler_| can become null after this call. handler_->OnAddReceiverPlanB(transceiver_state.MoveReceiverState()); } } for (auto* removed_receiver : removed_receivers) { if (handler_) { // |handler_| can become null after this call. handler_->OnRemoveReceiverPlanB(RTCRtpReceiver::getId( removed_receiver->state().webrtc_receiver().get())); } } }
173,074
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len) { int n; int n_read = 0; int fd = uipc_main.ch[ch_id].fd; struct pollfd pfd; UNUSED(p_msg_evt); if (ch_id >= UIPC_CH_NUM) { BTIF_TRACE_ERROR("UIPC_Read : invalid ch id %d", ch_id); return 0; } if (fd == UIPC_DISCONNECTED) { BTIF_TRACE_ERROR("UIPC_Read : channel %d closed", ch_id); return 0; } while (n_read < (int)len) { pfd.fd = fd; pfd.events = POLLIN|POLLHUP; /* make sure there is data prior to attempting read to avoid blocking a read for more than poll timeout */ if (poll(&pfd, 1, uipc_main.ch[ch_id].read_poll_tmo_ms) == 0) { BTIF_TRACE_EVENT("poll timeout (%d ms)", uipc_main.ch[ch_id].read_poll_tmo_ms); break; } if (pfd.revents & (POLLHUP|POLLNVAL) ) { BTIF_TRACE_EVENT("poll : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } n = recv(fd, p_buf+n_read, len-n_read, 0); if (n == 0) { BTIF_TRACE_EVENT("UIPC_Read : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } if (n < 0) { BTIF_TRACE_EVENT("UIPC_Read : read failed (%s)", strerror(errno)); return 0; } n_read+=n; } return n_read; } 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
UINT32 UIPC_Read(tUIPC_CH_ID ch_id, UINT16 *p_msg_evt, UINT8 *p_buf, UINT32 len) { int n; int n_read = 0; int fd = uipc_main.ch[ch_id].fd; struct pollfd pfd; UNUSED(p_msg_evt); if (ch_id >= UIPC_CH_NUM) { BTIF_TRACE_ERROR("UIPC_Read : invalid ch id %d", ch_id); return 0; } if (fd == UIPC_DISCONNECTED) { BTIF_TRACE_ERROR("UIPC_Read : channel %d closed", ch_id); return 0; } while (n_read < (int)len) { pfd.fd = fd; pfd.events = POLLIN|POLLHUP; /* make sure there is data prior to attempting read to avoid blocking a read for more than poll timeout */ if (TEMP_FAILURE_RETRY(poll(&pfd, 1, uipc_main.ch[ch_id].read_poll_tmo_ms)) == 0) { BTIF_TRACE_EVENT("poll timeout (%d ms)", uipc_main.ch[ch_id].read_poll_tmo_ms); break; } if (pfd.revents & (POLLHUP|POLLNVAL) ) { BTIF_TRACE_EVENT("poll : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } n = TEMP_FAILURE_RETRY(recv(fd, p_buf+n_read, len-n_read, 0)); if (n == 0) { BTIF_TRACE_EVENT("UIPC_Read : channel detached remotely"); UIPC_LOCK(); uipc_close_locked(ch_id); UIPC_UNLOCK(); return 0; } if (n < 0) { BTIF_TRACE_EVENT("UIPC_Read : read failed (%s)", strerror(errno)); return 0; } n_read+=n; } return n_read; }
173,493
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; } Commit Message: net: validate the range we feed to iov_iter_init() in sys_sendto/sys_recvfrom Cc: [email protected] # v3.19 Signed-off-by: Al Viro <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-264
SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; if (unlikely(!access_ok(VERIFY_READ, buff, len))) return -EFAULT; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; iov_iter_init(&msg.msg_iter, WRITE, &iov, 1, len); msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; }
167,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WarmupURLFetcher::WarmupURLFetcher( CreateCustomProxyConfigCallback create_custom_proxy_config_callback, WarmupURLFetcherCallback callback, GetHttpRttCallback get_http_rtt_callback, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, const std::string& user_agent) : is_fetch_in_flight_(false), previous_attempt_counts_(0), create_custom_proxy_config_callback_(create_custom_proxy_config_callback), callback_(callback), get_http_rtt_callback_(get_http_rtt_callback), user_agent_(user_agent), ui_task_runner_(ui_task_runner) { DCHECK(create_custom_proxy_config_callback); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <[email protected]> Reviewed-by: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
WarmupURLFetcher::WarmupURLFetcher( CreateCustomProxyConfigCallback create_custom_proxy_config_callback, WarmupURLFetcherCallback callback, GetHttpRttCallback get_http_rtt_callback, scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner, const std::string& user_agent) : is_fetch_in_flight_(false), previous_attempt_counts_(0), create_custom_proxy_config_callback_(create_custom_proxy_config_callback), callback_(callback), get_http_rtt_callback_(get_http_rtt_callback), user_agent_(user_agent), ui_task_runner_(ui_task_runner) { DCHECK(create_custom_proxy_config_callback); DCHECK(!params::IsIncludedInHoldbackFieldTrial()); }
172,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck * continually regenerating the same prime values. */ if (bits < 16) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; bitsp = (bits + 1) / 2; bitsq = bits - bitsp; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL)) goto err; if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL)) goto err; if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL)) goto err; if (BN_copy(rsa->e, e_value) == NULL) goto err; BN_set_flags(r2, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 0)) goto err; for (;;) { do { if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb)) goto err; } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate n */ if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ { BIGNUM *pr0 = BN_new(); if (pr0 == NULL) goto err; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) { BN_free(pr0); goto err; /* d */ } /* We MUST free pr0 before any further use of r0 */ BN_free(pr0); } { BIGNUM *d = BN_new(); if (d == NULL) goto err; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); if ( /* calculate d mod (p-1) */ !BN_mod(rsa->dmp1, d, r1, ctx) /* calculate d mod (q-1) */ || !BN_mod(rsa->dmq1, d, r2, ctx)) { BN_free(d); goto err; } /* We MUST free d before any further use of rsa->d */ BN_free(d); } { BIGNUM *p = BN_new(); if (p == NULL) goto err; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); /* calculate inverse of q mod p */ if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) { BN_free(p); goto err; } /* We MUST free p before any further use of rsa->p */ BN_free(p); } ok = 1; err: if (ok == -1) { RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN); ok = 0; } if (ctx != NULL) BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } Commit Message: CWE ID: CWE-327
static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck * continually regenerating the same prime values. */ if (bits < 16) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; bitsp = (bits + 1) / 2; bitsq = bits - bitsp; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL)) goto err; if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL)) goto err; if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL)) goto err; if (BN_copy(rsa->e, e_value) == NULL) goto err; BN_set_flags(rsa->p, BN_FLG_CONSTTIME); BN_set_flags(rsa->q, BN_FLG_CONSTTIME); BN_set_flags(r2, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 0)) goto err; for (;;) { do { if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb)) goto err; } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate n */ if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ { BIGNUM *pr0 = BN_new(); if (pr0 == NULL) goto err; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) { BN_free(pr0); goto err; /* d */ } /* We MUST free pr0 before any further use of r0 */ BN_free(pr0); } { BIGNUM *d = BN_new(); if (d == NULL) goto err; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); if ( /* calculate d mod (p-1) */ !BN_mod(rsa->dmp1, d, r1, ctx) /* calculate d mod (q-1) */ || !BN_mod(rsa->dmq1, d, r2, ctx)) { BN_free(d); goto err; } /* We MUST free d before any further use of rsa->d */ BN_free(d); } { BIGNUM *p = BN_new(); if (p == NULL) goto err; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); /* calculate inverse of q mod p */ if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) { BN_free(p); goto err; } /* We MUST free p before any further use of rsa->p */ BN_free(p); } ok = 1; err: if (ok == -1) { RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN); ok = 0; } if (ctx != NULL) BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; }
165,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void get_checksum2(char *buf, int32 len, char *sum) { md_context m; switch (xfersum_type) { case CSUM_MD5: { uchar seedbuf[4]; md5_begin(&m); if (proper_seed_order) { if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } md5_update(&m, (uchar *)buf, len); } else { md5_update(&m, (uchar *)buf, len); if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } } md5_result(&m, (uchar *)sum); break; } case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: { int32 i; static char *buf1; static int32 len1; mdfour_begin(&m); if (len > len1) { if (buf1) free(buf1); buf1 = new_array(char, len+4); len1 = len; if (!buf1) out_of_memory("get_checksum2"); } memcpy(buf1, buf, len); if (checksum_seed) { SIVAL(buf1,len,checksum_seed); len += 4; } for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) mdfour_update(&m, (uchar *)(buf1+i), CSUM_CHUNK); /* * Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ if (len - i > 0 || xfersum_type != CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)(buf1+i), len-i); mdfour_result(&m, (uchar *)sum); } } } Commit Message: CWE ID: CWE-354
void get_checksum2(char *buf, int32 len, char *sum) { md_context m; switch (xfersum_type) { case CSUM_MD5: { uchar seedbuf[4]; md5_begin(&m); if (proper_seed_order) { if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } md5_update(&m, (uchar *)buf, len); } else { md5_update(&m, (uchar *)buf, len); if (checksum_seed) { SIVALu(seedbuf, 0, checksum_seed); md5_update(&m, seedbuf, 4); } } md5_result(&m, (uchar *)sum); break; } case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: case CSUM_MD4_ARCHAIC: { int32 i; static char *buf1; static int32 len1; mdfour_begin(&m); if (len > len1) { if (buf1) free(buf1); buf1 = new_array(char, len+4); len1 = len; if (!buf1) out_of_memory("get_checksum2"); } memcpy(buf1, buf, len); if (checksum_seed) { SIVAL(buf1,len,checksum_seed); len += 4; } for (i = 0; i + CSUM_CHUNK <= len; i += CSUM_CHUNK) mdfour_update(&m, (uchar *)(buf1+i), CSUM_CHUNK); /* * Prior to version 27 an incorrect MD4 checksum was computed * by failing to call mdfour_tail() for block sizes that * are multiples of 64. This is fixed by calling mdfour_update() * are multiples of 64. This is fixed by calling mdfour_update() * even when there are no more bytes. */ if (len - i > 0 || xfersum_type > CSUM_MD4_BUSTED) mdfour_update(&m, (uchar *)(buf1+i), len-i); mdfour_result(&m, (uchar *)sum); } } }
164,644
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: perform_formatting_test(png_store *volatile ps) { #ifdef PNG_TIME_RFC1123_SUPPORTED /* The handle into the formatting code is the RFC1123 support; this test does * nothing if that is compiled out. */ context(ps, fault); Try { png_const_charp correct = "29 Aug 2079 13:53:60 +0000"; png_const_charp result; # if PNG_LIBPNG_VER >= 10600 char timestring[29]; # endif png_structp pp; png_time pt; pp = set_store_for_write(ps, NULL, "libpng formatting test"); if (pp == NULL) Throw ps; /* Arbitrary settings: */ pt.year = 2079; pt.month = 8; pt.day = 29; pt.hour = 13; pt.minute = 53; pt.second = 60; /* a leap second */ # if PNG_LIBPNG_VER < 10600 result = png_convert_to_rfc1123(pp, &pt); # else if (png_convert_to_rfc1123_buffer(timestring, &pt)) result = timestring; else result = NULL; # endif if (result == NULL) png_error(pp, "png_convert_to_rfc1123 failed"); if (strcmp(result, correct) != 0) { size_t pos = 0; char msg[128]; pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123("); pos = safecat(msg, sizeof msg, pos, correct); pos = safecat(msg, sizeof msg, pos, ") returned: '"); pos = safecat(msg, sizeof msg, pos, result); pos = safecat(msg, sizeof msg, pos, "'"); png_error(pp, msg); } store_write_reset(ps); } Catch(fault) { store_write_reset(fault); } #else UNUSED(ps) #endif } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
perform_formatting_test(png_store *volatile ps) perform_formatting_test(png_store *ps) { #ifdef PNG_TIME_RFC1123_SUPPORTED /* The handle into the formatting code is the RFC1123 support; this test does * nothing if that is compiled out. */ context(ps, fault); Try { png_const_charp correct = "29 Aug 2079 13:53:60 +0000"; png_const_charp result; # if PNG_LIBPNG_VER >= 10600 char timestring[29]; # endif png_structp pp; png_time pt; pp = set_store_for_write(ps, NULL, "libpng formatting test"); if (pp == NULL) Throw ps; /* Arbitrary settings: */ pt.year = 2079; pt.month = 8; pt.day = 29; pt.hour = 13; pt.minute = 53; pt.second = 60; /* a leap second */ # if PNG_LIBPNG_VER < 10600 result = png_convert_to_rfc1123(pp, &pt); # else if (png_convert_to_rfc1123_buffer(timestring, &pt)) result = timestring; else result = NULL; # endif if (result == NULL) png_error(pp, "png_convert_to_rfc1123 failed"); if (strcmp(result, correct) != 0) { size_t pos = 0; char msg[128]; pos = safecat(msg, sizeof msg, pos, "png_convert_to_rfc1123("); pos = safecat(msg, sizeof msg, pos, correct); pos = safecat(msg, sizeof msg, pos, ") returned: '"); pos = safecat(msg, sizeof msg, pos, result); pos = safecat(msg, sizeof msg, pos, "'"); png_error(pp, msg); } store_write_reset(ps); } Catch(fault) { store_write_reset(fault); } #else UNUSED(ps) #endif }
173,678
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: QuicConnectionHelperTest() : framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)), creator_(guid_, &framer_), net_log_(BoundNetLog()), scheduler_(new MockScheduler()), socket_(&empty_data_, net_log_.net_log()), runner_(new TestTaskRunner(&clock_)), helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)), connection_(guid_, IPEndPoint(), helper_), frame1_(1, false, 0, data1) { connection_.set_visitor(&visitor_); connection_.SetScheduler(scheduler_); } Commit Message: Fix uninitialized access in QuicConnectionHelperTest BUG=159928 Review URL: https://chromiumcodereview.appspot.com/11360153 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@166708 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
QuicConnectionHelperTest() : guid_(0), framer_(QuicDecrypter::Create(kNULL), QuicEncrypter::Create(kNULL)), creator_(guid_, &framer_), net_log_(BoundNetLog()), scheduler_(new MockScheduler()), socket_(&empty_data_, net_log_.net_log()), runner_(new TestTaskRunner(&clock_)), helper_(new TestConnectionHelper(runner_.get(), &clock_, &socket_)), connection_(guid_, IPEndPoint(), helper_), frame1_(1, false, 0, data1) { connection_.set_visitor(&visitor_); connection_.SetScheduler(scheduler_); }
171,411
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev1_vid_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_VID))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_VID))); return NULL; }
167,795
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept, uint8_t pin_len, bt_pin_code_t *pin_code) { BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept); if (pin_code == NULL) return BT_STATUS_FAIL; #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) if (pairing_cb.is_le_only) { int i; UINT32 passkey = 0; int multi[] = {100000, 10000, 1000, 100, 10,1}; BD_ADDR remote_bd_addr; bdcpy(remote_bd_addr, bd_addr->address); for (i = 0; i < 6; i++) { passkey += (multi[i] * (pin_code->pin[i] - '0')); } BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey); BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey); } else { BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin); if (accept) pairing_cb.pin_code_len = pin_len; } #else BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin); if (accept) pairing_cb.pin_code_len = pin_len; #endif return BT_STATUS_SUCCESS; } Commit Message: DO NOT MERGE Check size of pin before replying If a malicious client set a pin that was too long it would overflow the pin code memory. Bug: 27411268 Change-Id: I9197ac6fdaa92a4799dacb6364e04671a39450cc CWE ID: CWE-119
bt_status_t btif_dm_pin_reply( const bt_bdaddr_t *bd_addr, uint8_t accept, uint8_t pin_len, bt_pin_code_t *pin_code) { BTIF_TRACE_EVENT("%s: accept=%d", __FUNCTION__, accept); if (pin_code == NULL || pin_len > PIN_CODE_LEN) return BT_STATUS_FAIL; #if (defined(BLE_INCLUDED) && (BLE_INCLUDED == TRUE)) if (pairing_cb.is_le_only) { int i; UINT32 passkey = 0; int multi[] = {100000, 10000, 1000, 100, 10,1}; BD_ADDR remote_bd_addr; bdcpy(remote_bd_addr, bd_addr->address); for (i = 0; i < 6; i++) { passkey += (multi[i] * (pin_code->pin[i] - '0')); } BTIF_TRACE_DEBUG("btif_dm_pin_reply: passkey: %d", passkey); BTA_DmBlePasskeyReply(remote_bd_addr, accept, passkey); } else { BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin); if (accept) pairing_cb.pin_code_len = pin_len; } #else BTA_DmPinReply( (UINT8 *)bd_addr->address, accept, pin_len, pin_code->pin); if (accept) pairing_cb.pin_code_len = pin_len; #endif return BT_STATUS_SUCCESS; }
173,886
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const { return x >= frameLeft && x <= frameRight && y >= frameTop && y <= frameBottom; } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264
bool InputWindowInfo::frameContainsPoint(int32_t x, int32_t y) const { return x >= frameLeft && x < frameRight && y >= frameTop && y < frameBottom; }
174,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 http_connect(http_subtransport *t) { int error; char *proxy_url; if (t->connected && http_should_keep_alive(&t->parser) && t->parse_finished) return 0; if (t->io) { git_stream_close(t->io); git_stream_free(t->io); t->io = NULL; t->connected = 0; } if (t->connection_data.use_ssl) { error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port); } else { #ifdef GIT_CURL error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #else error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #endif } if (error < 0) return error; GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream"); if (git_stream_supports_proxy(t->io) && !git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url)) { error = git_stream_set_proxy(t->io, proxy_url); git__free(proxy_url); if (error < 0) return error; } error = git_stream_connect(t->io); #if defined(GIT_OPENSSL) || defined(GIT_SECURE_TRANSPORT) || defined(GIT_CURL) if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL && git_stream_is_encrypted(t->io)) { git_cert *cert; int is_valid; if ((error = git_stream_certificate(&cert, t->io)) < 0) return error; giterr_clear(); is_valid = error != GIT_ECERTIFICATE; error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload); if (error < 0) { if (!giterr_last()) giterr_set(GITERR_NET, "user cancelled certificate check"); return error; } } #endif if (error < 0) return error; t->connected = 1; return 0; } Commit Message: http: check certificate validity before clobbering the error variable CWE ID: CWE-284
static int http_connect(http_subtransport *t) { int error; char *proxy_url; if (t->connected && http_should_keep_alive(&t->parser) && t->parse_finished) return 0; if (t->io) { git_stream_close(t->io); git_stream_free(t->io); t->io = NULL; t->connected = 0; } if (t->connection_data.use_ssl) { error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port); } else { #ifdef GIT_CURL error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #else error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port); #endif } if (error < 0) return error; GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream"); if (git_stream_supports_proxy(t->io) && !git_remote__get_http_proxy(t->owner->owner, !!t->connection_data.use_ssl, &proxy_url)) { error = git_stream_set_proxy(t->io, proxy_url); git__free(proxy_url); if (error < 0) return error; } error = git_stream_connect(t->io); #if defined(GIT_OPENSSL) || defined(GIT_SECURE_TRANSPORT) || defined(GIT_CURL) if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL && git_stream_is_encrypted(t->io)) { git_cert *cert; int is_valid = (error == GIT_OK); if ((error = git_stream_certificate(&cert, t->io)) < 0) return error; giterr_clear(); error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload); if (error < 0) { if (!giterr_last()) giterr_set(GITERR_NET, "user cancelled certificate check"); return error; } } #endif if (error < 0) return error; t->connected = 1; return 0; }
170,109
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InputMethodDescriptor previous_input_method() const { if (previous_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return previous_input_method_; } 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 InputMethodDescriptor previous_input_method() const { virtual input_method::InputMethodDescriptor previous_input_method() const { if (previous_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return previous_input_method_; }
170,514
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 buffer_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; ref->ref++; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static void buffer_pipe_buf_get(struct pipe_inode_info *pipe, static bool buffer_pipe_buf_get(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct buffer_ref *ref = (struct buffer_ref *)buf->private; if (ref->ref > INT_MAX/2) return false; ref->ref++; return true; }
170,221
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: size_t OpenMP4SourceUDTA(char *filename) { mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object)); if (mp4 == NULL) return 0; memset(mp4, 0, sizeof(mp4object)); #ifdef _WINDOWS fopen_s(&mp4->mediafp, filename, "rb"); #else mp4->mediafp = fopen(filename, "rb"); #endif if (mp4->mediafp) { uint32_t qttag, qtsize32, len; int32_t nest = 0; uint64_t nestsize[MAX_NEST_LEVEL] = { 0 }; uint64_t lastsize = 0, qtsize; do { len = fread(&qtsize32, 1, 4, mp4->mediafp); len += fread(&qttag, 1, 4, mp4->mediafp); if (len == 8) { if (!GPMF_VALID_FOURCC(qttag)) { LONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR); NESTSIZE(lastsize - 8); continue; } qtsize32 = BYTESWAP32(qtsize32); if (qtsize32 == 1) // 64-bit Atom { fread(&qtsize, 1, 8, mp4->mediafp); qtsize = BYTESWAP64(qtsize) - 8; } else qtsize = qtsize32; nest++; if (qtsize < 8) break; if (nest >= MAX_NEST_LEVEL) break; nestsize[nest] = qtsize; lastsize = qtsize; if (qttag == MAKEID('m', 'd', 'a', 't') || qttag == MAKEID('f', 't', 'y', 'p')) { LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); continue; } if (qttag == MAKEID('G', 'P', 'M', 'F')) { mp4->videolength += 1.0; mp4->metadatalength += 1.0; mp4->indexcount = (int)mp4->metadatalength; mp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4); mp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8); mp4->metasizes[0] = (int)qtsize - 8; mp4->metaoffsets[0] = ftell(mp4->mediafp); mp4->metasize_count = 1; return (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second. } if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms qttag != MAKEID('u', 'd', 't', 'a')) { LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); NESTSIZE(qtsize); continue; } else { NESTSIZE(8); } } } while (len > 0); } return (size_t)mp4; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
size_t OpenMP4SourceUDTA(char *filename) { mp4object *mp4 = (mp4object *)malloc(sizeof(mp4object)); if (mp4 == NULL) return 0; memset(mp4, 0, sizeof(mp4object)); #ifdef _WINDOWS fopen_s(&mp4->mediafp, filename, "rb"); #else mp4->mediafp = fopen(filename, "rb"); #endif if (mp4->mediafp) { uint32_t qttag, qtsize32; size_t len; int32_t nest = 0; uint64_t nestsize[MAX_NEST_LEVEL] = { 0 }; uint64_t lastsize = 0, qtsize; do { len = fread(&qtsize32, 1, 4, mp4->mediafp); len += fread(&qttag, 1, 4, mp4->mediafp); if (len == 8) { if (!GPMF_VALID_FOURCC(qttag)) { LongSeek(mp4, lastsize - 8 - 8); NESTSIZE(lastsize - 8); continue; } qtsize32 = BYTESWAP32(qtsize32); if (qtsize32 == 1) // 64-bit Atom { fread(&qtsize, 1, 8, mp4->mediafp); qtsize = BYTESWAP64(qtsize) - 8; } else qtsize = qtsize32; nest++; if (qtsize < 8) break; if (nest >= MAX_NEST_LEVEL) break; nestsize[nest] = qtsize; lastsize = qtsize; if (qttag == MAKEID('m', 'd', 'a', 't') || qttag == MAKEID('f', 't', 'y', 'p')) { LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); continue; } if (qttag == MAKEID('G', 'P', 'M', 'F')) { mp4->videolength += 1.0; mp4->metadatalength += 1.0; mp4->indexcount = (int)mp4->metadatalength; mp4->metasizes = (uint32_t *)malloc(mp4->indexcount * 4 + 4); memset(mp4->metasizes, 0, mp4->indexcount * 4 + 4); mp4->metaoffsets = (uint64_t *)malloc(mp4->indexcount * 8 + 8); memset(mp4->metaoffsets, 0, mp4->indexcount * 8 + 8); mp4->metasizes[0] = (int)qtsize - 8; mp4->metaoffsets[0] = ftell(mp4->mediafp); mp4->metasize_count = 1; return (size_t)mp4; // not an MP4, RAW GPMF which has not inherent timing, assigning a during of 1second. } if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms qttag != MAKEID('u', 'd', 't', 'a')) { LongSeek(mp4, qtsize - 8); NESTSIZE(qtsize); continue; } else { NESTSIZE(8); } } } while (len > 0); } return (size_t)mp4; }
169,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WallpaperManager::DoSetDefaultWallpaper( const AccountId& account_id, MovableOnDestroyCallbackHolder on_finish) { if (user_manager::UserManager::Get()->IsLoggedInAsKioskApp()) return; wallpaper_cache_.erase(account_id); WallpaperResolution resolution = GetAppropriateResolution(); const bool use_small = (resolution == WALLPAPER_RESOLUTION_SMALL); const base::FilePath* file = NULL; const user_manager::User* user = user_manager::UserManager::Get()->FindUser(account_id); if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) { file = use_small ? &guest_small_wallpaper_file_ : &guest_large_wallpaper_file_; } else if (user && user->GetType() == user_manager::USER_TYPE_CHILD) { file = use_small ? &child_small_wallpaper_file_ : &child_large_wallpaper_file_; } else { file = use_small ? &default_small_wallpaper_file_ : &default_large_wallpaper_file_; } wallpaper::WallpaperLayout layout = use_small ? wallpaper::WALLPAPER_LAYOUT_CENTER : wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED; DCHECK(file); if (!default_wallpaper_image_.get() || default_wallpaper_image_->file_path() != *file) { default_wallpaper_image_.reset(); if (!file->empty()) { loaded_wallpapers_for_test_++; StartLoadAndSetDefaultWallpaper(*file, layout, std::move(on_finish), &default_wallpaper_image_); return; } CreateSolidDefaultWallpaper(); } if (default_wallpaper_image_->image().width() == 1 && default_wallpaper_image_->image().height() == 1) layout = wallpaper::WALLPAPER_LAYOUT_STRETCH; WallpaperInfo info(default_wallpaper_image_->file_path().value(), layout, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetWallpaper(default_wallpaper_image_->image(), info); } Commit Message: [reland] Do not set default wallpaper unless it should do so. [email protected], [email protected] Bug: 751382 Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda Reviewed-on: https://chromium-review.googlesource.com/619754 Commit-Queue: Xiaoqian Dai <[email protected]> Reviewed-by: Alexander Alekseev <[email protected]> Reviewed-by: Biao She <[email protected]> Cr-Original-Commit-Position: refs/heads/master@{#498325} Reviewed-on: https://chromium-review.googlesource.com/646430 Cr-Commit-Position: refs/heads/master@{#498982} CWE ID: CWE-200
void WallpaperManager::DoSetDefaultWallpaper( const AccountId& account_id, bool update_wallpaper, MovableOnDestroyCallbackHolder on_finish) { if (user_manager::UserManager::Get()->IsLoggedInAsKioskApp()) return; wallpaper_cache_.erase(account_id); WallpaperResolution resolution = GetAppropriateResolution(); const bool use_small = (resolution == WALLPAPER_RESOLUTION_SMALL); const base::FilePath* file = NULL; const user_manager::User* user = user_manager::UserManager::Get()->FindUser(account_id); if (user_manager::UserManager::Get()->IsLoggedInAsGuest()) { file = use_small ? &guest_small_wallpaper_file_ : &guest_large_wallpaper_file_; } else if (user && user->GetType() == user_manager::USER_TYPE_CHILD) { file = use_small ? &child_small_wallpaper_file_ : &child_large_wallpaper_file_; } else { file = use_small ? &default_small_wallpaper_file_ : &default_large_wallpaper_file_; } wallpaper::WallpaperLayout layout = use_small ? wallpaper::WALLPAPER_LAYOUT_CENTER : wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED; DCHECK(file); if (!default_wallpaper_image_.get() || default_wallpaper_image_->file_path() != *file) { default_wallpaper_image_.reset(); if (!file->empty()) { loaded_wallpapers_for_test_++; StartLoadAndSetDefaultWallpaper(*file, layout, update_wallpaper, std::move(on_finish), &default_wallpaper_image_); return; } CreateSolidDefaultWallpaper(); } if (update_wallpaper) { // 1x1 wallpaper is actually solid color, so it should be stretched. if (default_wallpaper_image_->image().width() == 1 && default_wallpaper_image_->image().height() == 1) { layout = wallpaper::WALLPAPER_LAYOUT_STRETCH; } WallpaperInfo info(default_wallpaper_image_->file_path().value(), layout, wallpaper::DEFAULT, base::Time::Now().LocalMidnight()); SetWallpaper(default_wallpaper_image_->image(), info); } }
171,966
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::DidFinishPrinting(PrintingResult result) { bool store_print_pages_params = true; if (result == FAIL_PRINT) { DisplayPrintJobError(); if (notify_browser_of_print_failure_ && print_pages_params_.get()) { int cookie = print_pages_params_->params.document_cookie; Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie)); } } else if (result == FAIL_PREVIEW) { DCHECK(is_preview_); store_print_pages_params = false; int cookie = print_pages_params_->params.document_cookie; if (notify_browser_of_print_failure_) Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie)); else Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie)); print_preview_context_.Failed(notify_browser_of_print_failure_); } if (print_web_view_) { print_web_view_->close(); print_web_view_ = NULL; } if (store_print_pages_params) { old_print_pages_params_.reset(print_pages_params_.release()); } else { print_pages_params_.reset(); old_print_pages_params_.reset(); } notify_browser_of_print_failure_ = true; } Commit Message: Fix print preview workflow to reflect settings of selected printer. BUG=95110 TEST=none Review URL: http://codereview.chromium.org/7831041 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void PrintWebViewHelper::DidFinishPrinting(PrintingResult result) { bool store_print_pages_params = true; if (result == FAIL_PRINT) { DisplayPrintJobError(); if (notify_browser_of_print_failure_ && print_pages_params_.get()) { int cookie = print_pages_params_->params.document_cookie; Send(new PrintHostMsg_PrintingFailed(routing_id(), cookie)); } } else if (result == FAIL_PREVIEW) { DCHECK(is_preview_); store_print_pages_params = false; int cookie = print_pages_params_.get() ? print_pages_params_->params.document_cookie : 0; if (notify_browser_of_print_failure_) Send(new PrintHostMsg_PrintPreviewFailed(routing_id(), cookie)); else Send(new PrintHostMsg_PrintPreviewCancelled(routing_id(), cookie)); print_preview_context_.Failed(notify_browser_of_print_failure_); } if (print_web_view_) { print_web_view_->close(); print_web_view_ = NULL; } if (store_print_pages_params) { old_print_pages_params_.reset(print_pages_params_.release()); } else { print_pages_params_.reset(); old_print_pages_params_.reset(); } notify_browser_of_print_failure_ = true; }
170,258
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, "%d", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError("Could not create lock file in %s\n", tmp); (void) sprintf(pid_str, "%10ld\n", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY); if (lfd < 0) { unlink(tmp); FatalError("Can't read lock file %s\n", LockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\0'; sscanf(pid_str, "%d", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", LockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) FatalError("Could not create server lock file: %s\n", LockFile); StillLocking = FALSE; } Commit Message: CWE ID: CWE-59
LockServer(void) { char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; sprintf(port, "%d", atoi(display)); len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; if (len > sizeof(LockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times * to create the file. */ StillLocking = TRUE; i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); if (lfd < 0) { unlink(tmp); i = 0; do { i++; lfd = open(tmp, O_CREAT | O_EXCL | O_WRONLY, 0644); if (lfd < 0) sleep(2); else break; } while (i < 3); } if (lfd < 0) FatalError("Could not create lock file in %s\n", tmp); (void) sprintf(pid_str, "%10ld\n", (long)getpid()); (void) write(lfd, pid_str, 11); (void) chmod(tmp, 0444); (void) close(lfd); /* * OK. Now the tmp file exists. Try three times to move it in place * for the lock. */ i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { haslock = (link(tmp,LockFile) == 0); if (haslock) { /* * We're done. */ break; } else { /* * Read the pid from the existing file */ lfd = open(LockFile, O_RDONLY|O_NOFOLLOW); if (lfd < 0) { unlink(tmp); FatalError("Can't read lock file %s\n", LockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ unlink(LockFile); close(lfd); continue; } pid_str[11] = '\0'; sscanf(pid_str, "%d", &l_pid); close(lfd); /* * Now try to kill the PID to see if it exists. */ errno = 0; t = kill(l_pid, 0); if ((t< 0) && (errno == ESRCH)) { /* * Stale lock file. */ unlink(LockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { /* * Process is still active. */ unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", LockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) FatalError("Could not create server lock file: %s\n", LockFile); StillLocking = FALSE; }
165,237
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: checked_xcalloc (size_t num, size_t size) { alloc_limit_assert ("checked_xcalloc", (num *size)); return xcalloc (num, size); } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
checked_xcalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); alloc_limit_assert ("checked_xcalloc", (res)); return xcalloc (num, size); }
168,356
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), 0600); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); return 1; // file copied } return 0; } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static int store_xauthority(void) { fs_build_mnt_dir(); char *src; char *dest = RUN_XAUTHORITY_FILE; FILE *fp = fopen(dest, "w"); if (fp) { fprintf(fp, "\n"); SET_PERMS_STREAM(fp, getuid(), getgid(), 0600); fclose(fp); } if (asprintf(&src, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); struct stat s; if (stat(src, &s) == 0) { if (is_link(src)) { fprintf(stderr, "Warning: invalid .Xauthority file\n"); return 0; } copy_file_as_user(src, dest, getuid(), getgid(), 0600); fs_logger2("clone", dest); return 1; // file copied } return 0; }
170,095
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bandwidth_pid(pid_t pid, const char *command, const char *dev, int down, int up) { EUID_ASSERT(); EUID_ROOT(); char *comm = pid_proc_comm(pid); EUID_USER(); if (!comm) { fprintf(stderr, "Error: cannot find sandbox\n"); exit(1); } if (strcmp(comm, "firejail") != 0) { fprintf(stderr, "Error: cannot find sandbox\n"); exit(1); } free(comm); char *name; if (asprintf(&name, "/run/firejail/network/%d-netmap", pid) == -1) errExit("asprintf"); struct stat s; if (stat(name, &s) == -1) { fprintf(stderr, "Error: the sandbox doesn't use a new network namespace\n"); exit(1); } pid_t child; if (find_child(pid, &child) == -1) { fprintf(stderr, "Error: cannot join the network namespace\n"); exit(1); } EUID_ROOT(); if (join_namespace(child, "net")) { fprintf(stderr, "Error: cannot join the network namespace\n"); exit(1); } if (strcmp(command, "set") == 0) bandwidth_set(pid, dev, down, up); else if (strcmp(command, "clear") == 0) bandwidth_remove(pid, dev); char *devname = NULL; if (dev) { char *fname; if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1) errExit("asprintf"); FILE *fp = fopen(fname, "r"); if (!fp) { fprintf(stderr, "Error: cannot read network map file %s\n", fname); exit(1); } char buf[1024]; int len = strlen(dev); while (fgets(buf, 1024, fp)) { char *ptr = strchr(buf, '\n'); if (ptr) *ptr = '\0'; if (*buf == '\0') break; if (strncmp(buf, dev, len) == 0 && buf[len] == ':') { devname = strdup(buf + len + 1); if (!devname) errExit("strdup"); if (if_nametoindex(devname) == 0) { fprintf(stderr, "Error: cannot find network device %s\n", devname); exit(1); } break; } } free(fname); fclose(fp); } char *cmd = NULL; if (devname) { if (strcmp(command, "set") == 0) { if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s %d %d", LIBDIR, command, devname, down, up) == -1) errExit("asprintf"); } else { if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s", LIBDIR, command, devname) == -1) errExit("asprintf"); } } else { if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s", LIBDIR, command) == -1) errExit("asprintf"); } assert(cmd); environ = NULL; if (setreuid(0, 0)) errExit("setreuid"); if (setregid(0, 0)) errExit("setregid"); if (!cfg.shell) cfg.shell = guess_shell(); if (!cfg.shell) { fprintf(stderr, "Error: no POSIX shell found, please use --shell command line option\n"); exit(1); } char *arg[4]; arg[0] = cfg.shell; arg[1] = "-c"; arg[2] = cmd; arg[3] = NULL; clearenv(); execvp(arg[0], arg); errExit("execvp"); } Commit Message: security fix CWE ID: CWE-269
void bandwidth_pid(pid_t pid, const char *command, const char *dev, int down, int up) { EUID_ASSERT(); EUID_ROOT(); char *comm = pid_proc_comm(pid); EUID_USER(); if (!comm) { fprintf(stderr, "Error: cannot find sandbox\n"); exit(1); } if (strcmp(comm, "firejail") != 0) { fprintf(stderr, "Error: cannot find sandbox\n"); exit(1); } free(comm); char *name; if (asprintf(&name, "/run/firejail/network/%d-netmap", pid) == -1) errExit("asprintf"); struct stat s; if (stat(name, &s) == -1) { fprintf(stderr, "Error: the sandbox doesn't use a new network namespace\n"); exit(1); } pid_t child; if (find_child(pid, &child) == -1) { fprintf(stderr, "Error: cannot join the network namespace\n"); exit(1); } EUID_ROOT(); if (join_namespace(child, "net")) { fprintf(stderr, "Error: cannot join the network namespace\n"); exit(1); } if (strcmp(command, "set") == 0) bandwidth_set(pid, dev, down, up); else if (strcmp(command, "clear") == 0) bandwidth_remove(pid, dev); char *devname = NULL; if (dev) { char *fname; if (asprintf(&fname, "%s/%d-netmap", RUN_FIREJAIL_NETWORK_DIR, (int) pid) == -1) errExit("asprintf"); FILE *fp = fopen(fname, "r"); if (!fp) { fprintf(stderr, "Error: cannot read network map file %s\n", fname); exit(1); } char buf[1024]; int len = strlen(dev); while (fgets(buf, 1024, fp)) { char *ptr = strchr(buf, '\n'); if (ptr) *ptr = '\0'; if (*buf == '\0') break; if (strncmp(buf, dev, len) == 0 && buf[len] == ':') { devname = strdup(buf + len + 1); if (!devname) errExit("strdup"); if (if_nametoindex(devname) == 0) { fprintf(stderr, "Error: cannot find network device %s\n", devname); exit(1); } break; } } free(fname); fclose(fp); } char *cmd = NULL; if (devname) { if (strcmp(command, "set") == 0) { if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s %d %d", LIBDIR, command, devname, down, up) == -1) errExit("asprintf"); } else { if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s %s", LIBDIR, command, devname) == -1) errExit("asprintf"); } } else { if (asprintf(&cmd, "%s/firejail/fshaper.sh --%s", LIBDIR, command) == -1) errExit("asprintf"); } assert(cmd); environ = NULL; if (setreuid(0, 0)) errExit("setreuid"); if (setregid(0, 0)) errExit("setregid"); char *arg[4]; arg[0] = "/bin/sh"; arg[1] = "-c"; arg[2] = cmd; arg[3] = NULL; clearenv(); execvp(arg[0], arg); errExit("execvp"); }
168,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pidfile_write(const char *pid_file, int pid) { FILE *pidfile = NULL; int pidfd = creat(pid_file, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (pidfd != -1) pidfile = fdopen(pidfd, "w"); if (!pidfile) { log_message(LOG_INFO, "pidfile_write : Cannot open %s pidfile", pid_file); return 0; } fprintf(pidfile, "%d\n", pid); fclose(pidfile); return 1; } Commit Message: When opening files for write, ensure they aren't symbolic links Issue #1048 identified that if, for example, a non privileged user created a symbolic link from /etc/keepalvied.data to /etc/passwd, writing to /etc/keepalived.data (which could be invoked via DBus) would cause /etc/passwd to be overwritten. This commit stops keepalived writing to pathnames where the ultimate component is a symbolic link, by setting O_NOFOLLOW whenever opening a file for writing. This might break some setups, where, for example, /etc/keepalived.data was a symbolic link to /home/fred/keepalived.data. If this was the case, instead create a symbolic link from /home/fred/keepalived.data to /tmp/keepalived.data, so that the file is still accessible via /home/fred/keepalived.data. There doesn't appear to be a way around this backward incompatibility, since even checking if the pathname is a symbolic link prior to opening for writing would create a race condition. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-59
pidfile_write(const char *pid_file, int pid) { FILE *pidfile = NULL; int pidfd = open(pid_file, O_NOFOLLOW | O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (pidfd != -1) pidfile = fdopen(pidfd, "w"); if (!pidfile) { log_message(LOG_INFO, "pidfile_write : Cannot open %s pidfile", pid_file); return 0; } fprintf(pidfile, "%d\n", pid); fclose(pidfile); return 1; }
168,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: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x)
170,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: smb_fdata(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { static int depth = 0; char s[128]; char *p; while (*fmt) { switch (*fmt) { case '*': fmt++; while (buf < maxbuf) { const u_char *buf2; depth++; buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr); depth--; if (buf2 == NULL) return(NULL); if (buf2 == buf) return(buf); buf = buf2; } return(buf); case '|': fmt++; if (buf >= maxbuf) return(buf); break; case '%': fmt++; buf = maxbuf; break; case '#': fmt++; return(buf); break; case '[': fmt++; if (buf >= maxbuf) return(buf); memset(s, 0, sizeof(s)); p = strchr(fmt, ']'); if ((size_t)(p - fmt + 1) > sizeof(s)) { /* overrun */ return(buf); } strncpy(s, fmt, p - fmt); s[p - fmt] = '\0'; fmt = p + 1; buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr); if (buf == NULL) return(NULL); break; default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (!depth && buf < maxbuf) { size_t len = PTR_DIFF(maxbuf, buf); ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len)); smb_print_data(ndo, buf, len); return(buf + len); } return(buf); } Commit Message: (for 4.9.3) CVE-2018-16452/SMB: prevent stack exhaustion Enforce a limit on how many times smb_fdata() can recurse. This fixes a stack exhaustion discovered by Include Security working under the Mozilla SOS program in 2018 by means of code audit. CWE ID: CWE-674
smb_fdata(netdissect_options *ndo, const u_char *buf, const char *fmt, const u_char *maxbuf, int unicodestr) { static int depth = 0; char s[128]; char *p; while (*fmt) { switch (*fmt) { case '*': fmt++; while (buf < maxbuf) { const u_char *buf2; depth++; /* Not sure how this relates with the protocol specification, * but in order to avoid stack exhaustion recurse at most that * many levels. */ if (depth == 10) ND_PRINT((ndo, "(too many nested levels, not recursing)")); else buf2 = smb_fdata(ndo, buf, fmt, maxbuf, unicodestr); depth--; if (buf2 == NULL) return(NULL); if (buf2 == buf) return(buf); buf = buf2; } return(buf); case '|': fmt++; if (buf >= maxbuf) return(buf); break; case '%': fmt++; buf = maxbuf; break; case '#': fmt++; return(buf); break; case '[': fmt++; if (buf >= maxbuf) return(buf); memset(s, 0, sizeof(s)); p = strchr(fmt, ']'); if ((size_t)(p - fmt + 1) > sizeof(s)) { /* overrun */ return(buf); } strncpy(s, fmt, p - fmt); s[p - fmt] = '\0'; fmt = p + 1; buf = smb_fdata1(ndo, buf, s, maxbuf, unicodestr); if (buf == NULL) return(NULL); break; default: ND_PRINT((ndo, "%c", *fmt)); fmt++; break; } } if (!depth && buf < maxbuf) { size_t len = PTR_DIFF(maxbuf, buf); ND_PRINT((ndo, "Data: (%lu bytes)\n", (unsigned long)len)); smb_print_data(ndo, buf, len); return(buf + len); } return(buf); }
169,814
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 entersafe_gen_key(sc_card_t *card, sc_entersafe_gen_key_data *data) { int r; size_t len = data->key_length >> 3; sc_apdu_t apdu; u8 rbuf[300]; u8 sbuf[4],*p; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* MSE */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x01, 0xB8); apdu.lc=0x04; sbuf[0]=0x83; sbuf[1]=0x02; sbuf[2]=data->key_id; sbuf[3]=0x2A; apdu.data = sbuf; apdu.datalen=4; apdu.lc=4; apdu.le=0; r=entersafe_transmit_apdu(card, &apdu, 0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe set MSE failed"); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.le = 0; sbuf[0] = (u8)(data->key_length >> 8); sbuf[1] = (u8)(data->key_length); apdu.data = sbuf; apdu.lc = 2; apdu.datalen = 2; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe generate keypair failed"); /* read public key via READ PUBLIC KEY */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xE6, 0x2A, data->key_id); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe get pukey failed"); data->modulus = malloc(len); if (!data->modulus) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_ERROR_OUT_OF_MEMORY); p=rbuf; assert(*p=='E'); p+=2+p[1]; /* N */ assert(*p=='N'); ++p; if(*p++>0x80) { u8 len_bytes=(*(p-1))&0x0f; size_t module_len=0; while(len_bytes!=0) { module_len=module_len<<8; module_len+=*p++; --len_bytes; } } entersafe_reverse_buffer(p,len); memcpy(data->modulus,p,len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS); } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
static int entersafe_gen_key(sc_card_t *card, sc_entersafe_gen_key_data *data) { int r; size_t len = data->key_length >> 3; sc_apdu_t apdu; u8 rbuf[300]; u8 sbuf[4],*p; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* MSE */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x01, 0xB8); apdu.lc=0x04; sbuf[0]=0x83; sbuf[1]=0x02; sbuf[2]=data->key_id; sbuf[3]=0x2A; apdu.data = sbuf; apdu.datalen=4; apdu.lc=4; apdu.le=0; r=entersafe_transmit_apdu(card, &apdu, 0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe set MSE failed"); /* generate key */ sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x46, 0x00, 0x00); apdu.le = 0; sbuf[0] = (u8)(data->key_length >> 8); sbuf[1] = (u8)(data->key_length); apdu.data = sbuf; apdu.lc = 2; apdu.datalen = 2; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe generate keypair failed"); /* read public key via READ PUBLIC KEY */ sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xE6, 0x2A, data->key_id); apdu.cla = 0x80; apdu.resp = rbuf; apdu.resplen = sizeof(rbuf); apdu.le = 256; r = entersafe_transmit_apdu(card, &apdu,0,0,0,0); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed"); SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, sc_check_sw(card,apdu.sw1,apdu.sw2),"EnterSafe get pukey failed"); data->modulus = malloc(len); if (!data->modulus) SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); p=rbuf; if (*p!='E') SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_DATA); p+=2+p[1]; /* N */ if (*p!='N') SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_INVALID_DATA); ++p; if(*p++>0x80) { u8 len_bytes=(*(p-1))&0x0f; size_t module_len=0; while(len_bytes!=0) { module_len=module_len<<8; module_len+=*p++; --len_bytes; } } entersafe_reverse_buffer(p,len); memcpy(data->modulus,p,len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE,SC_SUCCESS); }
169,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cJSON_strcasecmp( const char *s1, const char *s2 ) { if ( ! s1 ) return ( s1 == s2 ) ? 0 : 1; if ( ! s2 ) return 1; for ( ; tolower(*s1) == tolower(*s2); ++s1, ++s2) if( *s1 == 0 ) return 0; return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static int cJSON_strcasecmp( const char *s1, const char *s2 ) static int cJSON_strcasecmp(const char *s1,const char *s2) { if (!s1) return (s1==s2)?0:1;if (!s2) return 1; for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); }
167,297
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y, ExceptionInfo *exception) { size_t bit; ssize_t x; register Quantum *q; Quantum index; index=0; switch (depth) { case 1: /* Convert bitmap scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) ((((*p) & (0x80 >> bit)) != 0) ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } (void) SyncAuthenticPixels(image,exception); break; } case 2: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); if ((image->columns % 4) >= 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } } p++; } (void) SyncAuthenticPixels(image,exception); break; } case 4: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0xf,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } (void) SyncAuthenticPixels(image,exception); break; } case 8: /* Convert PseudoColor scanline. */ { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p,exception); SetPixelIndex(image,index,q); p++; q+=GetPixelChannels(image); } (void) SyncAuthenticPixels(image,exception); break; } } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1162 CWE ID: CWE-787
static void InsertRow(Image *image,ssize_t depth,unsigned char *p,ssize_t y, static MagickBooleanType InsertRow(Image *image,ssize_t bpp,unsigned char *p, ssize_t y,ExceptionInfo *exception) { int bit; Quantum index; register Quantum *q; ssize_t x; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); switch (bpp) { case 1: /* Convert bitmap scanline. */ { for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (ssize_t) (image->columns % 8); bit++) { index=((*p) & (0x80 >> bit) ? 0x01 : 0x00); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } p++; } break; } case 2: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-3); x+=4) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 4) != 0) { index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 1) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); if ((image->columns % 4) > 2) { index=ConstrainColormapIndex(image,(*p >> 2) & 0x3, exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); } } p++; } break; } case 4: /* Convert PseudoColor scanline. */ { for (x=0; x < ((ssize_t) image->columns-1); x+=2) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); q+=GetPixelChannels(image); index=ConstrainColormapIndex(image,(*p) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } break; } case 8: /* Convert PseudoColor scanline. */ { for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,*p,exception); SetPixelIndex(image,index,q); if (index < image->colors) SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q); p++; q+=GetPixelChannels(image); } } break; case 24: /* Convert DirectColor scanline. */ for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } break; } if (!SyncAuthenticPixels(image,exception)) return(MagickFalse); return(MagickTrue); }
169,042