instruction
stringclasses
1 value
input
stringlengths
93
3.53k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: BlockEntry::~BlockEntry() { } 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
BlockEntry::~BlockEntry()
174,456
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; scale_factor = 1.0f; rasterize_pdf = false; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = blink::kWebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; title = base::string16(); url = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Reviewed-by: Tom Sepez <tsepez@chromium.org> Reviewed-by: Jianzhou Feng <jzfeng@chromium.org> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; scale_factor = 1.0f; rasterize_pdf = false; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = blink::kWebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; title = base::string16(); url = base::string16(); header_template = base::string16(); footer_template = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; }
172,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void opl3_setup_voice(int dev, int voice, int chn) { struct channel_info *info = &synth_devs[dev]->chn_info[chn]; opl3_set_instr(dev, voice, info->pgm_num); devc->voc[voice].bender = 0; devc->voc[voice].bender_range = info->bender_range; devc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME]; devc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128; } Commit Message: sound/oss/opl3: validate voice and channel indexes User-controllable indexes for voice and channel values may cause reading and writing beyond the bounds of their respective arrays, leading to potentially exploitable memory corruption. Validate these indexes. Signed-off-by: Dan Rosenberg <drosenberg@vsecurity.com> Cc: stable@kernel.org Signed-off-by: Takashi Iwai <tiwai@suse.de> CWE ID: CWE-119
static void opl3_setup_voice(int dev, int voice, int chn) { struct channel_info *info; if (voice < 0 || voice >= devc->nr_voice) return; if (chn < 0 || chn > 15) return; info = &synth_devs[dev]->chn_info[chn]; opl3_set_instr(dev, voice, info->pgm_num); devc->voc[voice].bender = 0; devc->voc[voice].bender_range = info->bender_range; devc->voc[voice].volume = info->controllers[CTL_MAIN_VOLUME]; devc->voc[voice].panning = (info->controllers[CTL_PAN] * 2) - 128; }
165,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: externalParEntProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { const char *next = s; int tok; tok = XmlPrologTok(parser->m_encoding, s, end, &next); if (tok <= 0) { if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case XML_TOK_NONE: /* start == end */ default: break; } } /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. However, when parsing an external subset, doProlog will not accept a BOM as valid, and report a syntax error, so we have to skip the BOM */ else if (tok == XML_TOK_BOM) { s = next; tok = XmlPrologTok(parser->m_encoding, s, end, &next); } parser->m_processor = prologProcessor; return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer); } Commit Message: xmlparse.c: Deny internal entities closing the doctype CWE ID: CWE-611
externalParEntProcessor(XML_Parser parser, const char *s, const char *end, const char **nextPtr) { const char *next = s; int tok; tok = XmlPrologTok(parser->m_encoding, s, end, &next); if (tok <= 0) { if (! parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) { *nextPtr = s; return XML_ERROR_NONE; } switch (tok) { case XML_TOK_INVALID: return XML_ERROR_INVALID_TOKEN; case XML_TOK_PARTIAL: return XML_ERROR_UNCLOSED_TOKEN; case XML_TOK_PARTIAL_CHAR: return XML_ERROR_PARTIAL_CHAR; case XML_TOK_NONE: /* start == end */ default: break; } } /* This would cause the next stage, i.e. doProlog to be passed XML_TOK_BOM. However, when parsing an external subset, doProlog will not accept a BOM as valid, and report a syntax error, so we have to skip the BOM */ else if (tok == XML_TOK_BOM) { s = next; tok = XmlPrologTok(parser->m_encoding, s, end, &next); } parser->m_processor = prologProcessor; return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE); }
169,530
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() { return delegated_frame_host_ ? delegated_frame_host_->GetFrameSinkId() : cc::FrameSinkId(); } Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash RenderWidgetHostViewChildFrame expects its parent to have a valid FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even if DelegatedFrameHost is not used (in mus+ash). BUG=706553 TBR=jam@chromium.org Review-Url: https://codereview.chromium.org/2847253003 Cr-Commit-Position: refs/heads/master@{#468179} CWE ID: CWE-254
cc::FrameSinkId RenderWidgetHostViewAura::GetFrameSinkId() { return frame_sink_id_; }
172,234
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void QuicTransportHost::Initialize( IceTransportHost* ice_transport_host, quic::Perspective perspective, const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(ice_transport_host); DCHECK(!ice_transport_host_); ice_transport_host_ = ice_transport_host; P2PQuicTransportConfig config( this, ice_transport_host->ConnectConsumer(this)->packet_transport(), certificates); config.is_server = (perspective == quic::Perspective::IS_SERVER); quic_transport_ = quic_transport_factory_->CreateQuicTransport(std::move(config)); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <shampson@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void QuicTransportHost::Initialize( IceTransportHost* ice_transport_host, quic::Perspective perspective, const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(ice_transport_host); DCHECK(!ice_transport_host_); ice_transport_host_ = ice_transport_host; // TODO(https://crbug.com/874296): Pass through values for read and write // stream buffer sizes in the P2PQuicTransportConfig. Currently this is just // set to the same size as the QUIC receive window size (24 MB). uint32_t stream_buffer_size = 24 * 1024 * 1024; P2PQuicTransportConfig config( this, ice_transport_host->ConnectConsumer(this)->packet_transport(), certificates, stream_buffer_size); config.is_server = (perspective == quic::Perspective::IS_SERVER); quic_transport_ = quic_transport_factory_->CreateQuicTransport(std::move(config)); }
172,270
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool PluginInfoMessageFilter::Context::FindEnabledPlugin( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type, scoped_ptr<PluginMetadata>* plugin_metadata) const { bool allow_wildcard = true; std::vector<WebPluginInfo> matching_plugins; std::vector<std::string> mime_types; PluginService::GetInstance()->GetPluginInfoArray( url, mime_type, allow_wildcard, &matching_plugins, &mime_types); if (matching_plugins.empty()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound; return false; } content::PluginServiceFilter* filter = PluginService::GetInstance()->GetFilter(); size_t i = 0; for (; i < matching_plugins.size(); ++i) { if (!filter || filter->IsPluginEnabled(render_process_id_, render_view_id, resource_context_, url, top_origin_url, &matching_plugins[i])) { break; } } bool enabled = i < matching_plugins.size(); if (!enabled) { i = 0; status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; } *plugin = matching_plugins[i]; *actual_mime_type = mime_types[i]; if (plugin_metadata) *plugin_metadata = PluginFinder::GetInstance()->GetPluginMetadata(*plugin); return enabled; } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
bool PluginInfoMessageFilter::Context::FindEnabledPlugin( int render_view_id, const GURL& url, const GURL& top_origin_url, const std::string& mime_type, ChromeViewHostMsg_GetPluginInfo_Status* status, WebPluginInfo* plugin, std::string* actual_mime_type, scoped_ptr<PluginMetadata>* plugin_metadata) const { bool allow_wildcard = true; std::vector<WebPluginInfo> matching_plugins; std::vector<std::string> mime_types; PluginService::GetInstance()->GetPluginInfoArray( url, mime_type, allow_wildcard, &matching_plugins, &mime_types); if (matching_plugins.empty()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound; return false; } content::PluginServiceFilter* filter = PluginService::GetInstance()->GetFilter(); size_t i = 0; for (; i < matching_plugins.size(); ++i) { if (!filter || filter->IsPluginAvailable(render_process_id_, render_view_id, resource_context_, url, top_origin_url, &matching_plugins[i])) { break; } } bool enabled = i < matching_plugins.size(); if (!enabled) { i = 0; status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled; } *plugin = matching_plugins[i]; *actual_mime_type = mime_types[i]; if (plugin_metadata) *plugin_metadata = PluginFinder::GetInstance()->GetPluginMetadata(*plugin); return enabled; }
171,471
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void BrowserPolicyConnector::DeviceStopAutoRetry() { #if defined(OS_CHROMEOS) if (device_cloud_policy_subsystem_.get()) device_cloud_policy_subsystem_->StopAutoRetry(); #endif } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void BrowserPolicyConnector::DeviceStopAutoRetry() { void BrowserPolicyConnector::ResetDevicePolicy() { #if defined(OS_CHROMEOS) if (device_cloud_policy_subsystem_.get()) device_cloud_policy_subsystem_->Reset(); #endif }
170,279
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static ssize_t k90_show_current_profile(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct usb_interface *usbif = to_usb_interface(dev->parent); struct usb_device *usbdev = interface_to_usbdev(usbif); int current_profile; char data[8]; ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), K90_REQUEST_STATUS, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, data, 8, USB_CTRL_SET_TIMEOUT); if (ret < 0) { dev_warn(dev, "Failed to get K90 initial state (error %d).\n", ret); return -EIO; } current_profile = data[7]; if (current_profile < 1 || current_profile > 3) { dev_warn(dev, "Read invalid current profile: %02hhx.\n", data[7]); return -EIO; } return snprintf(buf, PAGE_SIZE, "%d\n", current_profile); } Commit Message: HID: corsair: fix DMA buffers on stack Not all platforms support DMA to the stack, and specifically since v4.9 this is no longer supported on x86 with VMAP_STACK either. Note that the macro-mode buffer was larger than necessary. Fixes: 6f78193ee9ea ("HID: corsair: Add Corsair Vengeance K90 driver") Cc: stable <stable@vger.kernel.org> Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-119
static ssize_t k90_show_current_profile(struct device *dev, struct device_attribute *attr, char *buf) { int ret; struct usb_interface *usbif = to_usb_interface(dev->parent); struct usb_device *usbdev = interface_to_usbdev(usbif); int current_profile; char *data; data = kmalloc(8, GFP_KERNEL); if (!data) return -ENOMEM; ret = usb_control_msg(usbdev, usb_rcvctrlpipe(usbdev, 0), K90_REQUEST_STATUS, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, data, 8, USB_CTRL_SET_TIMEOUT); if (ret < 0) { dev_warn(dev, "Failed to get K90 initial state (error %d).\n", ret); ret = -EIO; goto out; } current_profile = data[7]; if (current_profile < 1 || current_profile > 3) { dev_warn(dev, "Read invalid current profile: %02hhx.\n", data[7]); ret = -EIO; goto out; } ret = snprintf(buf, PAGE_SIZE, "%d\n", current_profile); out: kfree(data); return ret; }
168,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static unsigned short get_ushort(const unsigned char *data) { unsigned short val = *(const unsigned short *)data; #ifdef OPJ_BIG_ENDIAN val = ((val & 0xffU) << 8) | (val >> 8); #endif return val; } Commit Message: tgatoimage(): avoid excessive memory allocation attempt, and fixes unaligned load (#995) CWE ID: CWE-787
static unsigned short get_ushort(const unsigned char *data) /* Returns a ushort from a little-endian serialized value */ static unsigned short get_tga_ushort(const unsigned char *data) { return data[0] | (data[1] << 8); }
167,780
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: PHP_FUNCTION(locale_get_primary_language ) { get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_get_primary_language ) PHP_FUNCTION(locale_get_primary_language ) { get_icu_value_src_php( LOC_LANG_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,184
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: exsltStrPaddingFunction (xmlXPathParserContextPtr ctxt, int nargs) { int number, str_len = 0; xmlChar *str = NULL, *ret = NULL, *tmp; if ((nargs < 1) || (nargs > 2)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 2) { str = xmlXPathPopString(ctxt); str_len = xmlUTF8Strlen(str); } if (str_len == 0) { if (str != NULL) xmlFree(str); str = xmlStrdup((const xmlChar *) " "); str_len = 1; } number = (int) xmlXPathPopNumber(ctxt); if (number <= 0) { xmlXPathReturnEmptyString(ctxt); xmlFree(str); return; } while (number >= str_len) { ret = xmlStrncat(ret, str, str_len); number -= str_len; } tmp = xmlUTF8Strndup (str, number); ret = xmlStrcat(ret, tmp); if (tmp != NULL) xmlFree (tmp); xmlXPathReturnString(ctxt, ret); if (str != NULL) xmlFree(str); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltStrPaddingFunction (xmlXPathParserContextPtr ctxt, int nargs) { int number, str_len = 0, str_size = 0; xmlChar *str = NULL, *ret = NULL; if ((nargs < 1) || (nargs > 2)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 2) { str = xmlXPathPopString(ctxt); str_len = xmlUTF8Strlen(str); str_size = xmlStrlen(str); } if (str_len == 0) { if (str != NULL) xmlFree(str); str = xmlStrdup((const xmlChar *) " "); str_len = 1; str_size = 1; } number = (int) xmlXPathPopNumber(ctxt); if (number <= 0) { xmlXPathReturnEmptyString(ctxt); xmlFree(str); return; } while (number >= str_len) { ret = xmlStrncat(ret, str, str_size); number -= str_len; } if (number > 0) { str_size = xmlUTF8Strsize(str, number); ret = xmlStrncat(ret, str, str_size); } xmlXPathReturnString(ctxt, ret); if (str != NULL) xmlFree(str); }
173,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { return image_transform_png_set_expand_add(this, that, colour_type, bit_depth); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { #if PNG_LIBPNG_VER < 10700 return image_transform_png_set_expand_add(this, that, colour_type, bit_depth); #else UNUSED(bit_depth) this->next = *that; *that = this; /* This should do nothing unless the color type is gray and the bit depth is * less than 8: */ return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8; #endif /* 1.7 or later */ }
173,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Track::GetContentEncodingByIndex(unsigned long idx) const { const ptrdiff_t count = content_encoding_entries_end_ - content_encoding_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return content_encoding_entries_[idx]; } 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
Track::GetContentEncodingByIndex(unsigned long idx) const { const ContentEncoding* Track::GetContentEncodingByIndex( unsigned long idx) const { const ptrdiff_t count = content_encoding_entries_end_ - content_encoding_entries_; assert(count >= 0); if (idx >= static_cast<unsigned long>(count)) return NULL; return content_encoding_entries_[idx]; }
174,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void LoginHtmlDialog::GetDialogSize(gfx::Size* size) const { size->SetSize(width_, height_); } Commit Message: cros: The next 100 clang plugin errors. BUG=none TEST=none TBR=dpolukhin Review URL: http://codereview.chromium.org/7022008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@85418 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void LoginHtmlDialog::GetDialogSize(gfx::Size* size) const { bool LoginHtmlDialog::ShouldShowDialogTitle() const { return true; } void LoginHtmlDialog::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type.value == NotificationType::LOAD_COMPLETED_MAIN_FRAME); if (bubble_frame_view_) bubble_frame_view_->StopThrobber(); }
170,615
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void v9fs_device_unrealize_common(V9fsState *s, Error **errp) { g_free(s->ctx.fs_root); g_free(s->tag); } Commit Message: CWE ID: CWE-400
void v9fs_device_unrealize_common(V9fsState *s, Error **errp) { g_free(s->tag); g_free(s->ctx.fs_root); }
164,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void _xml_unparsedEntityDeclHandler(void *userData, const XML_Char *entityName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName) { xml_parser *parser = (xml_parser *)userData; if (parser && parser->unparsedEntityDeclHandler) { zval *retval, *args[6]; args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding); args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding); args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding); args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding); args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) { zval_ptr_dtor(&retval); } } } Commit Message: CWE ID: CWE-119
void _xml_unparsedEntityDeclHandler(void *userData, void _xml_unparsedEntityDeclHandler(void *userData, const XML_Char *entityName, const XML_Char *base, const XML_Char *systemId, const XML_Char *publicId, const XML_Char *notationName) { xml_parser *parser = (xml_parser *)userData; if (parser && parser->unparsedEntityDeclHandler) { zval *retval, *args[6]; args[0] = _xml_resource_zval(parser->index); args[1] = _xml_xmlchar_zval(entityName, 0, parser->target_encoding); args[2] = _xml_xmlchar_zval(base, 0, parser->target_encoding); args[3] = _xml_xmlchar_zval(systemId, 0, parser->target_encoding); args[4] = _xml_xmlchar_zval(publicId, 0, parser->target_encoding); args[5] = _xml_xmlchar_zval(notationName, 0, parser->target_encoding); if ((retval = xml_call_handler(parser, parser->unparsedEntityDeclHandler, parser->unparsedEntityDeclPtr, 6, args))) { zval_ptr_dtor(&retval); } } }
165,043
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DataReductionProxyConfig::FetchWarmupProbeURL() { DCHECK(thread_checker_.CalledOnValidThread()); if (!enabled_by_user_) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kProxyNotEnabledByUser); return; } if (!params::FetchWarmupProbeURLEnabled()) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kWarmupURLFetchingDisabled); return; } if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kConnectionTypeNone); return; } base::Optional<DataReductionProxyServer> warmup_proxy = GetProxyConnectionToProbe(); if (!warmup_proxy) return; warmup_url_fetch_in_flight_secure_proxy_ = warmup_proxy->IsSecureProxy(); warmup_url_fetch_in_flight_core_proxy_ = warmup_proxy->IsCoreProxy(); size_t previous_attempt_counts = GetWarmupURLFetchAttemptCounts(); network_properties_manager_->OnWarmupFetchInitiated( warmup_url_fetch_in_flight_secure_proxy_, warmup_url_fetch_in_flight_core_proxy_); RecordWarmupURLFetchAttemptEvent(WarmupURLFetchAttemptEvent::kFetchInitiated); warmup_url_fetcher_->FetchWarmupURL(previous_attempt_counts, warmup_proxy.value()); } 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 <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void DataReductionProxyConfig::FetchWarmupProbeURL() { DCHECK(thread_checker_.CalledOnValidThread()); if (params::IsIncludedInHoldbackFieldTrial()) return; if (!enabled_by_user_) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kProxyNotEnabledByUser); return; } if (!params::FetchWarmupProbeURLEnabled()) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kWarmupURLFetchingDisabled); return; } if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) { RecordWarmupURLFetchAttemptEvent( WarmupURLFetchAttemptEvent::kConnectionTypeNone); return; } base::Optional<DataReductionProxyServer> warmup_proxy = GetProxyConnectionToProbe(); if (!warmup_proxy) return; warmup_url_fetch_in_flight_secure_proxy_ = warmup_proxy->IsSecureProxy(); warmup_url_fetch_in_flight_core_proxy_ = warmup_proxy->IsCoreProxy(); size_t previous_attempt_counts = GetWarmupURLFetchAttemptCounts(); network_properties_manager_->OnWarmupFetchInitiated( warmup_url_fetch_in_flight_secure_proxy_, warmup_url_fetch_in_flight_core_proxy_); RecordWarmupURLFetchAttemptEvent(WarmupURLFetchAttemptEvent::kFetchInitiated); warmup_url_fetcher_->FetchWarmupURL(previous_attempt_counts, warmup_proxy.value()); }
172,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: char *enl_ipc_get(const char *msg_data) { static char *message = NULL; static unsigned short len = 0; char buff[13], *ret_msg = NULL; register unsigned char i; unsigned char blen; if (msg_data == IPC_TIMEOUT) { return(IPC_TIMEOUT); } for (i = 0; i < 12; i++) { buff[i] = msg_data[i]; } buff[12] = 0; blen = strlen(buff); if (message != NULL) { len += blen; message = (char *) erealloc(message, len + 1); strcat(message, buff); } else { len = blen; message = (char *) emalloc(len + 1); strcpy(message, buff); } if (blen < 12) { ret_msg = message; message = NULL; D(("Received complete reply: \"%s\"\n", ret_msg)); } return(ret_msg); } Commit Message: Fix double-free/OOB-write while receiving IPC data If a malicious client pretends to be the E17 window manager, it is possible to trigger an out of boundary heap write while receiving an IPC message. The length of the already received message is stored in an unsigned short, which overflows after receiving 64 KB of data. It's comparably small amount of data and therefore achievable for an attacker. When len overflows, realloc() will either be called with a small value and therefore chars will be appended out of bounds, or len + 1 will be exactly 0, in which case realloc() behaves like free(). This could be abused for a later double-free attack as it's even possible to overwrite the free information -- but this depends on the malloc implementation. Signed-off-by: Tobias Stoeckmann <tobias@stoeckmann.org> CWE ID: CWE-787
char *enl_ipc_get(const char *msg_data) { static char *message = NULL; static size_t len = 0; char buff[13], *ret_msg = NULL; register unsigned char i; unsigned char blen; if (msg_data == IPC_TIMEOUT) { return(IPC_TIMEOUT); } for (i = 0; i < 12; i++) { buff[i] = msg_data[i]; } buff[12] = 0; blen = strlen(buff); if (message != NULL) { len += blen; message = (char *) erealloc(message, len + 1); strcat(message, buff); } else { len = blen; message = (char *) emalloc(len + 1); strcpy(message, buff); } if (blen < 12) { ret_msg = message; message = NULL; D(("Received complete reply: \"%s\"\n", ret_msg)); } return(ret_msg); }
168,244
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: png_set_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp palette, int num_palette) { png_debug1(1, "in %s storage function", "PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) png_error(png_ptr, "Invalid palette length"); else { png_warning(png_ptr, "Invalid palette length"); return; } } /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. */ #ifdef PNG_FREE_ME_SUPPORTED png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); #endif /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead * of num_palette entries, in case of an invalid PNG file that has * too-large sample values. */ png_ptr->palette = (png_colorp)png_calloc(png_ptr, PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color)); png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color)); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; #ifdef PNG_FREE_ME_SUPPORTED info_ptr->free_me |= PNG_FREE_PLTE; #else png_ptr->flags |= PNG_FLAG_FREE_PLTE; #endif info_ptr->valid |= PNG_INFO_PLTE; } Commit Message: third_party/libpng: update to 1.2.54 TBR=darin@chromium.org BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_set_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp palette, int num_palette) { png_uint_32 max_palette_length; png_debug1(1, "in %s storage function", "PLTE"); if (png_ptr == NULL || info_ptr == NULL) return; max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ? (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH; if (num_palette < 0 || num_palette > (int) max_palette_length) { if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) png_error(png_ptr, "Invalid palette length"); else { png_warning(png_ptr, "Invalid palette length"); return; } } /* It may not actually be necessary to set png_ptr->palette here; * we do it for backward compatibility with the way the png_handle_tRNS * function used to do the allocation. */ #ifdef PNG_FREE_ME_SUPPORTED png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0); #endif /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead * of num_palette entries, in case of an invalid PNG file or incorrect * call to png_set_PLTE() with too-large sample values. */ png_ptr->palette = (png_colorp)png_calloc(png_ptr, PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color)); png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof(png_color)); info_ptr->palette = png_ptr->palette; info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette; #ifdef PNG_FREE_ME_SUPPORTED info_ptr->free_me |= PNG_FREE_PLTE; #else png_ptr->flags |= PNG_FLAG_FREE_PLTE; #endif info_ptr->valid |= PNG_INFO_PLTE; }
172,183
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; zend_bool old_allow_url_fopen; /* xmlInitParser(); */ old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; ctxt = xmlCreateFileParserCtxt(filename); PG(allow_url_fopen) = old_allow_url_fopen; if (ctxt) { ctxt->keepBlanks = 0; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; /*ctxt->sax->fatalError = NULL;*/ xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; } Commit Message: CWE ID: CWE-200
xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; zend_bool old_allow_url_fopen; /* xmlInitParser(); */ old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; ctxt = xmlCreateFileParserCtxt(filename); PG(allow_url_fopen) = old_allow_url_fopen; if (ctxt) { ctxt->keepBlanks = 0; ctxt->options -= XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; /*ctxt->sax->fatalError = NULL;*/ xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; }
164,727
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cJSON *cJSON_CreateIntArray( int64_t *numbers, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateInt( numbers[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_CreateIntArray( int64_t *numbers, int count )
167,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void DelegatedFrameHost::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& dst_size, const base::Callback<void(bool, const SkBitmap&)>& callback, const SkColorType color_type) { bool format_support = ((color_type == kRGB_565_SkColorType) || (color_type == kN32_SkColorType)); DCHECK(format_support); if (!CanCopyToBitmap()) { callback.Run(false, SkBitmap()); return; } const gfx::Size& dst_size_in_pixel = client_->ConvertViewSizeToPixel(dst_size); scoped_ptr<cc::CopyOutputRequest> request = cc::CopyOutputRequest::CreateRequest(base::Bind( &DelegatedFrameHost::CopyFromCompositingSurfaceHasResult, dst_size_in_pixel, color_type, callback)); gfx::Rect src_subrect_in_pixel = ConvertRectToPixel(client_->CurrentDeviceScaleFactor(), src_subrect); request->set_area(src_subrect_in_pixel); client_->RequestCopyOfOutput(request.Pass()); } Commit Message: repairs CopyFromCompositingSurface in HighDPI This CL removes the DIP=>Pixel transform in DelegatedFrameHost::CopyFromCompositingSurface(), because said transformation seems to be happening later in the copy logic and is currently being applied twice. BUG=397708 Review URL: https://codereview.chromium.org/421293002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@286414 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DelegatedFrameHost::CopyFromCompositingSurface( const gfx::Rect& src_subrect, const gfx::Size& output_size, const base::Callback<void(bool, const SkBitmap&)>& callback, const SkColorType color_type) { bool format_support = ((color_type == kRGB_565_SkColorType) || (color_type == kN32_SkColorType)); DCHECK(format_support); if (!CanCopyToBitmap()) { callback.Run(false, SkBitmap()); return; } scoped_ptr<cc::CopyOutputRequest> request = cc::CopyOutputRequest::CreateRequest(base::Bind( &DelegatedFrameHost::CopyFromCompositingSurfaceHasResult, output_size, color_type, callback)); request->set_area(src_subrect); client_->RequestCopyOfOutput(request.Pass()); }
171,193
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */ { va_list va; char *message = NULL; va_start(va, format); zend_vspprintf(&message, 0, format, va); if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) { zend_throw_error(exception_ce, message); } else { zend_error(E_ERROR, "%s", message); } efree(message); va_end(va); } /* }}} */ Commit Message: Use format string CWE ID: CWE-134
static void zend_throw_or_error(int fetch_type, zend_class_entry *exception_ce, const char *format, ...) /* {{{ */ { va_list va; char *message = NULL; va_start(va, format); zend_vspprintf(&message, 0, format, va); if (fetch_type & ZEND_FETCH_CLASS_EXCEPTION) { zend_throw_error(exception_ce, "%s", message); } else { zend_error(E_ERROR, "%s", message); } efree(message); va_end(va); } /* }}} */
167,531
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/148 CWE ID: CWE-787
static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { if ((q+PSDQuantum(count)+12) < (datum+length-16)) { (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- (PSDQuantum(count)+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); } break; } p+=count; if ((count & 0x01) != 0) p++; } }
168,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: _PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = strnlen(str, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); *bytes_consumed = 1; return INVALID_CODEPOINT; } Commit Message: CWE ID: CWE-200
_PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, size_t len, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } /* * we assume that no multi-byte character can take more than 5 bytes. * we assume that no multi-byte character can take more than 5 bytes. * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = MIN(len, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); *bytes_consumed = 1; return INVALID_CODEPOINT; }
164,670
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WriteFromUrlOperation::Download(const base::Closure& continuation) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (IsCancelled()) { return; } download_continuation_ = continuation; SetStage(image_writer_api::STAGE_DOWNLOAD); url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this); url_fetcher_->SetRequestContext(request_context_); url_fetcher_->SaveResponseToFileAtPath( image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE)); AddCleanUpFunction( base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this)); url_fetcher_->Start(); } Commit Message: Network traffic annotation added to extensions::image_writer::WriteFromUrlOperation. Network traffic annotation is added to network request of extensions::image_writer::WriteFromUrlOperation. BUG=656607 Review-Url: https://codereview.chromium.org/2691963002 Cr-Commit-Position: refs/heads/master@{#451456} CWE ID:
void WriteFromUrlOperation::Download(const base::Closure& continuation) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (IsCancelled()) { return; } download_continuation_ = continuation; SetStage(image_writer_api::STAGE_DOWNLOAD); // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("cros_recovery_image_download", R"( semantics { sender: "Chrome OS Recovery Utility" description: "The Google Chrome OS recovery utility downloads the recovery " "image from Google Download Server." trigger: "User uses the Chrome OS Recovery Utility app/extension, selects " "a Chrome OS recovery image, and clicks the Create button to write " "the image to a USB or SD card." data: "URL of the image file to be downloaded. No other data or user " "identifier is sent." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: true cookies_store: "user" setting: "This feature cannot be disabled by settings, it can only be used " "by whitelisted apps/extension." policy_exception_justification: "Not implemented, considered not useful." })"); url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this, traffic_annotation); url_fetcher_->SetRequestContext(request_context_); url_fetcher_->SaveResponseToFileAtPath( image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE)); AddCleanUpFunction( base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this)); url_fetcher_->Start(); }
171,962
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int enable(void) { LOG_INFO("%s", __func__); if (!interface_ready()) return BT_STATUS_NOT_READY; stack_manager_get_interface()->start_up_stack_async(); return BT_STATUS_SUCCESS; } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
static int enable(void) { static int enable(bool start_restricted) { LOG_INFO(LOG_TAG, "%s: start restricted = %d", __func__, start_restricted); restricted_mode = start_restricted; if (!interface_ready()) return BT_STATUS_NOT_READY; stack_manager_get_interface()->start_up_stack_async(); return BT_STATUS_SUCCESS; }
173,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool GesturePoint::IsInSecondClickTimeWindow() const { double duration = last_touch_time_ - last_tap_time_; return duration < kMaximumSecondsBetweenDoubleClick; } 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 GesturePoint::IsInSecondClickTimeWindow() const { double duration = last_touch_time_ - last_tap_time_; return duration < GestureConfiguration::max_seconds_between_double_click(); }
171,043
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: image_transform_png_set_expand_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* The general expand case depends on what the colour type is: */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); else if (that->bit_depth < 8) /* grayscale */ that->sample_depth = that->bit_depth = 8; if (that->have_tRNS) image_pixel_add_alpha(that, &display->this); this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_mod(PNG_CONST image_transform *this, image_transform_png_set_expand_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* The general expand case depends on what the colour type is: */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); else if (that->bit_depth < 8) /* grayscale */ that->sample_depth = that->bit_depth = 8; if (that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); this->next->mod(this->next, that, pp, display); }
173,633
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void XMLHttpRequest::didFailRedirectCheck() { networkError(); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::didFailRedirectCheck() { handleNetworkError(); }
171,166
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int64 GetReceivedListPrefValue(size_t index) { return ListPrefInt64Value(*received_update_, index); } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
int64 GetReceivedListPrefValue(size_t index) { return received_.GetListPrefValue(index); }
171,324
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int cuse_channel_release(struct inode *inode, struct file *file) { struct fuse_dev *fud = file->private_data; struct cuse_conn *cc = fc_to_cc(fud->fc); int rc; /* remove from the conntbl, no more access from this point on */ mutex_lock(&cuse_lock); list_del_init(&cc->list); mutex_unlock(&cuse_lock); /* remove device */ if (cc->dev) device_unregister(cc->dev); if (cc->cdev) { unregister_chrdev_region(cc->cdev->dev, 1); cdev_del(cc->cdev); } rc = fuse_dev_release(inode, file); /* puts the base reference */ return rc; } Commit Message: cuse: fix memory leak The problem is that fuse_dev_alloc() acquires an extra reference to cc.fc, and the original ref count is never dropped. Reported-by: Colin Ian King <colin.king@canonical.com> Signed-off-by: Miklos Szeredi <miklos@szeredi.hu> Fixes: cc080e9e9be1 ("fuse: introduce per-instance fuse_dev structure") Cc: <stable@vger.kernel.org> # v4.2+ CWE ID: CWE-399
static int cuse_channel_release(struct inode *inode, struct file *file) { struct fuse_dev *fud = file->private_data; struct cuse_conn *cc = fc_to_cc(fud->fc); int rc; /* remove from the conntbl, no more access from this point on */ mutex_lock(&cuse_lock); list_del_init(&cc->list); mutex_unlock(&cuse_lock); /* remove device */ if (cc->dev) device_unregister(cc->dev); if (cc->cdev) { unregister_chrdev_region(cc->cdev->dev, 1); cdev_del(cc->cdev); } /* Base reference is now owned by "fud" */ fuse_conn_put(&cc->fc); rc = fuse_dev_release(inode, file); /* puts the base reference */ return rc; }
167,573
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void* sspi_SecureHandleGetLowerPointer(SecHandle* handle) { void* pointer; if (!handle) return NULL; pointer = (void*) ~((size_t) handle->dwLower); return pointer; } Commit Message: nla: invalidate sec handle after creation If sec pointer isn't invalidated after creation it is not possible to check if the upper and lower pointers are valid. This fixes a segfault in the server part if the client disconnects before the authentication was finished. CWE ID: CWE-476
void* sspi_SecureHandleGetLowerPointer(SecHandle* handle) { void* pointer; if (!handle || !SecIsValidHandle(handle)) return NULL; pointer = (void*) ~((size_t) handle->dwLower); return pointer; }
167,604
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long long mkvparser::GetUIntLength( IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); long long total, available; int status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); len = 1; if (pos >= available) return pos; //too few bytes available //// TODO(vigneshv): This function assumes that unsigned values never have their //// high bit set. unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) return status; assert(status == 0); if (b == 0) //we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } 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 long mkvparser::GetUIntLength( long long mkvparser::GetUIntLength(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); long long total, available; int status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); len = 1; if (pos >= available) return pos; // too few bytes available unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) return status; assert(status == 0); if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } return 0; // success } //// TODO(vigneshv): This function assumes that unsigned values never have their //// high bit set. 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; }
174,377
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem( uint32_t id, const download::DownloadCreateInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!base::ContainsKey(downloads_, id)); download::DownloadItemImpl* download = item_factory_->CreateActiveItem(this, id, info); downloads_[id] = base::WrapUnique(download); downloads_by_guid_[download->GetGuid()] = download; DownloadItemUtils::AttachInfo( download, GetBrowserContext(), WebContentsImpl::FromRenderFrameHostID(info.render_process_id, info.render_frame_id)); return download; } Commit Message: Early return if a download Id is already used when creating a download This is protect against download Id overflow and use-after-free issue. BUG=958533 Change-Id: I2c183493cb09106686df9822b3987bfb95bcf720 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1591485 Reviewed-by: Xing Liu <xingliu@chromium.org> Commit-Queue: Min Qin <qinmin@chromium.org> Cr-Commit-Position: refs/heads/master@{#656910} CWE ID: CWE-416
download::DownloadItemImpl* DownloadManagerImpl::CreateActiveItem( uint32_t id, const download::DownloadCreateInfo& info) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (base::ContainsKey(downloads_, id)) return nullptr; download::DownloadItemImpl* download = item_factory_->CreateActiveItem(this, id, info); downloads_[id] = base::WrapUnique(download); downloads_by_guid_[download->GetGuid()] = download; DownloadItemUtils::AttachInfo( download, GetBrowserContext(), WebContentsImpl::FromRenderFrameHostID(info.render_process_id, info.render_frame_id)); return download; }
172,965
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); } Commit Message: CWE ID: CWE-399
static void SRP_user_pwd_free(SRP_user_pwd *user_pwd) void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); }
165,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type) { struct hexline *hx; u8 reset; int ret,pos=0; hx = kmalloc(sizeof(*hx), GFP_KERNEL); if (!hx) return -ENOMEM; /* stop the CPU */ reset = 1; if ((ret = usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1)) != 1) err("could not stop the USB controller CPU."); while ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) { deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n", hx->addr, hx->len, hx->chk); ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len); if (ret != hx->len) { err("error while transferring firmware (transferred size: %d, block size: %d)", ret, hx->len); ret = -EINVAL; break; } } if (ret < 0) { err("firmware download failed at %d with %d",pos,ret); kfree(hx); return ret; } if (ret == 0) { /* restart the CPU */ reset = 0; if (ret || usb_cypress_writemem(udev,cypress[type].cpu_cs_register,&reset,1) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } } else ret = -EIO; kfree(hx); return ret; } Commit Message: [media] dvb-usb-firmware: don't do DMA on stack The buffer allocation for the firmware data was changed in commit 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load") but the same applies for the reset value. Fixes: 43fab9793c1f ("[media] dvb-usb: don't use stack for firmware load") Cc: stable@vger.kernel.org Signed-off-by: Stefan Brüns <stefan.bruens@rwth-aachen.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com> CWE ID: CWE-119
int usb_cypress_load_firmware(struct usb_device *udev, const struct firmware *fw, int type) { struct hexline *hx; u8 *buf; int ret, pos = 0; u16 cpu_cs_register = cypress[type].cpu_cs_register; buf = kmalloc(sizeof(*hx), GFP_KERNEL); if (!buf) return -ENOMEM; hx = (struct hexline *)buf; /* stop the CPU */ buf[0] = 1; if (usb_cypress_writemem(udev, cpu_cs_register, buf, 1) != 1) err("could not stop the USB controller CPU."); while ((ret = dvb_usb_get_hexline(fw, hx, &pos)) > 0) { deb_fw("writing to address 0x%04x (buffer: 0x%02x %02x)\n", hx->addr, hx->len, hx->chk); ret = usb_cypress_writemem(udev, hx->addr, hx->data, hx->len); if (ret != hx->len) { err("error while transferring firmware (transferred size: %d, block size: %d)", ret, hx->len); ret = -EINVAL; break; } } if (ret < 0) { err("firmware download failed at %d with %d",pos,ret); kfree(buf); return ret; } if (ret == 0) { /* restart the CPU */ buf[0] = 0; if (usb_cypress_writemem(udev, cpu_cs_register, buf, 1) != 1) { err("could not restart the USB controller CPU."); ret = -EINVAL; } } else ret = -EIO; kfree(buf); return ret; }
168,230
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg) { const unsigned char *p; int plen; if (alg == NULL) return NULL; if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) return NULL; if (alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; return d2i_X509_ALGOR(NULL, &p, plen); } Commit Message: CWE ID:
static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg) { const unsigned char *p; int plen; if (alg == NULL || alg->parameter == NULL) return NULL; if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) return NULL; if (alg->parameter->type != V_ASN1_SEQUENCE) return NULL; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; return d2i_X509_ALGOR(NULL, &p, plen); }
164,720
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void LoadingStatsCollector::RecordPreconnectStats( std::unique_ptr<PreconnectStats> stats) { const GURL& main_frame_url = stats->url; auto it = preconnect_stats_.find(main_frame_url); if (it != preconnect_stats_.end()) { ReportPreconnectAccuracy(*it->second, std::map<GURL, OriginRequestSummary>()); preconnect_stats_.erase(it); } preconnect_stats_.emplace(main_frame_url, std::move(stats)); } 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 <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
void LoadingStatsCollector::RecordPreconnectStats( std::unique_ptr<PreconnectStats> stats) { const GURL& main_frame_url = stats->url; auto it = preconnect_stats_.find(main_frame_url); if (it != preconnect_stats_.end()) { ReportPreconnectAccuracy(*it->second, {}); preconnect_stats_.erase(it); } preconnect_stats_.emplace(main_frame_url, std::move(stats)); }
172,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SProcXFixesQueryVersion(ClientPtr client) { REQUEST(xXFixesQueryVersionReq); swaps(&stuff->length); swapl(&stuff->majorVersion); return (*ProcXFixesVector[stuff->xfixesReqType]) (client); } Commit Message: CWE ID: CWE-20
SProcXFixesQueryVersion(ClientPtr client) { REQUEST(xXFixesQueryVersionReq); REQUEST_SIZE_MATCH(xXFixesQueryVersionReq); swaps(&stuff->length); swapl(&stuff->majorVersion); return (*ProcXFixesVector[stuff->xfixesReqType]) (client); }
165,444
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void LauncherView::ButtonPressed(views::Button* sender, const views::Event& event) { if (dragging_) return; if (sender == overflow_button_) ShowOverflowMenu(); if (!delegate_) return; int view_index = view_model_->GetIndexOfView(sender); if (view_index == -1) return; switch (model_->items()[view_index].type) { case TYPE_TABBED: case TYPE_APP_PANEL: case TYPE_APP_SHORTCUT: case TYPE_PLATFORM_APP: delegate_->ItemClicked(model_->items()[view_index], event.flags()); break; case TYPE_APP_LIST: Shell::GetInstance()->ToggleAppList(); break; case TYPE_BROWSER_SHORTCUT: if (event.flags() & ui::EF_CONTROL_DOWN) delegate_->CreateNewWindow(); else delegate_->CreateNewTab(); break; } } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::ButtonPressed(views::Button* sender, const views::Event& event) { if (dragging_) return; if (sender == overflow_button_) { ShowOverflowBubble(); return; } if (!delegate_) return; int view_index = view_model_->GetIndexOfView(sender); if (view_index == -1) return; switch (model_->items()[view_index].type) { case TYPE_TABBED: case TYPE_APP_PANEL: case TYPE_APP_SHORTCUT: case TYPE_PLATFORM_APP: delegate_->ItemClicked(model_->items()[view_index], event.flags()); break; case TYPE_APP_LIST: Shell::GetInstance()->ToggleAppList(); break; case TYPE_BROWSER_SHORTCUT: if (event.flags() & ui::EF_CONTROL_DOWN) delegate_->CreateNewWindow(); else delegate_->CreateNewTab(); break; } }
170,887
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::unique_ptr<WebContents> CreateWebContents() { std::unique_ptr<WebContents> web_contents = CreateTestWebContents(); content::WebContentsTester::For(web_contents.get()) ->NavigateAndCommit(GURL("https://www.example.com")); return web_contents; } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
std::unique_ptr<WebContents> CreateWebContents() { std::unique_ptr<WebContents> web_contents = CreateTestWebContents(); ResourceCoordinatorTabHelper::CreateForWebContents(web_contents.get()); content::WebContentsTester::For(web_contents.get()) ->NavigateAndCommit(GURL("https://www.example.com")); base::RepeatingClosure run_loop_cb = base::BindRepeating( &base::TestMockTimeTaskRunner::RunUntilIdle, task_runner_); testing::WaitForLocalDBEntryToBeInitialized(web_contents.get(), run_loop_cb); testing::ExpireLocalDBObservationWindows(web_contents.get()); return web_contents; }
172,230
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata, const uint8_t *cert, size_t cert_len, krb5_const_principal princ, const void *opts, const struct _krb5_db_entry_new *db_entry, char ***authinds_out) { krb5_error_code ret; int valid_eku; const struct certauth_req_opts *req_opts = opts; *authinds_out = NULL; /* Verify the client EKU. */ ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx, &valid_eku); if (ret) return ret; if (!valid_eku) { TRACE_PKINIT_SERVER_EKU_REJECT(context); return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE; } return 0; } Commit Message: Fix certauth built-in module returns The PKINIT certauth eku module should never authoritatively authorize a certificate, because an extended key usage does not establish a relationship between the certificate and any specific user; it only establishes that the certificate was created for PKINIT client authentication. Therefore, pkinit_eku_authorize() should return KRB5_PLUGIN_NO_HANDLE on success, not 0. The certauth san module should pass if it does not find any SANs of the types it can match against; the presence of other types of SANs should not cause it to explicitly deny a certificate. Check for an empty result from crypto_retrieve_cert_sans() in verify_client_san(), instead of returning ENOENT from crypto_retrieve_cert_sans() when there are no SANs at all. ticket: 8561 CWE ID: CWE-287
pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata, const uint8_t *cert, size_t cert_len, krb5_const_principal princ, const void *opts, const struct _krb5_db_entry_new *db_entry, char ***authinds_out) { krb5_error_code ret; int valid_eku; const struct certauth_req_opts *req_opts = opts; *authinds_out = NULL; /* Verify the client EKU. */ ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx, &valid_eku); if (ret) return ret; if (!valid_eku) { TRACE_PKINIT_SERVER_EKU_REJECT(context); return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE; } return KRB5_PLUGIN_NO_HANDLE; }
170,174
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, serial->len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); }
169,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const Cluster* Segment::GetFirst() const { if ((m_clusters == NULL) || (m_clusterCount <= 0)) return &m_eos; Cluster* const pCluster = m_clusters[0]; assert(pCluster); return pCluster; } 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 Cluster* Segment::GetFirst() const Cluster* const pCluster = m_clusters[0]; assert(pCluster); return pCluster; }
174,322
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: _TIFFmalloc(tmsize_t s) { return (malloc((size_t) s)); } Commit Message: * libtiff/tif_{unix,vms,win32}.c (_TIFFmalloc): ANSI C does not require malloc() to return NULL pointer if requested allocation size is zero. Assure that _TIFFmalloc does. CWE ID: CWE-369
_TIFFmalloc(tmsize_t s) { if (s == 0) return ((void *) NULL); return (malloc((size_t) s)); }
169,459
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static char *print_value( cJSON *item, int depth, int fmt ) { char *out = 0; if ( ! item ) return 0; switch ( ( item->type ) & 255 ) { case cJSON_NULL: out = cJSON_strdup( "null" ); break; case cJSON_False: out = cJSON_strdup( "false" ); break; case cJSON_True: out = cJSON_strdup( "true" ); break; case cJSON_Number: out = print_number( item ); break; case cJSON_String: out = print_string( item ); break; case cJSON_Array: out = print_array( item, depth, fmt ); break; case cJSON_Object: out = print_object( item, depth, fmt ); break; } return out; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
static char *print_value( cJSON *item, int depth, int fmt ) static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p) { char *out=0; if (!item) return 0; if (p) { switch ((item->type)&255) { case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;} case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;} case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;} case cJSON_Number: out=print_number(item,p);break; case cJSON_String: out=print_string(item,p);break; case cJSON_Array: out=print_array(item,depth,fmt,p);break; case cJSON_Object: out=print_object(item,depth,fmt,p);break; } } else { switch ((item->type)&255) { case cJSON_NULL: out=cJSON_strdup("null"); break; case cJSON_False: out=cJSON_strdup("false");break; case cJSON_True: out=cJSON_strdup("true"); break; case cJSON_Number: out=print_number(item,0);break; case cJSON_String: out=print_string(item,0);break; case cJSON_Array: out=print_array(item,depth,fmt,0);break; case cJSON_Object: out=print_object(item,depth,fmt,0);break; } } return out; }
167,311
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_gss_ctx_id_rec *ctx; size_t i; if (minor_status == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *minor_status = 0; if (desired_object == GSS_C_NO_OID) return GSS_S_CALL_INACCESSIBLE_READ; if (data_set == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *data_set = GSS_C_NO_BUFFER_SET; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (!ctx->established) return GSS_S_NO_CONTEXT; for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/ sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) { if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) { return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status, context_handle, desired_object, data_set); } } *minor_status = EINVAL; return GSS_S_UNAVAILABLE; } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
krb5_gss_inquire_sec_context_by_oid (OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_gss_ctx_id_rec *ctx; size_t i; if (minor_status == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *minor_status = 0; if (desired_object == GSS_C_NO_OID) return GSS_S_CALL_INACCESSIBLE_READ; if (data_set == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; *data_set = GSS_C_NO_BUFFER_SET; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (ctx->terminated || !ctx->established) return GSS_S_NO_CONTEXT; for (i = 0; i < sizeof(krb5_gss_inquire_sec_context_by_oid_ops)/ sizeof(krb5_gss_inquire_sec_context_by_oid_ops[0]); i++) { if (g_OID_prefix_equal(desired_object, &krb5_gss_inquire_sec_context_by_oid_ops[i].oid)) { return (*krb5_gss_inquire_sec_context_by_oid_ops[i].func)(minor_status, context_handle, desired_object, data_set); } } *minor_status = EINVAL; return GSS_S_UNAVAILABLE; }
166,815
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void WebBluetoothServiceImpl::ClearState() { characteristic_id_to_notify_session_.clear(); pending_primary_services_requests_.clear(); descriptor_id_to_characteristic_id_.clear(); characteristic_id_to_service_id_.clear(); service_id_to_device_address_.clear(); connected_devices_.reset( new FrameConnectedBluetoothDevices(render_frame_host_)); device_chooser_controller_.reset(); BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this); } Commit Message: Ensure device choosers are closed on navigation The requestDevice() IPCs can race with navigation. This change ensures that choosers are closed on navigation and adds browser tests to exercise this for Web Bluetooth and WebUSB. Bug: 723503 Change-Id: I66760161220e17bd2be9309cca228d161fe76e9c Reviewed-on: https://chromium-review.googlesource.com/1099961 Commit-Queue: Reilly Grant <reillyg@chromium.org> Reviewed-by: Michael Wasserman <msw@chromium.org> Reviewed-by: Jeffrey Yasskin <jyasskin@chromium.org> Cr-Commit-Position: refs/heads/master@{#569900} CWE ID: CWE-362
void WebBluetoothServiceImpl::ClearState() { // Releasing the adapter will drop references to callbacks that have not yet // been executed. The binding must be closed first so that this is allowed. binding_.Close(); characteristic_id_to_notify_session_.clear(); pending_primary_services_requests_.clear(); descriptor_id_to_characteristic_id_.clear(); characteristic_id_to_service_id_.clear(); service_id_to_device_address_.clear(); connected_devices_.reset( new FrameConnectedBluetoothDevices(render_frame_host_)); device_chooser_controller_.reset(); BluetoothAdapterFactoryWrapper::Get().ReleaseAdapter(this); }
173,204
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void init_once(void *foo) { struct ext4_inode_info *ei = (struct ext4_inode_info *) foo; INIT_LIST_HEAD(&ei->i_orphan); init_rwsem(&ei->xattr_sem); init_rwsem(&ei->i_data_sem); inode_init_once(&ei->vfs_inode); } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-362
static void init_once(void *foo) { struct ext4_inode_info *ei = (struct ext4_inode_info *) foo; INIT_LIST_HEAD(&ei->i_orphan); init_rwsem(&ei->xattr_sem); init_rwsem(&ei->i_data_sem); init_rwsem(&ei->i_mmap_sem); inode_init_once(&ei->vfs_inode); }
167,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req, size_t *acl_len) { __be32 *savep; uint32_t attrlen, bitmap[3] = {0}; struct kvec *iov = req->rq_rcv_buf.head; int status; *acl_len = 0; if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0) goto out; if ((status = decode_attr_bitmap(xdr, bitmap)) != 0) goto out; if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0) goto out; if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U))) return -EIO; if (likely(bitmap[0] & FATTR4_WORD0_ACL)) { size_t hdrlen; u32 recvd; /* We ignore &savep and don't do consistency checks on * the attr length. Let userspace figure it out.... */ hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base; recvd = req->rq_rcv_buf.len - hdrlen; if (attrlen > recvd) { dprintk("NFS: server cheating in getattr" " acl reply: attrlen %u > recvd %u\n", attrlen, recvd); return -EINVAL; } xdr_read_pages(xdr, attrlen); *acl_len = attrlen; } else status = -EOPNOTSUPP; out: return status; } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: stable@kernel.org Signed-off-by: Andy Adamson <andros@netapp.com> Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID: CWE-189
static int decode_getacl(struct xdr_stream *xdr, struct rpc_rqst *req, struct nfs_getaclres *res) { __be32 *savep, *bm_p; uint32_t attrlen, bitmap[3] = {0}; struct kvec *iov = req->rq_rcv_buf.head; int status; res->acl_len = 0; if ((status = decode_op_hdr(xdr, OP_GETATTR)) != 0) goto out; bm_p = xdr->p; if ((status = decode_attr_bitmap(xdr, bitmap)) != 0) goto out; if ((status = decode_attr_length(xdr, &attrlen, &savep)) != 0) goto out; if (unlikely(bitmap[0] & (FATTR4_WORD0_ACL - 1U))) return -EIO; if (likely(bitmap[0] & FATTR4_WORD0_ACL)) { size_t hdrlen; u32 recvd; /* The bitmap (xdr len + bitmaps) and the attr xdr len words * are stored with the acl data to handle the problem of * variable length bitmaps.*/ xdr->p = bm_p; res->acl_data_offset = be32_to_cpup(bm_p) + 2; res->acl_data_offset <<= 2; /* We ignore &savep and don't do consistency checks on * the attr length. Let userspace figure it out.... */ hdrlen = (u8 *)xdr->p - (u8 *)iov->iov_base; attrlen += res->acl_data_offset; recvd = req->rq_rcv_buf.len - hdrlen; if (attrlen > recvd) { if (res->acl_flags & NFS4_ACL_LEN_REQUEST) { /* getxattr interface called with a NULL buf */ res->acl_len = attrlen; goto out; } dprintk("NFS: acl reply: attrlen %u > recvd %u\n", attrlen, recvd); return -EINVAL; } xdr_read_pages(xdr, attrlen); res->acl_len = attrlen; } else status = -EOPNOTSUPP; out: return status; }
165,719
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: cJSON *cJSON_GetArrayItem( cJSON *array, int item ) { cJSON *c = array->child; while ( c && item > 0 ) { --item; c = c->next; } return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_GetArrayItem( cJSON *array, int item )
167,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); }
167,034
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int string_check(char *buf, const char *buf2) { if(strcmp(buf, buf2)) { /* they shouldn't differ */ printf("sprintf failed:\nwe '%s'\nsystem: '%s'\n", buf, buf2); return 1; } return 0; } Commit Message: printf: fix floating point buffer overflow issues ... and add a bunch of floating point printf tests CWE ID: CWE-119
static int string_check(char *buf, const char *buf2) static int _string_check(int linenumber, char *buf, const char *buf2) { if(strcmp(buf, buf2)) { /* they shouldn't differ */ printf("sprintf line %d failed:\nwe '%s'\nsystem: '%s'\n", linenumber, buf, buf2); return 1; } return 0; }
169,437
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) { const uint16_t *ptr = (const uint16_t *)dat; ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat) l2tp_proxy_auth_id_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint16_t *ptr = (const uint16_t *)dat; if (length < 2) { ND_PRINT((ndo, "AVP too short")); return; } ND_PRINT((ndo, "%u", EXTRACT_16BITS(ptr) & L2TP_PROXY_AUTH_ID_MASK)); }
167,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: double VideoTrack::GetFrameRate() const { return m_rate; } 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
double VideoTrack::GetFrameRate() const
174,326
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static inline void uipc_wakeup_locked(void) { char sig_on = 1; BTIF_TRACE_EVENT("UIPC SEND WAKE UP"); send(uipc_main.signal_fds[1], &sig_on, sizeof(sig_on), 0); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static inline void uipc_wakeup_locked(void) { char sig_on = 1; BTIF_TRACE_EVENT("UIPC SEND WAKE UP"); TEMP_FAILURE_RETRY(send(uipc_main.signal_fds[1], &sig_on, sizeof(sig_on), 0)); }
173,499
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int cxusb_ctrl_msg(struct dvb_usb_device *d, u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen) { struct cxusb_state *st = d->priv; int ret, wo; if (1 + wlen > MAX_XFER_SIZE) { warn("i2c wr: len=%d is too big!\n", wlen); return -EOPNOTSUPP; } wo = (rbuf == NULL || rlen == 0); /* write-only */ mutex_lock(&d->data_mutex); st->data[0] = cmd; memcpy(&st->data[1], wbuf, wlen); if (wo) ret = dvb_usb_generic_write(d, st->data, 1 + wlen); else ret = dvb_usb_generic_rw(d, st->data, 1 + wlen, rbuf, rlen, 0); mutex_unlock(&d->data_mutex); return ret; } Commit Message: [media] cxusb: Use a dma capable buffer also for reading Commit 17ce039b4e54 ("[media] cxusb: don't do DMA on stack") added a kmalloc'ed bounce buffer for writes, but missed to do the same for reads. As the read only happens after the write is finished, we can reuse the same buffer. As dvb_usb_generic_rw handles a read length of 0 by itself, avoid calling it using the dvb_usb_generic_read wrapper function. Signed-off-by: Stefan Brüns <stefan.bruens@rwth-aachen.de> Signed-off-by: Mauro Carvalho Chehab <mchehab@s-opensource.com> CWE ID: CWE-119
static int cxusb_ctrl_msg(struct dvb_usb_device *d, u8 cmd, u8 *wbuf, int wlen, u8 *rbuf, int rlen) { struct cxusb_state *st = d->priv; int ret; if (1 + wlen > MAX_XFER_SIZE) { warn("i2c wr: len=%d is too big!\n", wlen); return -EOPNOTSUPP; } if (rlen > MAX_XFER_SIZE) { warn("i2c rd: len=%d is too big!\n", rlen); return -EOPNOTSUPP; } mutex_lock(&d->data_mutex); st->data[0] = cmd; memcpy(&st->data[1], wbuf, wlen); ret = dvb_usb_generic_rw(d, st->data, 1 + wlen, st->data, rlen, 0); if (!ret && rbuf && rlen) memcpy(rbuf, st->data, rlen); mutex_unlock(&d->data_mutex); return ret; }
168,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } return 0; }
173,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; } Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size. Bug: 25765591 Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6 CWE ID: CWE-254
void impeg2d_peek_next_start_code(dec_state_t *ps_dec) { stream_t *ps_stream; ps_stream = &ps_dec->s_bit_stream; impeg2d_bit_stream_flush_to_byte_boundary(ps_stream); while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) { impeg2d_bit_stream_get(ps_stream,8); } return; }
173,951
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CrosLibrary::TestApi::SetTouchpadLibrary( TouchpadLibrary* library, bool own) { library_->touchpad_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetTouchpadLibrary(
170,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: OmniboxPopupViewGtk::~OmniboxPopupViewGtk() { model_.reset(); g_object_unref(layout_); gtk_widget_destroy(window_); for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it) delete it->second; } Commit Message: GTK: Stop listening to gtk signals in the omnibox before destroying the model. BUG=123530 TEST=none Review URL: http://codereview.chromium.org/10103012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132498 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
OmniboxPopupViewGtk::~OmniboxPopupViewGtk() { // Stop listening to our signals before we destroy the model. I suspect that // we can race window destruction, otherwise. signal_registrar_.reset(); model_.reset(); g_object_unref(layout_); gtk_widget_destroy(window_); for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it) delete it->second; }
171,049
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void ResetScreenHandler::UpdateStatusChanged( const UpdateEngineClient::Status& status) { if (status.status == UpdateEngineClient::UPDATE_STATUS_ERROR) { base::DictionaryValue params; params.SetInteger("uiState", kErrorUIStateRollback); ShowScreen(OobeUI::kScreenErrorMessage, &params); } else if (status.status == UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) { DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart(); } } Commit Message: Rollback option put behind the flag. BUG=368860 Review URL: https://codereview.chromium.org/267393011 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@269753 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ResetScreenHandler::UpdateStatusChanged( const UpdateEngineClient::Status& status) { VLOG(1) << "Update status change to " << status.status; if (status.status == UpdateEngineClient::UPDATE_STATUS_ERROR) { base::DictionaryValue params; params.SetInteger("uiState", kErrorUIStateRollback); ShowScreen(OobeUI::kScreenErrorMessage, &params); } else if (status.status == UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) { DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart(); } }
171,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: juniper_atm1_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM1; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[0] == 0x80) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
juniper_atm1_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { int llc_hdrlen; struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_ATM1; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; if (l2info.cookie[0] == 0x80) { /* OAM cell ? */ oam_print(ndo, p, l2info.length, ATM_OAM_NOHEC); return l2info.header_len; } if (EXTRACT_24BITS(p) == 0xfefe03 || /* NLPID encaps ? */ EXTRACT_24BITS(p) == 0xaaaa03) { /* SNAP encaps ? */ llc_hdrlen = llc_print(ndo, p, l2info.length, l2info.caplen, NULL, NULL); if (llc_hdrlen > 0) return l2info.header_len; } if (p[0] == 0x03) { /* Cisco style NLPID encaps ? */ isoclns_print(ndo, p + 1, l2info.length - 1); /* FIXME check if frame was recognized */ return l2info.header_len; } if (ip_heuristic_guess(ndo, p, l2info.length) != 0) /* last try - vcmux encaps ? */ return l2info.header_len; return l2info.header_len; }
167,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: AccessibilityOrientation AXNodeObject::orientation() const { const AtomicString& ariaOrientation = getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation); AccessibilityOrientation orientation = AccessibilityOrientationUndefined; if (equalIgnoringCase(ariaOrientation, "horizontal")) orientation = AccessibilityOrientationHorizontal; else if (equalIgnoringCase(ariaOrientation, "vertical")) orientation = AccessibilityOrientationVertical; switch (roleValue()) { case ComboBoxRole: case ListBoxRole: case MenuRole: case ScrollBarRole: case TreeRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationVertical; return orientation; case MenuBarRole: case SliderRole: case SplitterRole: case TabListRole: case ToolbarRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationHorizontal; return orientation; case RadioGroupRole: case TreeGridRole: case TableRole: return orientation; default: return AXObject::orientation(); } } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
AccessibilityOrientation AXNodeObject::orientation() const { const AtomicString& ariaOrientation = getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation); AccessibilityOrientation orientation = AccessibilityOrientationUndefined; if (equalIgnoringASCIICase(ariaOrientation, "horizontal")) orientation = AccessibilityOrientationHorizontal; else if (equalIgnoringASCIICase(ariaOrientation, "vertical")) orientation = AccessibilityOrientationVertical; switch (roleValue()) { case ComboBoxRole: case ListBoxRole: case MenuRole: case ScrollBarRole: case TreeRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationVertical; return orientation; case MenuBarRole: case SliderRole: case SplitterRole: case TabListRole: case ToolbarRole: if (orientation == AccessibilityOrientationUndefined) orientation = AccessibilityOrientationHorizontal; return orientation; case RadioGroupRole: case TreeGridRole: case TableRole: return orientation; default: return AXObject::orientation(); } }
171,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep)) { return (-1); } n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); } Commit Message: CVE-2017-13014/White Board: Do more bounds checks. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). While we're at it, print a truncation error if the packets are truncated, rather than just, in effect, ignoring the result of the routines that print particular packet types. CWE ID: CWE-125
wb_prep(netdissect_options *ndo, const struct pkt_prep *prep, u_int len) { int n; const struct pgstate *ps; const u_char *ep = ndo->ndo_snapend; ND_PRINT((ndo, " wb-prep:")); if (len < sizeof(*prep) || !ND_TTEST(*prep)) return (-1); n = EXTRACT_32BITS(&prep->pp_n); ps = (const struct pgstate *)(prep + 1); while (--n >= 0 && ND_TTEST(*ps)) { const struct id_off *io, *ie; char c = '<'; ND_PRINT((ndo, " %u/%s:%u", EXTRACT_32BITS(&ps->slot), ipaddr_string(ndo, &ps->page.p_sid), EXTRACT_32BITS(&ps->page.p_uid))); io = (const struct id_off *)(ps + 1); for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) { ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off))); c = ','; } ND_PRINT((ndo, ">")); ps = (const struct pgstate *)io; } return ((const u_char *)ps <= ep? 0 : -1); }
167,878
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool ExtensionViewGuest::NavigateGuest(const std::string& src, bool force_navigation) { GURL url = extension_url_.Resolve(src); bool url_not_allowed = (url != GURL(url::kAboutBlankURL)) && (url.GetOrigin() != extension_url_.GetOrigin()); if (!url.is_valid() || url_not_allowed) return NavigateGuest(url::kAboutBlankURL, true /* force_navigation */); if (!force_navigation && (url_ == url)) return false; web_contents()->GetRenderProcessHost()->FilterURL(false, &url); web_contents()->GetController().LoadURL(url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); url_ = url; return true; } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} CWE ID: CWE-284
bool ExtensionViewGuest::NavigateGuest(const std::string& src, bool force_navigation) { GURL url = extension_url_.Resolve(src); bool url_not_allowed = url != GURL(url::kAboutBlankURL) && !url::IsSameOriginWith(url, extension_url_); if (!url.is_valid() || url_not_allowed) return NavigateGuest(url::kAboutBlankURL, true /* force_navigation */); if (!force_navigation && (url_ == url)) return false; web_contents()->GetRenderProcessHost()->FilterURL(false, &url); web_contents()->GetController().LoadURL(url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); url_ = url; return true; }
172,284
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool PermissionsData::CanRunOnPage(const Extension* extension, const GURL& document_url, const GURL& top_frame_url, int tab_id, int process_id, const URLPatternSet& permitted_url_patterns, std::string* error) const { if (g_policy_delegate && !g_policy_delegate->CanExecuteScriptOnPage( extension, document_url, top_frame_url, tab_id, process_id, error)) { return false; } bool can_execute_everywhere = CanExecuteScriptEverywhere(extension); if (!can_execute_everywhere && !ExtensionsClient::Get()->IsScriptableURL(document_url, error)) { return false; } if (!base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kExtensionsOnChromeURLs)) { if (document_url.SchemeIs(content::kChromeUIScheme) && !can_execute_everywhere) { if (error) *error = manifest_errors::kCannotAccessChromeUrl; return false; } } if (top_frame_url.SchemeIs(kExtensionScheme) && top_frame_url.GetOrigin() != Extension::GetBaseURLFromExtensionId(extension->id()).GetOrigin() && !can_execute_everywhere) { if (error) *error = manifest_errors::kCannotAccessExtensionUrl; return false; } if (HasTabSpecificPermissionToExecuteScript(tab_id, top_frame_url)) return true; bool can_access = permitted_url_patterns.MatchesURL(document_url); if (!can_access && error) { *error = ErrorUtils::FormatErrorMessage(manifest_errors::kCannotAccessPage, document_url.spec()); } return can_access; } Commit Message: Have the Debugger extension api check that it has access to the tab Check PermissionsData::CanAccessTab() prior to attaching the debugger. BUG=367567 Review URL: https://codereview.chromium.org/352523003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@280354 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool PermissionsData::CanRunOnPage(const Extension* extension, const GURL& document_url, const GURL& top_frame_url, int tab_id, int process_id, const URLPatternSet& permitted_url_patterns, std::string* error) const { if (g_policy_delegate && !g_policy_delegate->CanExecuteScriptOnPage( extension, document_url, top_frame_url, tab_id, process_id, error)) { return false; } if (IsRestrictedUrl(document_url, top_frame_url, extension, error)) return false; if (HasTabSpecificPermissionToExecuteScript(tab_id, top_frame_url)) return true; bool can_access = permitted_url_patterns.MatchesURL(document_url); if (!can_access && error) { *error = ErrorUtils::FormatErrorMessage(manifest_errors::kCannotAccessPage, document_url.spec()); } return can_access; }
171,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void UserSelectionScreen::FillUserDictionary( user_manager::User* user, bool is_owner, bool is_signin_to_add, proximity_auth::mojom::AuthType auth_type, const std::vector<std::string>* public_session_recommended_locales, base::DictionaryValue* user_dict) { const bool is_public_session = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const bool is_legacy_supervised_user = user->GetType() == user_manager::USER_TYPE_SUPERVISED; const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD; user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize()); user_dict->SetString(kKeyEmailAddress, user->display_email()); user_dict->SetString(kKeyDisplayName, user->GetDisplayName()); user_dict->SetBoolean(kKeyPublicAccount, is_public_session); user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user); user_dict->SetBoolean(kKeyChildUser, is_child_user); user_dict->SetBoolean(kKeyDesktopUser, false); user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type)); user_dict->SetBoolean(kKeySignedIn, user->is_logged_in()); user_dict->SetBoolean(kKeyIsOwner, is_owner); user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser()); user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user)); FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add); if (is_public_session) { AddPublicSessionDetailsToUserDictionaryEntry( user_dict, public_session_recommended_locales); } } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void UserSelectionScreen::FillUserDictionary( const user_manager::User* user, bool is_owner, bool is_signin_to_add, proximity_auth::mojom::AuthType auth_type, const std::vector<std::string>* public_session_recommended_locales, base::DictionaryValue* user_dict) { const bool is_public_session = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const bool is_legacy_supervised_user = user->GetType() == user_manager::USER_TYPE_SUPERVISED; const bool is_child_user = user->GetType() == user_manager::USER_TYPE_CHILD; user_dict->SetString(kKeyUsername, user->GetAccountId().Serialize()); user_dict->SetString(kKeyEmailAddress, user->display_email()); user_dict->SetString(kKeyDisplayName, user->GetDisplayName()); user_dict->SetBoolean(kKeyPublicAccount, is_public_session); user_dict->SetBoolean(kKeyLegacySupervisedUser, is_legacy_supervised_user); user_dict->SetBoolean(kKeyChildUser, is_child_user); user_dict->SetBoolean(kKeyDesktopUser, false); user_dict->SetInteger(kKeyInitialAuthType, static_cast<int>(auth_type)); user_dict->SetBoolean(kKeySignedIn, user->is_logged_in()); user_dict->SetBoolean(kKeyIsOwner, is_owner); user_dict->SetBoolean(kKeyIsActiveDirectory, user->IsActiveDirectoryUser()); user_dict->SetBoolean(kKeyAllowFingerprint, AllowFingerprintForUser(user)); FillMultiProfileUserPrefs(user, user_dict, is_signin_to_add); if (is_public_session) { AddPublicSessionDetailsToUserDictionaryEntry( user_dict, public_session_recommended_locales); } }
172,200
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: EntrySync* WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(WorkerGlobalScope& worker, const String& url, ExceptionState& exceptionState) { KURL completedURL = worker.completeURL(url); ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } if (!completedURL.isValid()) { exceptionState.throwDOMException(EncodingError, "the URL '" + url + "' is invalid."); return 0; } RefPtr<EntrySyncCallbackHelper> resolveURLHelper = EntrySyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = ResolveURICallbacks::create(resolveURLHelper->successCallback(), resolveURLHelper->errorCallback(), &worker); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->resolveURL(&worker, completedURL, callbacks.release()); return resolveURLHelper->getResult(exceptionState); } 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
EntrySync* WorkerGlobalScopeFileSystem::webkitResolveLocalFileSystemSyncURL(WorkerGlobalScope& worker, const String& url, ExceptionState& exceptionState) { KURL completedURL = worker.completeURL(url); ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem() || !secureContext->securityOrigin()->canRequest(completedURL)) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } if (!completedURL.isValid()) { exceptionState.throwDOMException(EncodingError, "the URL '" + url + "' is invalid."); return 0; } EntrySyncCallbackHelper* resolveURLHelper = EntrySyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = ResolveURICallbacks::create(resolveURLHelper->successCallback(), resolveURLHelper->errorCallback(), &worker); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->resolveURL(&worker, completedURL, callbacks.release()); return resolveURLHelper->getResult(exceptionState); }
171,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Blob::Blob(PassOwnPtr<BlobData> blobData, long long size) : m_type(blobData->contentType()) , m_size(size) { ASSERT(blobData); ScriptWrappable::init(this); m_internalURL = BlobURL::createInternalURL(); ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
Blob::Blob(PassOwnPtr<BlobData> blobData, long long size) : m_type(blobData->contentType()) , m_size(size) { ASSERT(blobData); ScriptWrappable::init(this); m_internalURL = BlobURL::createInternalURL(); BlobRegistry::registerBlobURL(m_internalURL, blobData); }
170,675
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: file_add_mapi_attrs (File* file, MAPI_Attr** attrs) { int i; for (i = 0; attrs[i]; i++) { MAPI_Attr* a = attrs[i]; if (a->num_values) { switch (a->name) { case MAPI_ATTACH_LONG_FILENAME: if (file->name) XFREE(file->name); file->name = strdup( (char*)a->values[0].data.buf ); break; case MAPI_ATTACH_DATA_OBJ: file->len = a->values[0].len; if (file->data) XFREE (file->data); file->data = CHECKED_XMALLOC (unsigned char, file->len); memmove (file->data, a->values[0].data.buf, file->len); break; case MAPI_ATTACH_MIME_TAG: if (file->mime_type) XFREE (file->mime_type); file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); break; case MAPI_ATTACH_CONTENT_ID: if (file->content_id) XFREE(file->content_id); file->content_id = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->content_id, a->values[0].data.buf, a->values[0].len); break; default: break; } } } } Commit Message: Check types to avoid invalid reads/writes. CWE ID: CWE-125
file_add_mapi_attrs (File* file, MAPI_Attr** attrs) { int i; for (i = 0; attrs[i]; i++) { MAPI_Attr* a = attrs[i]; if (a->num_values) { switch (a->name) { case MAPI_ATTACH_LONG_FILENAME: assert(a->type == szMAPI_STRING); if (file->name) XFREE(file->name); file->name = strdup( (char*)a->values[0].data.buf ); break; case MAPI_ATTACH_DATA_OBJ: assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT)); file->len = a->values[0].len; if (file->data) XFREE (file->data); file->data = CHECKED_XMALLOC (unsigned char, file->len); memmove (file->data, a->values[0].data.buf, file->len); break; case MAPI_ATTACH_MIME_TAG: assert(a->type == szMAPI_STRING); if (file->mime_type) XFREE (file->mime_type); file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); break; case MAPI_ATTACH_CONTENT_ID: assert(a->type == szMAPI_STRING); if (file->content_id) XFREE(file->content_id); file->content_id = CHECKED_XMALLOC (char, a->values[0].len); memmove (file->content_id, a->values[0].data.buf, a->values[0].len); break; default: break; } } } }
168,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void __exit ipgre_fini(void) { rtnl_link_unregister(&ipgre_tap_ops); rtnl_link_unregister(&ipgre_link_ops); unregister_pernet_device(&ipgre_net_ops); if (inet_del_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) printk(KERN_INFO "ipgre close: can't remove protocol\n"); } Commit Message: gre: fix netns vs proto registration ordering GRE protocol receive hook can be called right after protocol addition is done. If netns stuff is not yet initialized, we're going to oops in net_generic(). This is remotely oopsable if ip_gre is compiled as module and packet comes at unfortunate moment of module loading. Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
static void __exit ipgre_fini(void) { rtnl_link_unregister(&ipgre_tap_ops); rtnl_link_unregister(&ipgre_link_ops); if (inet_del_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) printk(KERN_INFO "ipgre close: can't remove protocol\n"); unregister_pernet_device(&ipgre_net_ops); }
165,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (ChromeWebUIControllerFactory::GetInstance()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool DebuggerFunction::InitTabContents() { Value* debuggee; EXTENSION_FUNCTION_VALIDATE(args_->Get(0, &debuggee)); DictionaryValue* dict = static_cast<DictionaryValue*>(debuggee); EXTENSION_FUNCTION_VALIDATE(dict->GetInteger(keys::kTabIdKey, &tab_id_)); contents_ = NULL; TabContentsWrapper* wrapper = NULL; bool result = ExtensionTabUtil::GetTabById( tab_id_, profile(), include_incognito(), NULL, NULL, &wrapper, NULL); if (!result || !wrapper) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kNoTabError, base::IntToString(tab_id_)); return false; } contents_ = wrapper->web_contents(); if (content::GetContentClient()->HasWebUIScheme( contents_->GetURL())) { error_ = ExtensionErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, contents_->GetURL().scheme()); return false; } return true; }
171,006
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool CheckClientDownloadRequest::ShouldUploadForMalwareScan( DownloadCheckResultReason reason) { if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads)) return false; if (reason != DownloadCheckResultReason::REASON_DOWNLOAD_SAFE && reason != DownloadCheckResultReason::REASON_DOWNLOAD_UNCOMMON && reason != DownloadCheckResultReason::REASON_VERDICT_UNKNOWN) return false; content::BrowserContext* browser_context = content::DownloadItemUtils::GetBrowserContext(item_); if (!browser_context) return false; Profile* profile = Profile::FromBrowserContext(browser_context); if (!profile) return false; int send_files_for_malware_check = profile->GetPrefs()->GetInteger( prefs::kSafeBrowsingSendFilesForMalwareCheck); if (send_files_for_malware_check != SendFilesForMalwareCheckValues::SEND_DOWNLOADS && send_files_for_malware_check != SendFilesForMalwareCheckValues::SEND_UPLOADS_AND_DOWNLOADS) return false; return !policy::BrowserDMTokenStorage::Get()->RetrieveDMToken().empty(); } Commit Message: Migrate download_protection code to new DM token class. Migrates RetrieveDMToken calls to use the new BrowserDMToken class. Bug: 1020296 Change-Id: Icef580e243430d73b6c1c42b273a8540277481d9 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1904234 Commit-Queue: Dominique Fauteux-Chapleau <domfc@chromium.org> Reviewed-by: Tien Mai <tienmai@chromium.org> Reviewed-by: Daniel Rubery <drubery@chromium.org> Cr-Commit-Position: refs/heads/master@{#714196} CWE ID: CWE-20
bool CheckClientDownloadRequest::ShouldUploadForMalwareScan( DownloadCheckResultReason reason) { if (!base::FeatureList::IsEnabled(kDeepScanningOfDownloads)) return false; if (reason != DownloadCheckResultReason::REASON_DOWNLOAD_SAFE && reason != DownloadCheckResultReason::REASON_DOWNLOAD_UNCOMMON && reason != DownloadCheckResultReason::REASON_VERDICT_UNKNOWN) return false; content::BrowserContext* browser_context = content::DownloadItemUtils::GetBrowserContext(item_); if (!browser_context) return false; Profile* profile = Profile::FromBrowserContext(browser_context); if (!profile) return false; int send_files_for_malware_check = profile->GetPrefs()->GetInteger( prefs::kSafeBrowsingSendFilesForMalwareCheck); if (send_files_for_malware_check != SendFilesForMalwareCheckValues::SEND_DOWNLOADS && send_files_for_malware_check != SendFilesForMalwareCheckValues::SEND_UPLOADS_AND_DOWNLOADS) return false; // If there's no valid DM token, the upload will fail, so we can skip // uploading now. return BrowserDMTokenStorage::Get()->RetrieveBrowserDMToken().is_valid(); }
172,357
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh, bool source_is_modifiable) { DCHECK(print_preview_rfh_); if (rfh != print_preview_rfh_) return; PrintPreviewDialogController* dialog_controller = PrintPreviewDialogController::GetInstance(); if (!dialog_controller) { PrintPreviewDone(); return; } dialog_controller->PrintPreview(web_contents()); PrintHostMsg_RequestPrintPreview_Params params; params.is_modifiable = source_is_modifiable; PrintPreviewUI::SetInitialParams( dialog_controller->GetPrintPreviewForContents(web_contents()), params); } Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen. BUG=670135, 550017, 726761, 728276 Review-Url: https://codereview.chromium.org/2906133004 Cr-Commit-Position: refs/heads/master@{#478884} CWE ID: CWE-20
void PrintViewManager::OnShowScriptedPrintPreview(content::RenderFrameHost* rfh, bool source_is_modifiable) { DCHECK(print_preview_rfh_); if (rfh != print_preview_rfh_) return; PrintPreviewDialogController* dialog_controller = PrintPreviewDialogController::GetInstance(); if (!dialog_controller) { PrintPreviewDone(); return; } // Running a dialog causes an exit to webpage-initiated fullscreen. // http://crbug.com/728276 if (web_contents()->IsFullscreenForCurrentTab()) web_contents()->ExitFullscreen(true); dialog_controller->PrintPreview(web_contents()); PrintHostMsg_RequestPrintPreview_Params params; params.is_modifiable = source_is_modifiable; PrintPreviewUI::SetInitialParams( dialog_controller->GetPrintPreviewForContents(web_contents()), params); }
172,314
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, unsigned char*& buf, size_t& buflen) { assert(pReader); assert(pos >= 0); long long total, available; long status = pReader->Length(&total, &available); assert(status >= 0); assert((total < 0) || (available <= total)); if (status < 0) return false; long len; const long long id = ReadUInt(pReader, pos, len); assert(id >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); if ((unsigned long)id != id_) return false; pos += len; // consume id const long long size_ = ReadUInt(pReader, pos, len); assert(size_ >= 0); assert(len > 0); assert(len <= 8); assert((pos + len) <= available); pos += len; // consume length of size of payload assert((pos + size_) <= available); const long buflen_ = static_cast<long>(size_); buf = new (std::nothrow) unsigned char[buflen_]; assert(buf); // TODO status = pReader->Read(pos, buflen_, buf); assert(status == 0); // TODO buflen = buflen_; pos += size_; // consume size of payload return true; } 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
bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, bool Match(IMkvReader* pReader, long long& pos, unsigned long expected_id, unsigned char*& buf, size_t& buflen) { if (!pReader || pos < 0) return false; long long total = 0; long long available = 0; long status = pReader->Length(&total, &available); if (status < 0 || (total >= 0 && available > total)) return false; long len = 0; const long long id = ReadID(pReader, pos, len); if (id < 0 || (available - pos) > len) return false; if (static_cast<unsigned long>(id) != expected_id) return false; pos += len; // consume id const long long size = ReadUInt(pReader, pos, len); if (size < 0 || len <= 0 || len > 8 || (available - pos) > len) return false; unsigned long long rollover_check = static_cast<unsigned long long>(pos) + len; if (rollover_check > LONG_LONG_MAX) return false; pos += len; // consume length of size of payload rollover_check = static_cast<unsigned long long>(pos) + size; if (rollover_check > LONG_LONG_MAX) return false; if ((pos + size) > available) return false; if (size >= LONG_MAX) return false; const long buflen_ = static_cast<long>(size); buf = SafeArrayAlloc<unsigned char>(1, buflen_); if (!buf) return false; status = pReader->Read(pos, buflen_, buf); if (status != 0) return false; buflen = buflen_; pos += size; // consume size of payload return true; }
173,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int sysMapFile(const char* fn, MemMapping* pMap) { memset(pMap, 0, sizeof(*pMap)); if (fn && fn[0] == '@') { FILE* mapf = fopen(fn+1, "r"); if (mapf == NULL) { LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno)); return -1; } if (sysMapBlockFile(mapf, pMap) != 0) { LOGW("Map of '%s' failed\n", fn); return -1; } fclose(mapf); } else { int fd = open(fn, O_RDONLY, 0); if (fd < 0) { LOGE("Unable to open '%s': %s\n", fn, strerror(errno)); return -1; } if (sysMapFD(fd, pMap) != 0) { LOGE("Map of '%s' failed\n", fn); close(fd); return -1; } close(fd); } return 0; } Commit Message: Fix integer overflows in recovery procedure. Bug: 26960931 Change-Id: Ieae45caccfb4728fcf514f0d920976585d8e6caf (cherry picked from commit 4f2df162c6ab4a71ca86e4b38735b681729c353b) CWE ID: CWE-189
int sysMapFile(const char* fn, MemMapping* pMap) { memset(pMap, 0, sizeof(*pMap)); if (fn && fn[0] == '@') { FILE* mapf = fopen(fn+1, "r"); if (mapf == NULL) { LOGV("Unable to open '%s': %s\n", fn+1, strerror(errno)); return -1; } if (sysMapBlockFile(mapf, pMap) != 0) { LOGW("Map of '%s' failed\n", fn); fclose(mapf); return -1; } fclose(mapf); } else { int fd = open(fn, O_RDONLY, 0); if (fd < 0) { LOGE("Unable to open '%s': %s\n", fn, strerror(errno)); return -1; } if (sysMapFD(fd, pMap) != 0) { LOGE("Map of '%s' failed\n", fn); close(fd); return -1; } close(fd); } return 0; }
173,905
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int parse_arguments(int *argc_p, const char ***argv_p) { static poptContext pc; char *ref = lp_refuse_options(module_id); const char *arg, **argv = *argv_p; int argc = *argc_p; int opt; if (ref && *ref) set_refuse_options(ref); set_refuse_options("log-file*"); #ifdef ICONV_OPTION if (!*lp_charset(module_id)) set_refuse_options("iconv"); #endif } Commit Message: CWE ID:
int parse_arguments(int *argc_p, const char ***argv_p) { static poptContext pc; char *ref = lp_refuse_options(module_id); const char *arg, **argv = *argv_p; int argc = *argc_p; int opt; int orig_protect_args = protect_args; if (ref && *ref) set_refuse_options(ref); set_refuse_options("log-file*"); #ifdef ICONV_OPTION if (!*lp_charset(module_id)) set_refuse_options("iconv"); #endif }
165,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: std::string ProcessRawBytesWithSeparators(const unsigned char* data, size_t data_length, char hex_separator, char line_separator) { static const char kHexChars[] = "0123456789ABCDEF"; std::string ret; size_t kMin = 0U; ret.reserve(std::max(kMin, data_length * 3 - 1)); for (size_t i = 0; i < data_length; ++i) { unsigned char b = data[i]; ret.push_back(kHexChars[(b >> 4) & 0xf]); ret.push_back(kHexChars[b & 0xf]); if (i + 1 < data_length) { if ((i + 1) % 16 == 0) ret.push_back(line_separator); else ret.push_back(hex_separator); } } return ret; } Commit Message: return early from ProcessRawBytesWithSeperators() when data length is 0 BUG=109717 TEST=N/A Review URL: http://codereview.chromium.org/9169028 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@117241 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
std::string ProcessRawBytesWithSeparators(const unsigned char* data, size_t data_length, char hex_separator, char line_separator) { static const char kHexChars[] = "0123456789ABCDEF"; std::string ret; size_t kMin = 0U; if (!data_length) return ""; ret.reserve(std::max(kMin, data_length * 3 - 1)); for (size_t i = 0; i < data_length; ++i) { unsigned char b = data[i]; ret.push_back(kHexChars[(b >> 4) & 0xf]); ret.push_back(kHexChars[b & 0xf]); if (i + 1 < data_length) { if ((i + 1) % 16 == 0) ret.push_back(line_separator); else ret.push_back(hex_separator); } } return ret; }
170,975
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int main() { gdImagePtr im; char *buffer; size_t size; size = read_test_file(&buffer, "heap_overflow.tga"); im = gdImageCreateFromTgaPtr(size, (void *) buffer); gdTestAssert(im == NULL); free(buffer); return gdNumFailures(); } Commit Message: Fix OOB reads of the TGA decompression buffer It is possible to craft TGA files which will overflow the decompression buffer, but not the image's bitmap. Therefore we also have to check for potential decompression buffer overflows. This issue had been reported by Ibrahim El-Sayed to security@libgd.org; a modified case exposing an off-by-one error of the first patch had been provided by Konrad Beckmann. This commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906 as well. CWE ID: CWE-125
int main() { check_file("heap_overflow_1.tga"); check_file("heap_overflow_2.tga"); return gdNumFailures(); } static void check_file(char *basename) { gdImagePtr im; char *buffer; size_t size; size = read_test_file(&buffer, basename); im = gdImageCreateFromTgaPtr(size, (void *) buffer); gdTestAssert(im == NULL); free(buffer); }
170,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static unsigned int variance_ref(const uint8_t *ref, const uint8_t *src, int l2w, int l2h, unsigned int *sse_ptr) { int se = 0; unsigned int sse = 0; const int w = 1 << l2w, h = 1 << l2h; for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int diff = ref[w * y + x] - src[w * y + x]; se += diff; sse += diff * diff; } //// Truncate high bit depth results by downshifting (with rounding) by: //// 2 * (bit_depth - 8) for sse //// (bit_depth - 8) for se } *sse_ptr = sse; return sse - (((int64_t) se * se) >> (l2w + l2h)); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
static unsigned int variance_ref(const uint8_t *ref, const uint8_t *src, //// Truncate high bit depth results by downshifting (with rounding) by: //// 2 * (bit_depth - 8) for sse //// (bit_depth - 8) for se static void RoundHighBitDepth(int bit_depth, int64_t *se, uint64_t *sse) { switch (bit_depth) { case VPX_BITS_12: *sse = (*sse + 128) >> 8; *se = (*se + 8) >> 4; break; case VPX_BITS_10: *sse = (*sse + 8) >> 4; *se = (*se + 2) >> 2; break; case VPX_BITS_8: default: break; } }
174,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: kdc_process_s4u2proxy_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, const krb5_enc_tkt_part *t2enc, const krb5_db_entry *server, krb5_const_principal server_princ, krb5_const_principal proxy_princ, const char **status) { krb5_error_code errcode; /* * Constrained delegation is mutually exclusive with renew/forward/etc. * 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 & (NON_TGT_OPTION | KDC_OPT_ENC_TKT_IN_SKEY)) { return KRB5KDC_ERR_BADOPTION; } /* Ensure that evidence ticket server matches TGT client */ if (!krb5_principal_compare(kdc_context, server->princ, /* after canon */ server_princ)) { return KRB5KDC_ERR_SERVER_NOMATCH; } if (!isflagset(t2enc->flags, TKT_FLG_FORWARDABLE)) { *status = "EVIDENCE_TKT_NOT_FORWARDABLE"; return KRB5_TKT_NOT_FORWARDABLE; } /* Backend policy check */ errcode = check_allowed_to_delegate_to(kdc_context, t2enc->client, server, proxy_princ); if (errcode) { *status = "NOT_ALLOWED_TO_DELEGATE"; return errcode; } return 0; } Commit Message: Prevent KDC unset status assertion failures Assign status values if S4U2Self padata fails to decode, if an S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request uses an evidence ticket which does not match the canonicalized request server principal name. Reported by Samuel Cabrero. If a status value is not assigned during KDC processing, default to "UNKNOWN_REASON" rather than failing an assertion. This change will prevent future denial of service bugs due to similar mistakes, and will allow us to omit assigning status values for unlikely errors such as small memory allocation failures. CVE-2017-11368: In MIT krb5 1.7 and later, an authenticated attacker can cause an assertion failure in krb5kdc by sending an invalid S4U2Self or S4U2Proxy request. CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C ticket: 8599 (new) target_version: 1.15-next target_version: 1.14-next tags: pullup CWE ID: CWE-617
kdc_process_s4u2proxy_req(kdc_realm_t *kdc_active_realm, krb5_kdc_req *request, const krb5_enc_tkt_part *t2enc, const krb5_db_entry *server, krb5_const_principal server_princ, krb5_const_principal proxy_princ, const char **status) { krb5_error_code errcode; /* * Constrained delegation is mutually exclusive with renew/forward/etc. * 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 & (NON_TGT_OPTION | KDC_OPT_ENC_TKT_IN_SKEY)) { *status = "INVALID_S4U2PROXY_OPTIONS"; return KRB5KDC_ERR_BADOPTION; } /* Ensure that evidence ticket server matches TGT client */ if (!krb5_principal_compare(kdc_context, server->princ, /* after canon */ server_princ)) { *status = "EVIDENCE_TICKET_MISMATCH"; return KRB5KDC_ERR_SERVER_NOMATCH; } if (!isflagset(t2enc->flags, TKT_FLG_FORWARDABLE)) { *status = "EVIDENCE_TKT_NOT_FORWARDABLE"; return KRB5_TKT_NOT_FORWARDABLE; } /* Backend policy check */ errcode = check_allowed_to_delegate_to(kdc_context, t2enc->client, server, proxy_princ); if (errcode) { *status = "NOT_ALLOWED_TO_DELEGATE"; return errcode; } return 0; }
168,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: UpdateLibrary* CrosLibrary::GetUpdateLibrary() { return update_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
UpdateLibrary* CrosLibrary::GetUpdateLibrary() {
170,634
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: const CuePoint* Cues::GetFirst() const { if (m_cue_points == NULL) return NULL; if (m_count == 0) return NULL; #if 0 LoadCuePoint(); //init cues const size_t count = m_count + m_preload_count; if (count == 0) //weird return NULL; #endif CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[0]; assert(pCP); assert(pCP->GetTimeCode() >= 0); return pCP; } 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 CuePoint* Cues::GetFirst() const if (m_count == 0) return NULL; #if 0 LoadCuePoint(); //init cues const size_t count = m_count + m_preload_count; if (count == 0) //weird return NULL; #endif CuePoint* const* const pp = m_cue_points; assert(pp); CuePoint* const pCP = pp[0]; assert(pCP); assert(pCP->GetTimeCode() >= 0); return pCP; }
174,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); put_io_context(ioc); } } Commit Message: block: Fix io_context leak after clone with CLONE_IO With CLONE_IO, copy_io() increments both ioc->refcount and ioc->nr_tasks. However exit_io_context() only decrements ioc->refcount if ioc->nr_tasks reaches 0. Always call put_io_context() in exit_io_context(). Signed-off-by: Louis Rilling <louis.rilling@kerlabs.com> Signed-off-by: Jens Axboe <jens.axboe@oracle.com> CWE ID: CWE-20
void exit_io_context(void) { struct io_context *ioc; task_lock(current); ioc = current->io_context; current->io_context = NULL; task_unlock(current); if (atomic_dec_and_test(&ioc->nr_tasks)) { if (ioc->aic && ioc->aic->exit) ioc->aic->exit(ioc->aic); cfq_exit(ioc); } put_io_context(ioc); }
165,648
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static void copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); if (rv) fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); unlink(src); } Commit Message: replace copy_file with copy_file_as_user CWE ID: CWE-269
static void copy_asoundrc(void) { char *src = RUN_ASOUNDRC_FILE ; char *dest; if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); fs_logger2("clone", dest); unlink(src); }
170,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: asocket* find_local_socket(unsigned local_id, unsigned peer_id) { asocket* s; asocket* result = NULL; adb_mutex_lock(&socket_list_lock); for (s = local_socket_list.next; s != &local_socket_list; s = s->next) { if (s->id != local_id) { continue; } if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) { result = s; } break; } adb_mutex_unlock(&socket_list_lock); return result; } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
asocket* find_local_socket(unsigned local_id, unsigned peer_id) { asocket* s; asocket* result = NULL; std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); for (s = local_socket_list.next; s != &local_socket_list; s = s->next) { if (s->id != local_id) { continue; } if (peer_id == 0 || (s->peer && s->peer->id == peer_id)) { result = s; } break; } return result; }
174,151
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static int tight_fill_palette(VncState *vs, int x, int y, size_t count, uint32_t *bg, uint32_t *fg, VncPalette **palette) { int max; max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor; if (max < 2 && count >= tight_conf[vs->tight.compression].mono_min_rect_size) { max = 2; } if (max >= 256) { max = 256; } switch(vs->clientds.pf.bytes_per_pixel) { case 4: return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette); case 2: return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette); default: max = 2; return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette); } return 0; } Commit Message: CWE ID: CWE-125
static int tight_fill_palette(VncState *vs, int x, int y, size_t count, uint32_t *bg, uint32_t *fg, VncPalette **palette) { int max; max = count / tight_conf[vs->tight.compression].idx_max_colors_divisor; if (max < 2 && count >= tight_conf[vs->tight.compression].mono_min_rect_size) { max = 2; } if (max >= 256) { max = 256; } switch (vs->client_pf.bytes_per_pixel) { case 4: return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette); case 2: return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette); default: max = 2; return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette); } return 0; }
165,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void CrosLibrary::TestApi::SetCryptohomeLibrary( CryptohomeLibrary* library, bool own) { library_->crypto_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetCryptohomeLibrary(
170,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; assert(p); delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pSeekHead; } 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
Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pTags; delete m_pSeekHead; }
173,870
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG t1,t2; BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); r[6]=c1; r[7]=c2; } Commit Message: Fix for CVE-2014-3570 (with minor bn_asm.c revamp). Reviewed-by: Emilia Kasper <emilia@openssl.org> CWE ID: CWE-310
void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1,c2,c3; c1=0; c2=0; c3=0; sqr_add_c(a,0,c1,c2,c3); r[0]=c1; c1=0; sqr_add_c2(a,1,0,c2,c3,c1); r[1]=c2; c2=0; sqr_add_c(a,1,c3,c1,c2); sqr_add_c2(a,2,0,c3,c1,c2); r[2]=c3; c3=0; sqr_add_c2(a,3,0,c1,c2,c3); sqr_add_c2(a,2,1,c1,c2,c3); r[3]=c1; c1=0; sqr_add_c(a,2,c2,c3,c1); sqr_add_c2(a,3,1,c2,c3,c1); r[4]=c2; c2=0; sqr_add_c2(a,3,2,c3,c1,c2); r[5]=c3; c3=0; sqr_add_c(a,3,c1,c2,c3); r[6]=c1; r[7]=c2; }
166,830
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::ListValue* val) const { v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize())); for (size_t i = 0; i < val->GetSize(); ++i) { const base::Value* child = NULL; CHECK(val->Get(i, &child)); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, child); CHECK(!child_v8.IsEmpty()); v8::TryCatch try_catch(isolate); result->Set(static_cast<uint32_t>(i), child_v8); if (try_catch.HasCaught()) LOG(ERROR) << "Setter for index " << i << " threw an exception."; } return result; } Commit Message: V8ValueConverter::ToV8Value should not trigger setters BUG=606390 Review URL: https://codereview.chromium.org/1918793003 Cr-Commit-Position: refs/heads/master@{#390045} CWE ID:
v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array( v8::Isolate* isolate, v8::Local<v8::Object> creation_context, const base::ListValue* val) const { v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize())); // TODO(robwu): Callers should pass in the context. v8::Local<v8::Context> context = isolate->GetCurrentContext(); for (size_t i = 0; i < val->GetSize(); ++i) { const base::Value* child = NULL; CHECK(val->Get(i, &child)); v8::Local<v8::Value> child_v8 = ToV8ValueImpl(isolate, creation_context, child); CHECK(!child_v8.IsEmpty()); v8::Maybe<bool> maybe = result->CreateDataProperty(context, static_cast<uint32_t>(i), child_v8); if (!maybe.IsJust() || !maybe.FromJust()) LOG(ERROR) << "Failed to set value at index " << i; } return result; }
173,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: int main(int argc, char *argv[]) { int ret; struct lxc_lock *lock; lock = lxc_newlock(NULL, NULL); if (!lock) { fprintf(stderr, "%d: failed to get unnamed lock\n", __LINE__); exit(1); } ret = lxclock(lock, 0); if (ret) { fprintf(stderr, "%d: failed to take unnamed lock (%d)\n", __LINE__, ret); exit(1); } ret = lxcunlock(lock); if (ret) { fprintf(stderr, "%d: failed to put unnamed lock (%d)\n", __LINE__, ret); exit(1); } lxc_putlock(lock); lock = lxc_newlock("/var/lib/lxc", mycontainername); if (!lock) { fprintf(stderr, "%d: failed to get lock\n", __LINE__); exit(1); } struct stat sb; char *pathname = RUNTIME_PATH "/lock/lxc/var/lib/lxc/"; ret = stat(pathname, &sb); if (ret != 0) { fprintf(stderr, "%d: filename %s not created\n", __LINE__, pathname); exit(1); } lxc_putlock(lock); test_two_locks(); fprintf(stderr, "all tests passed\n"); exit(ret); } Commit Message: CVE-2015-1331: lxclock: use /run/lxc/lock rather than /run/lock/lxc This prevents an unprivileged user to use LXC to create arbitrary file on the filesystem. Signed-off-by: Serge Hallyn <serge.hallyn@ubuntu.com> Signed-off-by: Tyler Hicks <tyhicks@canonical.com> Acked-by: Stéphane Graber <stgraber@ubuntu.com> CWE ID: CWE-59
int main(int argc, char *argv[]) { int ret; struct lxc_lock *lock; lock = lxc_newlock(NULL, NULL); if (!lock) { fprintf(stderr, "%d: failed to get unnamed lock\n", __LINE__); exit(1); } ret = lxclock(lock, 0); if (ret) { fprintf(stderr, "%d: failed to take unnamed lock (%d)\n", __LINE__, ret); exit(1); } ret = lxcunlock(lock); if (ret) { fprintf(stderr, "%d: failed to put unnamed lock (%d)\n", __LINE__, ret); exit(1); } lxc_putlock(lock); lock = lxc_newlock("/var/lib/lxc", mycontainername); if (!lock) { fprintf(stderr, "%d: failed to get lock\n", __LINE__); exit(1); } struct stat sb; char *pathname = RUNTIME_PATH "/lxc/lock/var/lib/lxc/"; ret = stat(pathname, &sb); if (ret != 0) { fprintf(stderr, "%d: filename %s not created\n", __LINE__, pathname); exit(1); } lxc_putlock(lock); test_two_locks(); fprintf(stderr, "all tests passed\n"); exit(ret); }
166,726
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register z_crc_t c; register const z_crc_t FAR *buf4; c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const z_crc_t FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf4++; buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(ZSWAP32(c)); } Commit Message: Avoid pre-decrement of pointer in big-endian CRC calculation. There was a small optimization for PowerPCs to pre-increment a pointer when accessing a word, instead of post-incrementing. This required prefacing the loop with a decrement of the pointer, possibly pointing before the object passed. This is not compliant with the C standard, for which decrementing a pointer before its allocated memory is undefined. When tested on a modern PowerPC with a modern compiler, the optimization no longer has any effect. Due to all that, and per the recommendation of a security audit of the zlib code by Trail of Bits and TrustInSoft, in support of the Mozilla Foundation, this "optimization" was removed, in order to avoid the possibility of undefined behavior. CWE ID: CWE-189
local unsigned long crc32_big(crc, buf, len) unsigned long crc; const unsigned char FAR *buf; unsigned len; { register z_crc_t c; register const z_crc_t FAR *buf4; c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } buf4 = (const z_crc_t FAR *)(const void FAR *)buf; while (len >= 32) { DOBIG32; len -= 32; } while (len >= 4) { DOBIG4; len -= 4; } buf = (const unsigned char FAR *)buf4; if (len) do { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; return (unsigned long)(ZSWAP32(c)); }
168,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) { cJSON *current_element = NULL; if ((object == NULL) || (name == NULL)) { return NULL; } current_element = object->child; if (case_sensitive) { while ((current_element != NULL) && (strcmp(name, current_element->string) != 0)) { current_element = current_element->next; } } else { while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) { current_element = current_element->next; } } return current_element; } Commit Message: Fix crash of cJSON_GetObjectItemCaseSensitive when calling it on arrays CWE ID: CWE-754
static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) { cJSON *current_element = NULL; if ((object == NULL) || (name == NULL)) { return NULL; } current_element = object->child; if (case_sensitive) { while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) { current_element = current_element->next; } } else { while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) { current_element = current_element->next; } } if ((current_element == NULL) || (current_element->string == NULL)) { return NULL; } return current_element; }
169,480
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) { DCHECK(message_loop()->BelongsToCurrentThread()); if (!stream_id_) return; if (state == AudioOutputIPCDelegate::kError) { DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)"; base::AutoLock auto_lock_(audio_thread_lock_); if (audio_thread_.get() && !audio_thread_->IsStopped()) callback_->OnRenderError(); } } Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call. I've kept my unit test changes intact but disabled until I get a proper fix. BUG=147499,150805 TBR=henrika Review URL: https://codereview.chromium.org/10946040 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void AudioOutputDevice::OnStateChanged(AudioOutputIPCDelegate::State state) { DCHECK(message_loop()->BelongsToCurrentThread()); if (!stream_id_) return; if (state == AudioOutputIPCDelegate::kError) { DLOG(WARNING) << "AudioOutputDevice::OnStateChanged(kError)"; if (!audio_thread_.IsStopped()) callback_->OnRenderError(); } }
170,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: void cJSON_DeleteItemFromObject( cJSON *object, const char *string ) { cJSON_Delete( cJSON_DetachItemFromObject( object, string ) ); } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
void cJSON_DeleteItemFromObject( cJSON *object, const char *string )
167,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Identify and fix the vulnerability in the code. Respond with the corrected function only. Remember, I want response with just the fixed function code only, No explanation.
Code: SPL_METHOD(FilesystemIterator, key) { 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_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(FilesystemIterator, key) { 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_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } }
167,035