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: void FileAPIMessageFilter::OnCreateSnapshotFile( int request_id, const GURL& blob_url, const GURL& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); FileSystemURL url(path); base::Callback<void(const FilePath&)> register_file_callback = base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob, this, blob_url, url.path()); FileSystemOperation* operation = GetNewOperation(url, request_id); if (!operation) return; operation->CreateSnapshotFile( url, base::Bind(&FileAPIMessageFilter::DidCreateSnapshot, this, request_id, register_file_callback)); } Commit Message: File permission fix: now we selectively grant read permission for Sandboxed files We also need to check the read permission and call GrantReadFile() for sandboxed files for CreateSnapshotFile(). BUG=162114 TEST=manual Review URL: https://codereview.chromium.org/11280231 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@170181 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void FileAPIMessageFilter::OnCreateSnapshotFile( int request_id, const GURL& blob_url, const GURL& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); FileSystemURL url(path); base::Callback<void(const FilePath&)> register_file_callback = base::Bind(&FileAPIMessageFilter::RegisterFileAsBlob, this, blob_url, url); // Make sure if this file can be read by the renderer as this is // called when the renderer is about to create a new File object // (for reading the file). base::PlatformFileError error; if (!HasPermissionsForFile(url, kReadFilePermissions, &error)) { Send(new FileSystemMsg_DidFail(request_id, error)); return; } FileSystemOperation* operation = GetNewOperation(url, request_id); if (!operation) return; operation->CreateSnapshotFile( url, base::Bind(&FileAPIMessageFilter::DidCreateSnapshot, this, request_id, register_file_callback)); }
171,586
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 OomInterventionTabHelper::StartDetectionInRenderer() { auto* config = OomInterventionConfig::GetInstance(); bool renderer_pause_enabled = config->is_renderer_pause_enabled(); bool navigate_ads_enabled = config->is_navigate_ads_enabled(); if ((renderer_pause_enabled || navigate_ads_enabled) && decider_) { DCHECK(!web_contents()->GetBrowserContext()->IsOffTheRecord()); const std::string& host = web_contents()->GetVisibleURL().host(); if (!decider_->CanTriggerIntervention(host)) { renderer_pause_enabled = false; navigate_ads_enabled = false; } } content::RenderFrameHost* main_frame = web_contents()->GetMainFrame(); DCHECK(main_frame); content::RenderProcessHost* render_process_host = main_frame->GetProcess(); DCHECK(render_process_host); content::BindInterface(render_process_host, mojo::MakeRequest(&intervention_)); DCHECK(!binding_.is_bound()); blink::mojom::OomInterventionHostPtr host; binding_.Bind(mojo::MakeRequest(&host)); blink::mojom::DetectionArgsPtr detection_args = config->GetRendererOomDetectionArgs(); intervention_->StartDetection(std::move(host), std::move(detection_args), renderer_pause_enabled, navigate_ads_enabled); } Commit Message: OomIntervention opt-out should work properly with 'show original' OomIntervention should not be re-triggered on the same page if the user declines the intervention once. This CL fixes the bug. Bug: 889131, 887119 Change-Id: Idb9eebb2bb9f79756b63f0e010fe018ba5c490e8 Reviewed-on: https://chromium-review.googlesource.com/1245019 Commit-Queue: Yuzu Saijo <yuzus@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Cr-Commit-Position: refs/heads/master@{#594574} CWE ID: CWE-119
void OomInterventionTabHelper::StartDetectionInRenderer() { auto* config = OomInterventionConfig::GetInstance(); bool renderer_pause_enabled = config->is_renderer_pause_enabled(); bool navigate_ads_enabled = config->is_navigate_ads_enabled(); if ((renderer_pause_enabled || navigate_ads_enabled) && decider_) { DCHECK(!web_contents()->GetBrowserContext()->IsOffTheRecord()); const std::string& host = web_contents()->GetVisibleURL().host(); if (!decider_->CanTriggerIntervention(host)) { renderer_pause_enabled = false; navigate_ads_enabled = false; } } if (!renderer_pause_enabled && !navigate_ads_enabled) return; content::RenderFrameHost* main_frame = web_contents()->GetMainFrame(); DCHECK(main_frame); content::RenderProcessHost* render_process_host = main_frame->GetProcess(); DCHECK(render_process_host); content::BindInterface(render_process_host, mojo::MakeRequest(&intervention_)); DCHECK(!binding_.is_bound()); blink::mojom::OomInterventionHostPtr host; binding_.Bind(mojo::MakeRequest(&host)); blink::mojom::DetectionArgsPtr detection_args = config->GetRendererOomDetectionArgs(); intervention_->StartDetection(std::move(host), std::move(detection_args), renderer_pause_enabled, navigate_ads_enabled); }
172,114
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: my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error) { *ret = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, unset_and_free_gvalue); g_hash_table_foreach (vals, hash_foreach_stringify, *ret); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_many_stringify (MyObject *obj, GHashTable /* char * -> GValue * */ *vals, GHashTable /* char * -> GValue * */ **ret, GError **error)
165,112
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n) { long v; int u; /* We can reliably get at most 31 bits since ISO/IEC 9899 only guarantees that a long can represent values up to 2^31-1. */ assert(n >= 0 && n < 32); /* Get the number of bits requested from the specified bit stream. */ v = 0; while (--n >= 0) { if ((u = jpc_bitstream_getbit(bitstream)) < 0) { return -1; } v = (v << 1) | u; } return v; } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID:
long jpc_bitstream_getbits(jpc_bitstream_t *bitstream, int n) { long v; int u; /* We can reliably get at most 31 bits since ISO/IEC 9899 only guarantees that a long can represent values up to 2^31-1. */ //assert(n >= 0 && n < 32); if (n < 0 || n >= 32) { return -1; } /* Get the number of bits requested from the specified bit stream. */ v = 0; while (--n >= 0) { if ((u = jpc_bitstream_getbit(bitstream)) < 0) { return -1; } v = (v << 1) | u; } return v; }
168,732
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 ExtensionTtsController::FinishCurrentUtterance() { if (current_utterance_) { current_utterance_->FinishAndDestroy(); current_utterance_ = NULL; } } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void ExtensionTtsController::FinishCurrentUtterance() { bool can_enqueue = false; if (options->HasKey(constants::kEnqueueKey)) { EXTENSION_FUNCTION_VALIDATE( options->GetBoolean(constants::kEnqueueKey, &can_enqueue)); }
170,378
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: TestResultCallback() : callback_(base::Bind(&TestResultCallback::SetResult, base::Unretained(this))) {} Commit Message: Update helper classes in usb_device_handle_unittest for OnceCallback Helper classes in usb_device_handle_unittest.cc don't fit to OnceCallback migration, as they are copied and passed to others. This CL updates them to pass new callbacks for each use to avoid the copy of callbacks. Bug: 714018 Change-Id: Ifb70901439ae92b6b049b84534283c39ebc40ee0 Reviewed-on: https://chromium-review.googlesource.com/527549 Reviewed-by: Ken Rockot <rockot@chromium.org> Commit-Queue: Taiju Tsuiki <tzik@chromium.org> Cr-Commit-Position: refs/heads/master@{#478549} CWE ID:
TestResultCallback()
171,977
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 WorkerFetchContext::DispatchWillSendRequest( unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirect_response, const FetchInitiatorInfo& initiator_info) { probe::willSendRequest(global_scope_, identifier, nullptr, request, redirect_response, initiator_info); } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
void WorkerFetchContext::DispatchWillSendRequest( unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirect_response, Resource::Type resource_type, const FetchInitiatorInfo& initiator_info) { probe::willSendRequest(global_scope_, identifier, nullptr, request, redirect_response, initiator_info, resource_type); }
172,476
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: MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t extent, packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; default: break; } extent=MagickMax(image->columns,image->rows); if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*extent*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*extent*quantum_info->depth+7)/8)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/126 CWE ID: CWE-125
MagickExport size_t GetQuantumExtent(const Image *image, const QuantumInfo *quantum_info,const QuantumType quantum_type) { size_t extent, packet_size; assert(quantum_info != (QuantumInfo *) NULL); assert(quantum_info->signature == MagickCoreSignature); packet_size=1; switch (quantum_type) { case GrayAlphaQuantum: packet_size=2; break; case IndexAlphaQuantum: packet_size=2; break; case RGBQuantum: packet_size=3; break; case BGRQuantum: packet_size=3; break; case RGBAQuantum: packet_size=4; break; case RGBOQuantum: packet_size=4; break; case BGRAQuantum: packet_size=4; break; case CMYKQuantum: packet_size=4; break; case CMYKAQuantum: packet_size=5; break; case CbYCrAQuantum: packet_size=4; break; case CbYCrQuantum: packet_size=3; break; case CbYCrYQuantum: packet_size=4; break; default: break; } extent=MagickMax(image->columns,image->rows); if (quantum_info->pack == MagickFalse) return((size_t) (packet_size*extent*((quantum_info->depth+7)/8))); return((size_t) ((packet_size*extent*quantum_info->depth+7)/8)); }
168,794
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 update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, int open_flags) { struct nfs_inode *nfsi = NFS_I(state->inode); struct nfs_delegation *deleg_cur; int ret = 0; open_flags &= (FMODE_READ|FMODE_WRITE); rcu_read_lock(); deleg_cur = rcu_dereference(nfsi->delegation); if (deleg_cur == NULL) goto no_delegation; spin_lock(&deleg_cur->lock); if (nfsi->delegation != deleg_cur || (deleg_cur->type & open_flags) != open_flags) goto no_delegation_unlock; if (delegation == NULL) delegation = &deleg_cur->stateid; else if (memcmp(deleg_cur->stateid.data, delegation->data, NFS4_STATEID_SIZE) != 0) goto no_delegation_unlock; nfs_mark_delegation_referenced(deleg_cur); __update_open_stateid(state, open_stateid, &deleg_cur->stateid, open_flags); ret = 1; no_delegation_unlock: spin_unlock(&deleg_cur->lock); no_delegation: rcu_read_unlock(); if (!ret && open_stateid != NULL) { __update_open_stateid(state, open_stateid, NULL, open_flags); ret = 1; } return ret; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static int update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, int open_flags) static int update_open_stateid(struct nfs4_state *state, nfs4_stateid *open_stateid, nfs4_stateid *delegation, fmode_t fmode) { struct nfs_inode *nfsi = NFS_I(state->inode); struct nfs_delegation *deleg_cur; int ret = 0; fmode &= (FMODE_READ|FMODE_WRITE); rcu_read_lock(); deleg_cur = rcu_dereference(nfsi->delegation); if (deleg_cur == NULL) goto no_delegation; spin_lock(&deleg_cur->lock); if (nfsi->delegation != deleg_cur || (deleg_cur->type & fmode) != fmode) goto no_delegation_unlock; if (delegation == NULL) delegation = &deleg_cur->stateid; else if (memcmp(deleg_cur->stateid.data, delegation->data, NFS4_STATEID_SIZE) != 0) goto no_delegation_unlock; nfs_mark_delegation_referenced(deleg_cur); __update_open_stateid(state, open_stateid, &deleg_cur->stateid, fmode); ret = 1; no_delegation_unlock: spin_unlock(&deleg_cur->lock); no_delegation: rcu_read_unlock(); if (!ret && open_stateid != NULL) { __update_open_stateid(state, open_stateid, NULL, fmode); ret = 1; } return ret; }
165,708
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: isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; } Commit Message: isofs: avoid info leak on export For type 1 the parent_offset member in struct isofs_fid gets copied uninitialized to userland. Fix this by initializing it to 0. Signed-off-by: Mathias Krause <minipli@googlemail.com> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-200
isofs_export_encode_fh(struct inode *inode, __u32 *fh32, int *max_len, struct inode *parent) { struct iso_inode_info * ei = ISOFS_I(inode); int len = *max_len; int type = 1; __u16 *fh16 = (__u16*)fh32; /* * WARNING: max_len is 5 for NFSv2. Because of this * limitation, we use the lower 16 bits of fh32[1] to hold the * offset of the inode and the upper 16 bits of fh32[1] to * hold the offset of the parent. */ if (parent && (len < 5)) { *max_len = 5; return 255; } else if (len < 3) { *max_len = 3; return 255; } len = 3; fh32[0] = ei->i_iget5_block; fh16[2] = (__u16)ei->i_iget5_offset; /* fh16 [sic] */ fh16[3] = 0; /* avoid leaking uninitialized data */ fh32[2] = inode->i_generation; if (parent) { struct iso_inode_info *eparent; eparent = ISOFS_I(parent); fh32[3] = eparent->i_iget5_block; fh16[3] = (__u16)eparent->i_iget5_offset; /* fh16 [sic] */ fh32[4] = parent->i_generation; len = 5; type = 2; } *max_len = len; return type; }
166,177
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 AXObject* AXObject::disabledAncestor() const { const AtomicString& disabled = getAttribute(aria_disabledAttr); if (equalIgnoringCase(disabled, "true")) return this; if (equalIgnoringCase(disabled, "false")) return 0; if (AXObject* parent = parentObject()) return parent->disabledAncestor(); return 0; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
const AXObject* AXObject::disabledAncestor() const { const AtomicString& disabled = getAttribute(aria_disabledAttr); if (equalIgnoringASCIICase(disabled, "true")) return this; if (equalIgnoringASCIICase(disabled, "false")) return 0; if (AXObject* parent = parentObject()) return parent->disabledAncestor(); return 0; }
171,925
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_tRNS_to_alpha_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* LIBPNG BUG: this always forces palette images to RGB. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); /* This effectively does an 'expand' only if there is some transparency to * convert to an alpha channel. */ if (that->have_tRNS) image_pixel_add_alpha(that, &display->this); /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */ else { if (that->bit_depth < 8) that->bit_depth =8; if (that->sample_depth < 8) that->sample_depth = 8; } 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_tRNS_to_alpha_mod(PNG_CONST image_transform *this, image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { #if PNG_LIBPNG_VER < 10700 /* LIBPNG BUG: this always forces palette images to RGB. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); #endif /* This effectively does an 'expand' only if there is some transparency to * convert to an alpha channel. */ if (that->have_tRNS) # if PNG_LIBPNG_VER >= 10700 if (that->colour_type != PNG_COLOR_TYPE_PALETTE && (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0) # endif image_pixel_add_alpha(that, &display->this, 0/*!for background*/); #if PNG_LIBPNG_VER < 10700 /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */ else { if (that->bit_depth < 8) that->bit_depth =8; if (that->sample_depth < 8) that->sample_depth = 8; } #endif this->next->mod(this->next, that, pp, display); }
173,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: int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { u16 offset = sizeof(struct ipv6hdr); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset <= packet_len) { struct ipv6_opt_hdr *exthdr; switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } if (offset + sizeof(struct ipv6_opt_hdr) > packet_len) return -EINVAL; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); offset += ipv6_optlen(exthdr); *nexthdr = &exthdr->nexthdr; } return -EINVAL; } Commit Message: ipv6: avoid overflow of offset in ip6_find_1stfragopt In some cases, offset can overflow and can cause an infinite loop in ip6_find_1stfragopt(). Make it unsigned int to prevent the overflow, and cap it at IPV6_MAXPLEN, since packets larger than that should be invalid. This problem has been here since before the beginning of git history. Signed-off-by: Sabrina Dubroca <sd@queasysnail.net> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-190
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { unsigned int offset = sizeof(struct ipv6hdr); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset <= packet_len) { struct ipv6_opt_hdr *exthdr; unsigned int len; switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } if (offset + sizeof(struct ipv6_opt_hdr) > packet_len) return -EINVAL; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); len = ipv6_optlen(exthdr); if (len + offset >= IPV6_MAXPLEN) return -EINVAL; offset += len; *nexthdr = &exthdr->nexthdr; } return -EINVAL; }
168,260
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_framing_cap_print(netdissect_options *ndo, const u_char *dat) { const uint32_t *ptr = (const uint32_t *)dat; if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_ASYNC_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_SYNC_MASK) { ND_PRINT((ndo, "S")); } } 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_framing_cap_print(netdissect_options *ndo, const u_char *dat) l2tp_framing_cap_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint32_t *ptr = (const uint32_t *)dat; if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_ASYNC_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_CAP_SYNC_MASK) { ND_PRINT((ndo, "S")); } }
167,894
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 BlobURLRequestJob::CountSize() { error_ = false; pending_get_file_info_count_ = 0; total_size_ = 0; item_length_list_.resize(blob_data_->items().size()); for (size_t i = 0; i < blob_data_->items().size(); ++i) { const BlobData::Item& item = blob_data_->items().at(i); if (IsFileType(item.type())) { ++pending_get_file_info_count_; GetFileStreamReader(i)->GetLength( base::Bind(&BlobURLRequestJob::DidGetFileItemLength, weak_factory_.GetWeakPtr(), i)); continue; } int64 item_length = static_cast<int64>(item.length()); item_length_list_[i] = item_length; total_size_ += item_length; } if (pending_get_file_info_count_ == 0) DidCountSize(net::OK); } Commit Message: Avoid integer overflows in BlobURLRequestJob. BUG=169685 Review URL: https://chromiumcodereview.appspot.com/12047012 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@179154 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void BlobURLRequestJob::CountSize() { error_ = false; pending_get_file_info_count_ = 0; total_size_ = 0; item_length_list_.resize(blob_data_->items().size()); for (size_t i = 0; i < blob_data_->items().size(); ++i) { const BlobData::Item& item = blob_data_->items().at(i); if (IsFileType(item.type())) { ++pending_get_file_info_count_; GetFileStreamReader(i)->GetLength( base::Bind(&BlobURLRequestJob::DidGetFileItemLength, weak_factory_.GetWeakPtr(), i)); continue; } if (!AddItemLength(i, item.length())) return; } if (pending_get_file_info_count_ == 0) DidCountSize(net::OK); }
171,398
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 Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "Usage: writeconfig <filename>\n" ); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); Com_Printf( "Writing %s.\n", filename ); Com_WriteConfigToFile( filename ); } Commit Message: All: Merge some file writing extension checks CWE ID: CWE-269
void Com_WriteConfig_f( void ) { char filename[MAX_QPATH]; if ( Cmd_Argc() != 2 ) { Com_Printf( "Usage: writeconfig <filename>\n" ); return; } if (!COM_CompareExtension(filename, ".cfg")) { Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n"); return; } Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) ); COM_DefaultExtension( filename, sizeof( filename ), ".cfg" ); Com_Printf( "Writing %s.\n", filename ); Com_WriteConfigToFile( filename ); }
170,080
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: hash_foreach (gpointer key, gpointer val, gpointer user_data) { const char *keystr = key; const char *valstr = val; guint *count = user_data; *count += (strlen (keystr) + strlen (valstr)); g_print ("%s -> %s\n", keystr, valstr); } Commit Message: CWE ID: CWE-264
hash_foreach (gpointer key, gpointer val, gpointer user_data)
165,084
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: DidStartNavigationToPendingEntry(const GURL& url, content::ReloadType reload_type) { devtools_bindings_->frontend_host_.reset( content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(devtools_bindings_)))); } Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds BUG=662859 Review-Url: https://codereview.chromium.org/2607833002 Cr-Commit-Position: refs/heads/master@{#440926} CWE ID: CWE-200
DidStartNavigationToPendingEntry(const GURL& url, content::ReloadType reload_type) { devtools_bindings_->UpdateFrontendHost(); }
172,453
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::InitAgentHost() { if (debuggee_.tab_id) { WebContents* web_contents = NULL; bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id, GetProfile(), include_incognito(), NULL, NULL, &web_contents, NULL); if (result && web_contents) { if (content::HasWebUIScheme(web_contents->GetURL())) { error_ = ErrorUtils::FormatErrorMessage( keys::kAttachToWebUIError, web_contents->GetURL().scheme()); return false; } agent_host_ = DevToolsAgentHost::GetOrCreateFor(web_contents); } } else if (debuggee_.extension_id) { ExtensionHost* extension_host = ExtensionSystem::Get(GetProfile()) ->process_manager() ->GetBackgroundHostForExtension(*debuggee_.extension_id); if (extension_host) { agent_host_ = DevToolsAgentHost::GetOrCreateFor( extension_host->render_view_host()); } } else if (debuggee_.target_id) { agent_host_ = DevToolsAgentHost::GetForId(*debuggee_.target_id); } else { error_ = keys::kInvalidTargetError; return false; } if (!agent_host_.get()) { FormatErrorMessage(keys::kNoTargetError); return false; } return true; } 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 DebuggerFunction::InitAgentHost() { const Extension* extension = GetExtension(); if (debuggee_.tab_id) { WebContents* web_contents = NULL; bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id, GetProfile(), include_incognito(), NULL, NULL, &web_contents, NULL); if (result && web_contents) { // TODO(rdevlin.cronin) This should definitely be GetLastCommittedURL(). GURL url = web_contents->GetVisibleURL(); if (PermissionsData::IsRestrictedUrl(url, url, extension, &error_)) return false; agent_host_ = DevToolsAgentHost::GetOrCreateFor(web_contents); } } else if (debuggee_.extension_id) { ExtensionHost* extension_host = ExtensionSystem::Get(GetProfile()) ->process_manager() ->GetBackgroundHostForExtension(*debuggee_.extension_id); if (extension_host) { if (PermissionsData::IsRestrictedUrl(extension_host->GetURL(), extension_host->GetURL(), extension, &error_)) { return false; } agent_host_ = DevToolsAgentHost::GetOrCreateFor( extension_host->render_view_host()); } } else if (debuggee_.target_id) { agent_host_ = DevToolsAgentHost::GetForId(*debuggee_.target_id); } else { error_ = keys::kInvalidTargetError; return false; } if (!agent_host_.get()) { FormatErrorMessage(keys::kNoTargetError); return false; } return true; }
171,653
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 re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } Commit Message: re_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c CWE ID: CWE-476
int re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; }
168,484
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: cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { assert((size_t)CDF_SHORT_SEC_SIZE(h) == len); (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + CDF_SHORT_SEC_POS(h, id), len); return len; } Commit Message: add more check found by cert's fuzzer. CWE ID: CWE-119
cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs, size_t len, const cdf_header_t *h, cdf_secid_t id) { size_t ss = CDF_SHORT_SEC_SIZE(h); size_t pos = CDF_SHORT_SEC_POS(h, id); assert(ss == len); if (sst->sst_len < (size_t)id) { DPRINTF(("bad sector id %d > %d\n", id, sst->sst_len)); return -1; } (void)memcpy(((char *)buf) + offs, ((const char *)sst->sst_tab) + pos, len); return len; }
169,884
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 OpenTwoTabs(const GURL& first_url, const GURL& second_url) { content::WindowedNotificationObserver load1( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open1(first_url, content::Referrer(), WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false); browser()->OpenURL(open1); load1.Wait(); content::WindowedNotificationObserver load2( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open2(second_url, content::Referrer(), WindowOpenDisposition::NEW_BACKGROUND_TAB, ui::PAGE_TRANSITION_TYPED, false); browser()->OpenURL(open2); load2.Wait(); ASSERT_EQ(2, tsm()->count()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void OpenTwoTabs(const GURL& first_url, const GURL& second_url) { content::WindowedNotificationObserver load1( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open1(first_url, content::Referrer(), WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false); content::WebContents* web_contents = browser()->OpenURL(open1); load1.Wait(); if (URLShouldBeStoredInLocalDatabase(first_url)) testing::ExpireLocalDBObservationWindows(web_contents); content::WindowedNotificationObserver load2( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); OpenURLParams open2(second_url, content::Referrer(), WindowOpenDisposition::NEW_BACKGROUND_TAB, ui::PAGE_TRANSITION_TYPED, false); web_contents = browser()->OpenURL(open2); load2.Wait(); // Expire all the observation windows to prevent the discarding and freezing // interventions to fail because of a lack of observations. if (URLShouldBeStoredInLocalDatabase(second_url)) testing::ExpireLocalDBObservationWindows(web_contents); ASSERT_EQ(2, tsm()->count()); }
172,228
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 asn1_write_LDAPString(struct asn1_data *data, const char *s) { asn1_write(data, s, strlen(s)); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_LDAPString(struct asn1_data *data, const char *s) { return asn1_write(data, s, strlen(s)); }
164,590
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: ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; }
167,793
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 MediaElementAudioSourceHandler::Process(size_t number_of_frames) { AudioBus* output_bus = Output(0).Bus(); MutexTryLocker try_locker(process_lock_); if (try_locker.Locked()) { if (!MediaElement() || !source_sample_rate_) { output_bus->Zero(); return; } if (source_number_of_channels_ != output_bus->NumberOfChannels()) { output_bus->Zero(); return; } AudioSourceProvider& provider = MediaElement()->GetAudioSourceProvider(); if (multi_channel_resampler_.get()) { DCHECK_NE(source_sample_rate_, Context()->sampleRate()); multi_channel_resampler_->Process(&provider, output_bus, number_of_frames); } else { DCHECK_EQ(source_sample_rate_, Context()->sampleRate()); provider.ProvideInput(output_bus, number_of_frames); } if (!PassesCORSAccessCheck()) { if (maybe_print_cors_message_) { maybe_print_cors_message_ = false; PostCrossThreadTask( *task_runner_, FROM_HERE, CrossThreadBind(&MediaElementAudioSourceHandler::PrintCORSMessage, WrapRefCounted(this), current_src_string_)); } output_bus->Zero(); } } else { output_bus->Zero(); } } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <rtoy@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Hongchan Choi <hongchan@chromium.org> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceHandler::Process(size_t number_of_frames) { AudioBus* output_bus = Output(0).Bus(); MutexTryLocker try_locker(process_lock_); if (try_locker.Locked()) { if (!MediaElement() || !source_sample_rate_) { output_bus->Zero(); return; } if (source_number_of_channels_ != output_bus->NumberOfChannels()) { output_bus->Zero(); return; } AudioSourceProvider& provider = MediaElement()->GetAudioSourceProvider(); if (multi_channel_resampler_.get()) { DCHECK_NE(source_sample_rate_, Context()->sampleRate()); multi_channel_resampler_->Process(&provider, output_bus, number_of_frames); } else { DCHECK_EQ(source_sample_rate_, Context()->sampleRate()); provider.ProvideInput(output_bus, number_of_frames); } if (is_origin_tainted_) { output_bus->Zero(); } } else { output_bus->Zero(); } }
173,149
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 V8ContextNativeHandler::RunWithNativesEnabledModuleSystem( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsFunction()); v8::Local<v8::Value> call_with_args[] = { context()->module_system()->NewInstance()}; ModuleSystem::NativesEnabledScope natives_enabled(context()->module_system()); context()->CallFunction(v8::Local<v8::Function>::Cast(args[0]), 1, call_with_args); } Commit Message: Add a test that getModuleSystem() doesn't work cross origin BUG=504011 R=kalman@chromium.org TBR=fukino@chromium.org Review URL: https://codereview.chromium.org/1241443004 Cr-Commit-Position: refs/heads/master@{#338663} CWE ID: CWE-79
void V8ContextNativeHandler::RunWithNativesEnabledModuleSystem( void V8ContextNativeHandler::RunWithNativesEnabled( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsFunction()); ModuleSystem::NativesEnabledScope natives_enabled(context()->module_system()); context()->CallFunction(v8::Local<v8::Function>::Cast(args[0])); }
171,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: static int getSingletonPos(const char* str) { int result =-1; int i=0; int len = 0; if( str && ((len=strlen(str))>0) ){ for( i=0; i<len ; i++){ if( isIDSeparator(*(str+i)) ){ if( i==1){ /* string is of the form x-avy or a-prv1 */ result =0; break; } else { /* delimiter found; check for singleton */ if( isIDSeparator(*(str+i+2)) ){ /* a singleton; so send the position of separator before singleton */ result = i+1; break; } } } }/* end of for */ } return result; } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static int getSingletonPos(const char* str) { int result =-1; int i=0; int len = 0; if( str && ((len=strlen(str))>0) ){ for( i=0; i<len ; i++){ if( isIDSeparator(*(str+i)) ){ if( i==1){ /* string is of the form x-avy or a-prv1 */ result =0; break; } else { /* delimiter found; check for singleton */ if( isIDSeparator(*(str+i+2)) ){ /* a singleton; so send the position of separator before singleton */ result = i+1; break; } } } }/* end of for */ } return result; }
167,202
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 readpng2_end_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; /* retrieve the pointer to our special-purpose struct */ mainprog_ptr = png_get_progressive_ptr(png_ptr); /* let the main program know that it should flush any buffered image * data to the display now and set a "done" flag or whatever, but note * that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do * NOT call readpng2_cleanup() either here or in the finish_display() * routine; wait until control returns to the main program via * readpng2_decode_data() */ (*mainprog_ptr->mainprog_finish_display)(); /* all done */ return; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static void readpng2_end_callback(png_structp png_ptr, png_infop info_ptr) { mainprog_info *mainprog_ptr; /* retrieve the pointer to our special-purpose struct */ mainprog_ptr = png_get_progressive_ptr(png_ptr); /* let the main program know that it should flush any buffered image * data to the display now and set a "done" flag or whatever, but note * that it SHOULD NOT DESTROY THE PNG STRUCTS YET--in other words, do * NOT call readpng2_cleanup() either here or in the finish_display() * routine; wait until control returns to the main program via * readpng2_decode_data() */ (*mainprog_ptr->mainprog_finish_display)(); /* all done */ (void)info_ptr; /* Unused */ return; }
173,568
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: virtual void SetUp() { video_ = new libvpx_test::WebMVideoSource(kVP9TestFile); ASSERT_TRUE(video_ != NULL); video_->Init(); video_->Begin(); vpx_codec_dec_cfg_t cfg = {0}; decoder_ = new libvpx_test::VP9Decoder(cfg, 0); ASSERT_TRUE(decoder_ != NULL); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { video_ = new libvpx_test::WebMVideoSource(kVP9TestFile); ASSERT_TRUE(video_ != NULL); video_->Init(); video_->Begin(); vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t(); decoder_ = new libvpx_test::VP9Decoder(cfg, 0); ASSERT_TRUE(decoder_ != NULL); }
174,546
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 ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) { if (fields->Len > 0) { const UINT64 offset = (UINT64)fields->BufferOffset + (UINT64)fields->Len; if (offset > Stream_Length(s)) return -1; fields->Buffer = (PBYTE) malloc(fields->Len); if (!fields->Buffer) return -1; Stream_SetPosition(s, fields->BufferOffset); Stream_Read(s, fields->Buffer, fields->Len); } return 1; }
169,277
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: XvQueryAdaptors( Display *dpy, Window window, unsigned int *p_nAdaptors, XvAdaptorInfo **p_pAdaptors) { XExtDisplayInfo *info = xv_find_display(dpy); xvQueryAdaptorsReq *req; xvQueryAdaptorsReply rep; size_t size; unsigned int ii, jj; char *name; XvAdaptorInfo *pas = NULL, *pa; XvFormat *pfs, *pf; char *buffer = NULL; char *buffer; char *string; xvAdaptorInfo *pa; xvFormat *pf; } u; Commit Message: CWE ID: CWE-125
XvQueryAdaptors( Display *dpy, Window window, unsigned int *p_nAdaptors, XvAdaptorInfo **p_pAdaptors) { XExtDisplayInfo *info = xv_find_display(dpy); xvQueryAdaptorsReq *req; xvQueryAdaptorsReply rep; size_t size; unsigned int ii, jj; char *name; char *end; XvAdaptorInfo *pas = NULL, *pa; XvFormat *pfs, *pf; char *buffer = NULL; char *buffer; char *string; xvAdaptorInfo *pa; xvFormat *pf; } u;
165,009
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: InputMethodDescriptors* ChromeOSGetSupportedInputMethodDescriptors() { InputMethodDescriptors* input_methods = new InputMethodDescriptors; for (size_t i = 0; i < arraysize(chromeos::kIBusEngines); ++i) { if (InputMethodIdIsWhitelisted(chromeos::kIBusEngines[i].name)) { input_methods->push_back(chromeos::CreateInputMethodDescriptor( chromeos::kIBusEngines[i].name, chromeos::kIBusEngines[i].longname, chromeos::kIBusEngines[i].layout, chromeos::kIBusEngines[i].language)); } } return input_methods; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
InputMethodDescriptors* ChromeOSGetSupportedInputMethodDescriptors() { virtual void RemoveObserver(Observer* observer) { }
170,523
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: scoped_refptr<VideoFrame> CloneVideoFrameWithLayout( const VideoFrame* const src_frame, const VideoFrameLayout& dst_layout) { LOG_ASSERT(src_frame->IsMappable()); LOG_ASSERT(src_frame->format() == dst_layout.format()); auto dst_frame = VideoFrame::CreateFrameWithLayout( dst_layout, src_frame->visible_rect(), src_frame->natural_size(), src_frame->timestamp(), false /* zero_initialize_memory*/); if (!dst_frame) { LOG(ERROR) << "Failed to create VideoFrame"; return nullptr; } const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format()); LOG_ASSERT(dst_layout.planes().size() == num_planes); LOG_ASSERT(src_frame->layout().planes().size() == num_planes); for (size_t i = 0; i < num_planes; ++i) { libyuv::CopyPlane( src_frame->data(i), src_frame->layout().planes()[i].stride, dst_frame->data(i), dst_frame->layout().planes()[i].stride, VideoFrame::Columns(i, dst_frame->format(), dst_frame->natural_size().width()), VideoFrame::Rows(i, dst_frame->format(), dst_frame->natural_size().height())); } return dst_frame; } Commit Message: media/gpu/test: ImageProcessorClient: Use bytes for width and height in libyuv::CopyPlane() |width| is in bytes in libyuv::CopyPlane(). We formerly pass width in pixels. This should matter when a pixel format is used whose pixel is composed of more than one bytes. Bug: None Test: image_processor_test Change-Id: I98e90be70c8d0128319172d4d19f3a8017b65d78 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1553129 Commit-Queue: Hirokazu Honda <hiroh@chromium.org> Reviewed-by: Alexandre Courbot <acourbot@chromium.org> Cr-Commit-Position: refs/heads/master@{#648117} CWE ID: CWE-20
scoped_refptr<VideoFrame> CloneVideoFrameWithLayout( const VideoFrame* const src_frame, const VideoFrameLayout& dst_layout) { LOG_ASSERT(src_frame->IsMappable()); LOG_ASSERT(src_frame->format() == dst_layout.format()); auto dst_frame = VideoFrame::CreateFrameWithLayout( dst_layout, src_frame->visible_rect(), src_frame->natural_size(), src_frame->timestamp(), false /* zero_initialize_memory*/); if (!dst_frame) { LOG(ERROR) << "Failed to create VideoFrame"; return nullptr; } const size_t num_planes = VideoFrame::NumPlanes(dst_layout.format()); LOG_ASSERT(dst_layout.planes().size() == num_planes); LOG_ASSERT(src_frame->layout().planes().size() == num_planes); for (size_t i = 0; i < num_planes; ++i) { // |width| in libyuv::CopyPlane() is in bytes, not pixels. gfx::Size plane_size = VideoFrame::PlaneSize(dst_frame->format(), i, dst_frame->natural_size()); libyuv::CopyPlane( src_frame->data(i), src_frame->layout().planes()[i].stride, dst_frame->data(i), dst_frame->layout().planes()[i].stride, plane_size.width(), plane_size.height()); } return dst_frame; }
172,397
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: my_object_error_quark (void) { static GQuark quark = 0; if (!quark) quark = g_quark_from_static_string ("my_object_error"); return quark; } Commit Message: CWE ID: CWE-264
my_object_error_quark (void)
165,098
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: on_unregister_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gpointer user_data) { struct tcmur_handler *handler = find_handler_by_subtype(subtype); struct dbus_info *info = handler->opaque; if (!handler) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", FALSE, "unknown subtype")); return TRUE; } dbus_unexport_handler(handler); tcmur_unregister_handler(handler); g_bus_unwatch_name(info->watcher_id); g_free(info); g_free(handler); g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", TRUE, "succeeded")); return TRUE; } Commit Message: fixed local DoS when UnregisterHandler was called for a not existing handler Any user with DBUS access could cause a SEGFAULT in tcmu-runner by running something like this: dbus-send --system --print-reply --dest=org.kernel.TCMUService1 /org/kernel/TCMUService1/HandlerManager1 org.kernel.TCMUService1.HandlerManager1.UnregisterHandler string:123 CWE ID: CWE-20
on_unregister_handler(TCMUService1HandlerManager1 *interface, GDBusMethodInvocation *invocation, gchar *subtype, gpointer user_data) { struct tcmur_handler *handler = find_handler_by_subtype(subtype); struct dbus_info *info = handler ? handler->opaque : NULL; if (!handler) { g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", FALSE, "unknown subtype")); return TRUE; } dbus_unexport_handler(handler); tcmur_unregister_handler(handler); g_bus_unwatch_name(info->watcher_id); g_free(info); g_free(handler); g_dbus_method_invocation_return_value(invocation, g_variant_new("(bs)", TRUE, "succeeded")); return TRUE; }
167,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: nfs3svc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readargs *args) { unsigned int len; int v; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); len = min(args->count, max_blocksize); /* set up the kvec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return xdr_argsize_check(rqstp, p); } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
nfs3svc_decode_readargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readargs *args) { unsigned int len; int v; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->offset); args->count = ntohl(*p++); if (!xdr_argsize_check(rqstp, p)) return 0; len = min(args->count, max_blocksize); /* set up the kvec */ v=0; while (len > 0) { struct page *p = *(rqstp->rq_next_page++); rqstp->rq_vec[v].iov_base = page_address(p); rqstp->rq_vec[v].iov_len = min_t(unsigned int, len, PAGE_SIZE); len -= rqstp->rq_vec[v].iov_len; v++; } args->vlen = v; return 1; }
168,140
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 bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; } Commit Message: Check if auth_user is set. Fixes a crash if password packet appears before startup packet (#42). CWE ID: CWE-476
static bool check_client_passwd(PgSocket *client, const char *passwd) { char md5[MD5_PASSWD_LEN + 1]; const char *correct; PgUser *user = client->auth_user; /* auth_user may be missing */ if (!user) { slog_error(client, "Password packet before auth packet?"); return false; } /* disallow empty passwords */ if (!*passwd || !*user->passwd) return false; switch (cf_auth_type) { case AUTH_PLAIN: return strcmp(user->passwd, passwd) == 0; case AUTH_CRYPT: correct = crypt(user->passwd, (char *)client->tmp_login_salt); return correct && strcmp(correct, passwd) == 0; case AUTH_MD5: if (strlen(passwd) != MD5_PASSWD_LEN) return false; if (!isMD5(user->passwd)) pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd); pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5); return strcmp(md5, passwd) == 0; } return false; }
170,132
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 Block::Frame::Read(IMkvReader* pReader, unsigned char* buf) const { assert(pReader); assert(buf); const long status = pReader->Read(pos, len, buf); return status; } 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 Block::Frame::Read(IMkvReader* pReader, unsigned char* buf) const
174,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: static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_qcd_t *qcd = &ms->parms.qcd; int i; fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n", (int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes); for (i = 0; i < qcd->compparms.numstepsizes; ++i) { fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n", i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]), i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i])); } return 0; } Commit Message: Changed the JPC bitstream code to more gracefully handle a request for a larger sized integer than what can be handled (i.e., return with an error instead of failing an assert). CWE ID:
static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out) { jpc_qcd_t *qcd = &ms->parms.qcd; int i; fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n", (int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes); for (i = 0; i < qcd->compparms.numstepsizes; ++i) { fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n", i, JAS_CAST(unsigned, JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i])), i, JAS_CAST(unsigned, JPC_QCX_GETMANT(qcd->compparms.stepsizes[i]))); } return 0; }
168,734
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: ExtensionTtsController::ExtensionTtsController() : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)), current_utterance_(NULL), platform_impl_(NULL) { } Commit Message: Extend TTS extension API to support richer events returned from the engine to the client. Previously we just had a completed event; this adds start, word boundary, sentence boundary, and marker boundary. In addition, interrupted and canceled, which were previously errors, now become events. Mac and Windows implementations extended to support as many of these events as possible. BUG=67713 BUG=70198 BUG=75106 BUG=83404 TEST=Updates all TTS API tests to be event-based, and adds new tests. Review URL: http://codereview.chromium.org/6792014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
ExtensionTtsController::ExtensionTtsController()
170,376
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_bearer_type_print(netdissect_options *ndo, const u_char *dat) { const uint32_t *ptr = (const uint32_t *)dat; if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) { ND_PRINT((ndo, "D")); } } 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_bearer_type_print(netdissect_options *ndo, const u_char *dat) l2tp_bearer_type_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint32_t *ptr = (const uint32_t *)dat; if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_ANALOG_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_BEARER_TYPE_DIGITAL_MASK) { ND_PRINT((ndo, "D")); } }
167,892
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: dns_resolver_match(const struct key *key, const struct key_match_data *match_data) { int slen, dlen, ret = 0; const char *src = key->description, *dsp = match_data->raw_data; kenter("%s,%s", src, dsp); if (!src || !dsp) goto no_match; if (strcasecmp(src, dsp) == 0) goto matched; slen = strlen(src); dlen = strlen(dsp); if (slen <= 0 || dlen <= 0) goto no_match; if (src[slen - 1] == '.') slen--; if (dsp[dlen - 1] == '.') dlen--; if (slen != dlen || strncasecmp(src, dsp, slen) != 0) goto no_match; matched: ret = 1; no_match: kleave(" = %d", ret); return ret; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@redhat.com> CWE ID: CWE-476
dns_resolver_match(const struct key *key, static int dns_resolver_cmp(const struct key *key, const struct key_match_data *match_data) { int slen, dlen, ret = 0; const char *src = key->description, *dsp = match_data->raw_data; kenter("%s,%s", src, dsp); if (!src || !dsp) goto no_match; if (strcasecmp(src, dsp) == 0) goto matched; slen = strlen(src); dlen = strlen(dsp); if (slen <= 0 || dlen <= 0) goto no_match; if (src[slen - 1] == '.') slen--; if (dsp[dlen - 1] == '.') dlen--; if (slen != dlen || strncasecmp(src, dsp, slen) != 0) goto no_match; matched: ret = 1; no_match: kleave(" = %d", ret); return ret; }
168,438
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_CreateFalse( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_False; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
cJSON *cJSON_CreateFalse( void )
167,271
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 Track::GetNumber() const { return m_info.number; } 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 Track::GetNumber() const
174,349
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: MagickExport int LocaleLowercase(const int c) { if (c < 0) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); } Commit Message: ... CWE ID: CWE-125
MagickExport int LocaleLowercase(const int c) { if (c == EOF) return(c); #if defined(MAGICKCORE_LOCALE_SUPPORT) if (c_locale != (locale_t) NULL) return(tolower_l((int) ((unsigned char) c),c_locale)); #endif return(tolower((int) ((unsigned char) c))); }
170,235
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 DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, true)); background_lifecycle_unit->Discard(reason); testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void DiscardAndActivateTest(DiscardReason reason) { LifecycleUnit* background_lifecycle_unit = nullptr; LifecycleUnit* foreground_lifecycle_unit = nullptr; CreateTwoTabs(true /* focus_tab_strip */, &background_lifecycle_unit, &foreground_lifecycle_unit); content::WebContents* initial_web_contents = tab_strip_model_->GetWebContentsAt(0); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, true)); background_lifecycle_unit->Discard(reason); ::testing::Mock::VerifyAndClear(&tab_observer_); TransitionFromPendingDiscardToDiscardedIfNeeded(reason, background_lifecycle_unit); EXPECT_NE(initial_web_contents, tab_strip_model_->GetWebContentsAt(0)); EXPECT_FALSE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); EXPECT_CALL(tab_observer_, OnDiscardedStateChange(::testing::_, false)); tab_strip_model_->ActivateTabAt(0, true); ::testing::Mock::VerifyAndClear(&tab_observer_); EXPECT_EQ(LifecycleUnitState::ACTIVE, background_lifecycle_unit->GetState()); EXPECT_TRUE(tab_strip_model_->GetWebContentsAt(0) ->GetController() .GetPendingEntry()); }
172,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 DaemonProcess::OnChannelConnected() { DCHECK(caller_task_runner()->BelongsToCurrentThread()); DeleteAllDesktopSessions(); next_terminal_id_ = 0; SendToNetwork( new ChromotingDaemonNetworkMsg_Configuration(serialized_config_)); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void DaemonProcess::OnChannelConnected() { void DaemonProcess::OnChannelConnected(int32 peer_pid) { DCHECK(caller_task_runner()->BelongsToCurrentThread()); DeleteAllDesktopSessions(); next_terminal_id_ = 0; SendToNetwork( new ChromotingDaemonNetworkMsg_Configuration(serialized_config_)); }
171,540
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_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; size_t fname_len; int ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|b", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1) == SUCCESS); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, isValidPharFilename) { char *fname; const char *ext_str; size_t fname_len; int ext_len, is_executable; zend_bool executable = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|b", &fname, &fname_len, &executable) == FAILURE) { return; } is_executable = executable; RETVAL_BOOL(phar_detect_phar_fname_ext(fname, fname_len, &ext_str, &ext_len, is_executable, 2, 1) == SUCCESS); }
165,059
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: SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mTimeToSampleCount(0), mTimeToSample(), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); } Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug 28076789. Detail: Before the original fix (Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the code allowed a time-to-sample table size to be 0. The change made in that fix disallowed such situation, which in fact should be allowed. This current patch allows it again while maintaining the security of the previous fix. Bug: 28288202 Bug: 28076789 Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295 CWE ID: CWE-20
SampleTable::SampleTable(const sp<DataSource> &source) : mDataSource(source), mChunkOffsetOffset(-1), mChunkOffsetType(0), mNumChunkOffsets(0), mSampleToChunkOffset(-1), mNumSampleToChunkOffsets(0), mSampleSizeOffset(-1), mSampleSizeFieldSize(0), mDefaultSampleSize(0), mNumSampleSizes(0), mHasTimeToSample(false), mTimeToSampleCount(0), mTimeToSample(), mSampleTimeEntries(NULL), mCompositionTimeDeltaEntries(NULL), mNumCompositionTimeDeltaEntries(0), mCompositionDeltaLookup(new CompositionDeltaLookup), mSyncSampleOffset(-1), mNumSyncSamples(0), mSyncSamples(NULL), mLastSyncSampleIndex(0), mSampleToChunkEntries(NULL) { mSampleIterator = new SampleIterator(this); }
173,771
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 copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb) { struct xfrm_algo *algo; struct nlattr *nla; nla = nla_reserve(skb, XFRMA_ALG_AUTH, sizeof(*algo) + (auth->alg_key_len + 7) / 8); if (!nla) return -EMSGSIZE; algo = nla_data(nla); strcpy(algo->alg_name, auth->alg_name); memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8); algo->alg_key_len = auth->alg_key_len; return 0; } Commit Message: xfrm_user: fix info leak in copy_to_user_auth() copy_to_user_auth() fails to initialize the remainder of alg_name and therefore discloses up to 54 bytes of heap memory via netlink to userland. Use strncpy() instead of strcpy() to fill the trailing bytes of alg_name with null bytes. Signed-off-by: Mathias Krause <minipli@googlemail.com> Acked-by: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb) { struct xfrm_algo *algo; struct nlattr *nla; nla = nla_reserve(skb, XFRMA_ALG_AUTH, sizeof(*algo) + (auth->alg_key_len + 7) / 8); if (!nla) return -EMSGSIZE; algo = nla_data(nla); strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name)); memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8); algo->alg_key_len = auth->alg_key_len; return 0; }
166,188
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: SProcXIBarrierReleasePointer(ClientPtr client) { xXIBarrierReleasePointerInfo *info; REQUEST(xXIBarrierReleasePointerReq); int i; swaps(&stuff->length); REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq); swapl(&stuff->num_barriers); REQUEST_FIXED_SIZE(xXIBarrierReleasePointerReq, stuff->num_barriers * sizeof(xXIBarrierReleasePointerInfo)); info = (xXIBarrierReleasePointerInfo*) &stuff[1]; swapl(&info->barrier); swapl(&info->eventid); } Commit Message: CWE ID: CWE-190
SProcXIBarrierReleasePointer(ClientPtr client) { xXIBarrierReleasePointerInfo *info; REQUEST(xXIBarrierReleasePointerReq); int i; swaps(&stuff->length); REQUEST_AT_LEAST_SIZE(xXIBarrierReleasePointerReq); swapl(&stuff->num_barriers); if (stuff->num_barriers > UINT32_MAX / sizeof(xXIBarrierReleasePointerInfo)) return BadLength; REQUEST_FIXED_SIZE(xXIBarrierReleasePointerReq, stuff->num_barriers * sizeof(xXIBarrierReleasePointerInfo)); info = (xXIBarrierReleasePointerInfo*) &stuff[1]; swapl(&info->barrier); swapl(&info->eventid); }
165,445
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 build_l4proto_sctp(const struct nf_conntrack *ct, struct nethdr *n) { ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); if (!nfct_attr_is_set(ct, ATTR_SCTP_STATE)) return; ct_build_u8(ct, ATTR_SCTP_STATE, n, NTA_SCTP_STATE); ct_build_u32(ct, ATTR_SCTP_VTAG_ORIG, n, NTA_SCTP_VTAG_ORIG); ct_build_u32(ct, ATTR_SCTP_VTAG_REPL, n, NTA_SCTP_VTAG_REPL); } Commit Message: CWE ID: CWE-17
static void build_l4proto_sctp(const struct nf_conntrack *ct, struct nethdr *n) { /* SCTP is optional, make sure nf_conntrack_sctp is loaded */ if (!nfct_attr_is_set(ct, ATTR_SCTP_STATE)) return; ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT, sizeof(struct nfct_attr_grp_port)); ct_build_u8(ct, ATTR_SCTP_STATE, n, NTA_SCTP_STATE); ct_build_u32(ct, ATTR_SCTP_VTAG_ORIG, n, NTA_SCTP_VTAG_ORIG); ct_build_u32(ct, ATTR_SCTP_VTAG_REPL, n, NTA_SCTP_VTAG_REPL); }
164,631
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 key_notify_policy_flush(const struct km_event *c) { struct sk_buff *skb_out; struct sadb_msg *hdr; skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb_out) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg)); hdr->sadb_msg_type = SADB_X_SPDFLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; } Commit Message: af_key: initialize satype in key_notify_policy_flush() This field was left uninitialized. Some user daemons perform check against this field. Signed-off-by: Nicolas Dichtel <nicolas.dichtel@6wind.com> Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com> CWE ID: CWE-119
static int key_notify_policy_flush(const struct km_event *c) { struct sk_buff *skb_out; struct sadb_msg *hdr; skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC); if (!skb_out) return -ENOBUFS; hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg)); hdr->sadb_msg_type = SADB_X_SPDFLUSH; hdr->sadb_msg_seq = c->seq; hdr->sadb_msg_pid = c->portid; hdr->sadb_msg_version = PF_KEY_V2; hdr->sadb_msg_errno = (uint8_t) 0; hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); return 0; }
166,073
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 ManifestUmaUtil::FetchFailed(FetchFailureReason reason) { ManifestFetchResultType fetch_result_type = MANIFEST_FETCH_RESULT_TYPE_COUNT; switch (reason) { case FETCH_EMPTY_URL: fetch_result_type = MANIFEST_FETCH_ERROR_EMPTY_URL; break; case FETCH_UNSPECIFIED_REASON: fetch_result_type = MANIFEST_FETCH_ERROR_UNSPECIFIED; break; } DCHECK_NE(fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); UMA_HISTOGRAM_ENUMERATION(kUMANameFetchResult, fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <dominickn@chromium.org> Reviewed-by: Mounir Lamouri <mlamouri@chromium.org> Reviewed-by: Mike West <mkwst@chromium.org> Cr-Commit-Position: refs/heads/master@{#531121} CWE ID:
void ManifestUmaUtil::FetchFailed(FetchFailureReason reason) { ManifestFetchResultType fetch_result_type = MANIFEST_FETCH_RESULT_TYPE_COUNT; switch (reason) { case FETCH_EMPTY_URL: fetch_result_type = MANIFEST_FETCH_ERROR_EMPTY_URL; break; case FETCH_FROM_UNIQUE_ORIGIN: fetch_result_type = MANIFEST_FETCH_ERROR_FROM_UNIQUE_ORIGIN; break; case FETCH_UNSPECIFIED_REASON: fetch_result_type = MANIFEST_FETCH_ERROR_UNSPECIFIED; break; } DCHECK_NE(fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); UMA_HISTOGRAM_ENUMERATION(kUMANameFetchResult, fetch_result_type, MANIFEST_FETCH_RESULT_TYPE_COUNT); }
172,922
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: Block::~Block() { delete[] m_frames; } 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
Block::~Block()
174,455
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: exsltDateCreateDate (exsltDateType type) { exsltDateValPtr ret; ret = (exsltDateValPtr) xmlMalloc(sizeof(exsltDateVal)); if (ret == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltDateCreateDate: out of memory\n"); return (NULL); } memset (ret, 0, sizeof(exsltDateVal)); if (type != EXSLT_UNKNOWN) ret->type = type; return ret; } 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
exsltDateCreateDate (exsltDateType type) { exsltDateValPtr ret; ret = (exsltDateValPtr) xmlMalloc(sizeof(exsltDateVal)); if (ret == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltDateCreateDate: out of memory\n"); return (NULL); } memset (ret, 0, sizeof(exsltDateVal)); if (type != XS_DURATION) { ret->value.date.mon = 1; ret->value.date.day = 1; } if (type != EXSLT_UNKNOWN) ret->type = type; return ret; }
173,291
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: flatpak_proxy_client_finalize (GObject *object) { FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object); client->proxy->clients = g_list_remove (client->proxy->clients, client); g_clear_object (&client->proxy); g_hash_table_destroy (client->rewrite_reply); g_hash_table_destroy (client->get_owner_reply); g_hash_table_destroy (client->unique_id_policy); free_side (&client->client_side); free_side (&client->bus_side); G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object); } Commit Message: Fix vulnerability in dbus proxy During the authentication all client data is directly forwarded to the dbus daemon as is, until we detect the BEGIN command after which we start filtering the binary dbus protocol. Unfortunately the detection of the BEGIN command in the proxy did not exactly match the detection in the dbus daemon. A BEGIN followed by a space or tab was considered ok in the daemon but not by the proxy. This could be exploited to send arbitrary dbus messages to the host, which can be used to break out of the sandbox. This was noticed by Gabriel Campana of The Google Security Team. This fix makes the detection of the authentication phase end match the dbus code. In addition we duplicate the authentication line validation from dbus, which includes ensuring all data is ASCII, and limiting the size of a line to 16k. In fact, we add some extra stringent checks, disallowing ASCII control chars and requiring that auth lines start with a capital letter. CWE ID: CWE-436
flatpak_proxy_client_finalize (GObject *object) { FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object); client->proxy->clients = g_list_remove (client->proxy->clients, client); g_clear_object (&client->proxy); g_byte_array_free (client->auth_buffer, TRUE); g_hash_table_destroy (client->rewrite_reply); g_hash_table_destroy (client->get_owner_reply); g_hash_table_destroy (client->unique_id_policy); free_side (&client->client_side); free_side (&client->bus_side); G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object); }
169,341
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: AutocompleteLog::AutocompleteLog( const string16& text, bool just_deleted_text, AutocompleteInput::Type input_type, size_t selected_index, SessionID::id_type tab_id, metrics::OmniboxEventProto::PageClassification current_page_classification, base::TimeDelta elapsed_time_since_user_first_modified_omnibox, size_t inline_autocompleted_length, const AutocompleteResult& result) : text(text), just_deleted_text(just_deleted_text), input_type(input_type), selected_index(selected_index), tab_id(tab_id), current_page_classification(current_page_classification), elapsed_time_since_user_first_modified_omnibox( elapsed_time_since_user_first_modified_omnibox), inline_autocompleted_length(inline_autocompleted_length), result(result) { } Commit Message: Adds per-provider information to omnibox UMA logs. Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future. BUG= TEST= Review URL: https://chromiumcodereview.appspot.com/10380007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
AutocompleteLog::AutocompleteLog( const string16& text, bool just_deleted_text, AutocompleteInput::Type input_type, size_t selected_index, SessionID::id_type tab_id, metrics::OmniboxEventProto::PageClassification current_page_classification, base::TimeDelta elapsed_time_since_user_first_modified_omnibox, size_t inline_autocompleted_length, const AutocompleteResult& result) : text(text), just_deleted_text(just_deleted_text), input_type(input_type), selected_index(selected_index), tab_id(tab_id), current_page_classification(current_page_classification), elapsed_time_since_user_first_modified_omnibox( elapsed_time_since_user_first_modified_omnibox), inline_autocompleted_length(inline_autocompleted_length), result(result), providers_info() { }
170,757
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 Block::GetTimeCode(const Cluster* pCluster) const { if (pCluster == 0) return m_timecode; const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; //unscaled timecode units } 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 Block::GetTimeCode(const Cluster* pCluster) const const long long tc0 = pCluster->GetTimeCode(); assert(tc0 >= 0); const long long tc = tc0 + m_timecode; return tc; // unscaled timecode units }
174,366
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 AutofillPopupBaseView::AddExtraInitParams( views::Widget::InitParams* params) { params->opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params->shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
void AutofillPopupBaseView::AddExtraInitParams(
172,092
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult( const GURL& url, const std::string& file_name, const std::string& download_digest_sha256) { if (client_) { base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, url.spec()); event.SetStringKey(kKeyFileName, file_name); event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event)); } } Commit Message: Add reporting for DLP deep scanning For each triggered rule in the DLP response, we report the download as violating that rule. This also implements the UnsafeReportingEnabled enterprise policy, which controls whether or not we do any reporting. Bug: 980777 Change-Id: I48100cfb4dd5aa92ed80da1f34e64a6e393be2fa Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1772381 Commit-Queue: Daniel Rubery <drubery@chromium.org> Reviewed-by: Karan Bhatia <karandeepb@chromium.org> Reviewed-by: Roger Tawa <rogerta@chromium.org> Cr-Commit-Position: refs/heads/master@{#691371} CWE ID: CWE-416
void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult( const GURL& url, const std::string& file_name, const std::string& download_digest_sha256) { if (client_) { // Create a real-time event dictionary from the arguments and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, url.spec()); event.SetStringKey(kKeyFileName, file_name); event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event)); } }
172,412
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 start_auth_request(PgSocket *client, const char *username) { int res; PktBuf *buf; client->auth_user = client->db->auth_user; /* have to fetch user info from db */ client->pool = get_pool(client->db, client->db->auth_user); if (!find_server(client)) { client->wait_for_user_conn = true; return; } slog_noise(client, "Doing auth_conn query"); client->wait_for_user_conn = false; client->wait_for_user = true; if (!sbuf_pause(&client->sbuf)) { release_server(client->link); disconnect_client(client, true, "pause failed"); return; } client->link->ready = 0; res = 0; buf = pktbuf_dynamic(512); if (buf) { pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username); res = pktbuf_send_immediate(buf, client->link); pktbuf_free(buf); /* * Should do instead: * res = pktbuf_send_queued(buf, client->link); * but that needs better integration with SBuf. */ } if (!res) disconnect_server(client->link, false, "unable to send login query"); } Commit Message: Remove too early set of auth_user When query returns 0 rows (user not found), this user stays as login user... Should fix #69. CWE ID: CWE-287
static void start_auth_request(PgSocket *client, const char *username) { int res; PktBuf *buf; /* have to fetch user info from db */ client->pool = get_pool(client->db, client->db->auth_user); if (!find_server(client)) { client->wait_for_user_conn = true; return; } slog_noise(client, "Doing auth_conn query"); client->wait_for_user_conn = false; client->wait_for_user = true; if (!sbuf_pause(&client->sbuf)) { release_server(client->link); disconnect_client(client, true, "pause failed"); return; } client->link->ready = 0; res = 0; buf = pktbuf_dynamic(512); if (buf) { pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username); res = pktbuf_send_immediate(buf, client->link); pktbuf_free(buf); /* * Should do instead: * res = pktbuf_send_queued(buf, client->link); * but that needs better integration with SBuf. */ } if (!res) disconnect_server(client->link, false, "unable to send login query"); }
168,871
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 dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain == 0) { /* 2.0.34: EOF is incorrect. We use 0 for * errors and EOF, just like fileGetbuf, * which is a simple fread() wrapper. * TBB. Original bug report: Daniel Cowgill. */ return 0; /* NOT EOF */ } rlen = remain; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; } Commit Message: Avoid potentially dangerous signed to unsigned conversion We make sure to never pass a negative `rlen` as size to memcpy(). See also <https://bugs.php.net/bug.php?id=73280>. Patch provided by Emmanuel Law. CWE ID: CWE-119
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len) { int rlen, remain; dpIOCtxPtr dctx; dynamicPtr *dp; dctx = (dpIOCtxPtr) ctx; dp = dctx->dp; remain = dp->logicalSize - dp->pos; if(remain >= len) { rlen = len; } else { if(remain <= 0) { /* 2.0.34: EOF is incorrect. We use 0 for * errors and EOF, just like fileGetbuf, * which is a simple fread() wrapper. * TBB. Original bug report: Daniel Cowgill. */ return 0; /* NOT EOF */ } rlen = remain; } memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen); dp->pos += rlen; return rlen; }
168,769
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: size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); return 1000000 - count; // give it 1 megabyte of stack #else return 1000000; // no stack depth check on this platform #endif } Commit Message: Fix stack size detection on Linux (fix #1427) CWE ID: CWE-190
size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); const uint32_t max_stack = 1000000; // give it 1 megabyte of stack if (count>max_stack) return 0; return max_stack - count; #else return 1000000; // no stack depth check on this platform #endif }
169,218
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 LocalFileSystem::fileSystemNotAvailable( PassRefPtrWillBeRawPtr<ExecutionContext> context, PassRefPtr<CallbackWrapper> callbacks) { context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR)); } 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
void LocalFileSystem::fileSystemNotAvailable( PassRefPtrWillBeRawPtr<ExecutionContext> context, CallbackWrapper* callbacks) { context->postTask(createCrossThreadTask(&reportFailure, callbacks->release(), FileError::ABORT_ERR)); }
171,428
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 insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct *desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; desc = get_desc(sel); if (!desc) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc->type & BIT(3))) return -EINVAL; switch ((desc->l << 1) | desc->d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } } Commit Message: x86/insn-eval: Fix use-after-free access to LDT entry get_desc() computes a pointer into the LDT while holding a lock that protects the LDT from being freed, but then drops the lock and returns the (now potentially dangling) pointer to its caller. Fix it by giving the caller a copy of the LDT entry instead. Fixes: 670f928ba09b ("x86/insn-eval: Add utility function to get segment descriptor") Cc: stable@vger.kernel.org Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID: CWE-362
int insn_get_code_seg_params(struct pt_regs *regs) { struct desc_struct desc; short sel; if (v8086_mode(regs)) /* Address and operand size are both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); sel = get_segment_selector(regs, INAT_SEG_REG_CS); if (sel < 0) return sel; if (!get_desc(&desc, sel)) return -EINVAL; /* * The most significant byte of the Type field of the segment descriptor * determines whether a segment contains data or code. If this is a data * segment, return error. */ if (!(desc.type & BIT(3))) return -EINVAL; switch ((desc.l << 1) | desc.d) { case 0: /* * Legacy mode. CS.L=0, CS.D=0. Address and operand size are * both 16-bit. */ return INSN_CODE_SEG_PARAMS(2, 2); case 1: /* * Legacy mode. CS.L=0, CS.D=1. Address and operand size are * both 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 4); case 2: /* * IA-32e 64-bit mode. CS.L=1, CS.D=0. Address size is 64-bit; * operand size is 32-bit. */ return INSN_CODE_SEG_PARAMS(4, 8); case 3: /* Invalid setting. CS.L=1, CS.D=1 */ /* fall through */ default: return -EINVAL; } }
169,609
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: LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; unsigned int retval; size_t tmpretval; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); if(!str){ if(buff){ *buff = '\0'; } return 0; } tmpretval = strlen(str); if(tmpretval>=INT_MAX){ tmpretval = INT_MAX-1; } retval = (int)tmpretval; if(buff){ memcpy(buff,str,retval+1); buff[retval] = '\0'; } openmpt_free_string(str); return retval; } Commit Message: [Fix] libmodplug: C API: Limit the length of strings copied to the output buffer of ModPlug_InstrumentName() and ModPlug_SampleName() to 32 bytes (including terminating null) as is done by original libmodplug. This avoids potential buffer overflows in software relying on this limit instead of querying the required buffer size beforehand. libopenmpt can return strings longer than 32 bytes here beacuse the internal limit of 32 bytes applies to strings encoded in arbitrary character encodings but the API returns them converted to UTF-8, which can be longer. (reported by Antonio Morales Maldonado of Semmle Security Research Team) git-svn-id: https://source.openmpt.org/svn/openmpt/trunk/OpenMPT@12127 56274372-70c3-4bfc-bfc3-4c3a0b034d27 CWE ID: CWE-120
LIBOPENMPT_MODPLUG_API unsigned int ModPlug_InstrumentName(ModPlugFile* file, unsigned int qual, char* buff) { const char* str; char buf[32]; if(!file) return 0; str = openmpt_module_get_instrument_name(file->mod,qual-1); memset(buf,0,32); if(str){ strncpy(buf,str,31); openmpt_free_string(str); } if(buff){ strncpy(buff,buf,32); } return (unsigned int)strlen(buf); }
169,500
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 color_sycc_to_rgb(opj_image_t *img) { if(img->numcomps < 3) { img->color_space = OPJ_CLRSPC_GRAY; return; } if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 2) && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */ { sycc420_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* horizontal sub-sample only */ { sycc422_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 1) && (img->comps[2].dx == 1) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* no sub-sample */ { sycc444_to_rgb(img); } else { fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } img->color_space = OPJ_CLRSPC_SRGB; }/* color_sycc_to_rgb() */ Commit Message: Fix Out-Of-Bounds Read in sycc42x_to_rgb function (#745) 42x Images with an odd x0/y0 lead to subsampled component starting at the 2nd column/line. That is offset = comp->dx * comp->x0 - image->x0 = 1 Fix #726 CWE ID: CWE-125
void color_sycc_to_rgb(opj_image_t *img) { if(img->numcomps < 3) { img->color_space = OPJ_CLRSPC_GRAY; return; } if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 2) && (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */ { sycc420_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 2) && (img->comps[2].dx == 2) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* horizontal sub-sample only */ { sycc422_to_rgb(img); } else if((img->comps[0].dx == 1) && (img->comps[1].dx == 1) && (img->comps[2].dx == 1) && (img->comps[0].dy == 1) && (img->comps[1].dy == 1) && (img->comps[2].dy == 1))/* no sub-sample */ { sycc444_to_rgb(img); } else { fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__); return; } }/* color_sycc_to_rgb() */
168,838
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 RilSapSocket::sendResponse(MsgHeader* hdr) { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; pthread_mutex_lock(&write_lock); if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields, hdr)) && encoded_size <= INT32_MAX && commandFd != -1) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t buffer[buffer_size]; written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, MsgHeader_fields, hdr); if (success) { RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size, written_size); log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size); RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d", hdr->token, hdr->type, hdr->id,hdr->error ); if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) { RLOGE("Error %d while writing to fd", errno); } else { RLOGD("Write successful"); } } else { RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.", hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream)); } } else { RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d", hdr->type, encoded_size, commandFd, success); } pthread_mutex_unlock(&write_lock); } Commit Message: Replace variable-length arrays on stack with malloc. Bug: 30202619 Change-Id: Ib95e08a1c009d88a4b4fd8d8fdba0641c6129008 (cherry picked from commit 943905bb9f99e3caa856b42c531e2be752da8834) CWE ID: CWE-264
void RilSapSocket::sendResponse(MsgHeader* hdr) { size_t encoded_size = 0; uint32_t written_size; size_t buffer_size = 0; pb_ostream_t ostream; bool success = false; pthread_mutex_lock(&write_lock); if ((success = pb_get_encoded_size(&encoded_size, MsgHeader_fields, hdr)) && encoded_size <= INT32_MAX && commandFd != -1) { buffer_size = encoded_size + sizeof(uint32_t); uint8_t* buffer = (uint8_t*)malloc(buffer_size); if (!buffer) { RLOGE("sendResponse: OOM"); pthread_mutex_unlock(&write_lock); return; } written_size = htonl((uint32_t) encoded_size); ostream = pb_ostream_from_buffer(buffer, buffer_size); pb_write(&ostream, (uint8_t *)&written_size, sizeof(written_size)); success = pb_encode(&ostream, MsgHeader_fields, hdr); if (success) { RLOGD("Size: %d (0x%x) Size as written: 0x%x", encoded_size, encoded_size, written_size); log_hex("onRequestComplete", &buffer[sizeof(written_size)], encoded_size); RLOGI("[%d] < SAP RESPONSE type: %d. id: %d. error: %d", hdr->token, hdr->type, hdr->id,hdr->error ); if ( 0 != blockingWrite_helper(commandFd, buffer, buffer_size)) { RLOGE("Error %d while writing to fd", errno); } else { RLOGD("Write successful"); } } else { RLOGE("Error while encoding response of type %d id %d buffer_size: %d: %s.", hdr->type, hdr->id, buffer_size, PB_GET_ERROR(&ostream)); } free(buffer); } else { RLOGE("Not sending response type %d: encoded_size: %u. commandFd: %d. encoded size result: %d", hdr->type, encoded_size, commandFd, success); } pthread_mutex_unlock(&write_lock); }
173,389
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: DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, IncludePrivacySensitiveFields include_privacy_sensitive_fields) { NOTIMPLEMENTED(); return NULL; } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index) { NOTIMPLEMENTED(); return NULL; }
171,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: PHP_FUNCTION(pg_trace) { char *z_filename, *mode = "w"; int z_filename_len, mode_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; id = PGG(default_link); if (zend_parse_parameters(argc TSRMLS_CC, "s|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; } Commit Message: CWE ID: CWE-254
PHP_FUNCTION(pg_trace) { char *z_filename, *mode = "w"; int z_filename_len, mode_len; zval *pgsql_link = NULL; int id = -1, argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; id = PGG(default_link); if (zend_parse_parameters(argc TSRMLS_CC, "p|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { CHECK_DEFAULT_LINK(id); } if (pgsql_link == NULL && id == -1) { RETURN_FALSE; } ZEND_FETCH_RESOURCE2(pgsql, PGconn *, &pgsql_link, id, "PostgreSQL link", le_link, le_plink); stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; }
165,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: ConnectionInfoPopupAndroid::ConnectionInfoPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), InfoBarService::FromWebContents(web_contents), nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); } Commit Message: Fix UAF in Origin Info Bubble and permission settings UI. In addition to fixing the UAF, will this also fix the problem of the bubble showing over the previous tab (if the bubble is open when the tab it was opened for closes). BUG=490492 TBR=tedchoc Review URL: https://codereview.chromium.org/1317443002 Cr-Commit-Position: refs/heads/master@{#346023} CWE ID:
ConnectionInfoPopupAndroid::ConnectionInfoPopupAndroid( JNIEnv* env, jobject java_website_settings_pop, WebContents* web_contents) { content::NavigationEntry* nav_entry = web_contents->GetController().GetVisibleEntry(); if (nav_entry == NULL) return; popup_jobject_.Reset(env, java_website_settings_pop); presenter_.reset(new WebsiteSettings( this, Profile::FromBrowserContext(web_contents->GetBrowserContext()), TabSpecificContentSettings::FromWebContents(web_contents), web_contents, nav_entry->GetURL(), nav_entry->GetSSL(), content::CertStore::GetInstance())); }
171,777
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: ProcDbeGetVisualInfo(ClientPtr client) { REQUEST(xDbeGetVisualInfoReq); DbeScreenPrivPtr pDbeScreenPriv; xDbeGetVisualInfoReply rep; Drawable *drawables; DrawablePtr *pDrawables = NULL; register int i, j, rc; register int count; /* number of visual infos in reply */ register int length; /* length of reply */ ScreenPtr pScreen; XdbeScreenVisualInfo *pScrVisInfo; REQUEST_AT_LEAST_SIZE(xDbeGetVisualInfoReq); if (stuff->n > UINT32_MAX / sizeof(DrawablePtr)) return BadAlloc; return BadAlloc; } Commit Message: CWE ID: CWE-190
ProcDbeGetVisualInfo(ClientPtr client) { REQUEST(xDbeGetVisualInfoReq); DbeScreenPrivPtr pDbeScreenPriv; xDbeGetVisualInfoReply rep; Drawable *drawables; DrawablePtr *pDrawables = NULL; register int i, j, rc; register int count; /* number of visual infos in reply */ register int length; /* length of reply */ ScreenPtr pScreen; XdbeScreenVisualInfo *pScrVisInfo; REQUEST_AT_LEAST_SIZE(xDbeGetVisualInfoReq); if (stuff->n > UINT32_MAX / sizeof(CARD32)) return BadLength; REQUEST_FIXED_SIZE(xDbeGetVisualInfoReq, stuff->n * sizeof(CARD32)); if (stuff->n > UINT32_MAX / sizeof(DrawablePtr)) return BadAlloc; return BadAlloc; }
165,447
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: zsetstrokecolorspace(i_ctx_t * i_ctx_p) { int code; zsetstrokecolorspace(i_ctx_t * i_ctx_p) { int code; code = zswapcolors(i_ctx_p); if (code < 0) /* Now, the actual continuation routine */ push_op_estack(setstrokecolorspace_cont); code = zsetcolorspace(i_ctx_p); if (code >= 0) return o_push_estack; return code; } if (code >= 0) return o_push_estack; return code; } Commit Message: CWE ID: CWE-119
zsetstrokecolorspace(i_ctx_t * i_ctx_p) { int code; zsetstrokecolorspace(i_ctx_t * i_ctx_p) { int code; es_ptr iesp = esp; /* preserve exec stack in case of error */ code = zswapcolors(i_ctx_p); if (code < 0) /* Now, the actual continuation routine */ push_op_estack(setstrokecolorspace_cont); code = zsetcolorspace(i_ctx_p); if (code >= 0) return o_push_estack; return code; } if (code >= 0) return o_push_estack; /* Something went wrong, swap back to the non-stroking space and restore the exec stack */ esp = iesp; (void)zswapcolors(i_ctx_p); return code; }
164,700
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: virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, cpu_used_); } else if (video->frame() == 3) { vpx_active_map_t map = {0}; uint8_t active_map[9 * 13] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, }; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; ASSERT_EQ(map.cols, 13u); ASSERT_EQ(map.rows, 9u); map.active_map = active_map; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } else if (video->frame() == 15) { vpx_active_map_t map = {0}; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; map.active_map = NULL; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video, ::libvpx_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(VP8E_SET_CPUUSED, cpu_used_); } else if (video->frame() == 3) { vpx_active_map_t map = vpx_active_map_t(); uint8_t active_map[9 * 13] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, }; map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; ASSERT_EQ(map.cols, 13u); ASSERT_EQ(map.rows, 9u); map.active_map = active_map; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } else if (video->frame() == 15) { vpx_active_map_t map = vpx_active_map_t(); map.cols = (kWidth + 15) / 16; map.rows = (kHeight + 15) / 16; map.active_map = NULL; encoder->Control(VP8E_SET_ACTIVEMAP, &map); } }
174,501
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 PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; } Commit Message: CWE ID: CWE-200
static PHP_GINIT_FUNCTION(libxml) { libxml_globals->stream_context = NULL; libxml_globals->error_buffer.c = NULL; libxml_globals->error_list = NULL; libxml_globals->entity_loader_disabled = 0; }
164,744
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: key_ref_t keyring_search(key_ref_t keyring, struct key_type *type, const char *description) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; int ret; if (!ctx.match_data.cmp) return ERR_PTR(-ENOKEY); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) return ERR_PTR(ret); } key = keyring_search_aux(keyring, &ctx); if (type->match_free) type->match_free(&ctx.match_data); return key; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@redhat.com> CWE ID: CWE-476
key_ref_t keyring_search(key_ref_t keyring, struct key_type *type, const char *description) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = KEYRING_SEARCH_DO_STATE_CHECK, }; key_ref_t key; int ret; if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) return ERR_PTR(ret); } key = keyring_search_aux(keyring, &ctx); if (type->match_free) type->match_free(&ctx.match_data); return key; }
168,440
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: ReverbConvolverStage::ReverbConvolverStage(const float* impulseResponse, size_t, size_t reverbTotalLatency, size_t stageOffset, size_t stageLength, size_t fftSize, size_t renderPhase, size_t renderSliceSize, ReverbAccumulationBuffer* accumulationBuffer, bool directMode) : m_accumulationBuffer(accumulationBuffer) , m_accumulationReadIndex(0) , m_inputReadIndex(0) , m_directMode(directMode) { ASSERT(impulseResponse); ASSERT(accumulationBuffer); if (!m_directMode) { m_fftKernel = adoptPtr(new FFTFrame(fftSize)); m_fftKernel->doPaddedFFT(impulseResponse + stageOffset, stageLength); m_fftConvolver = adoptPtr(new FFTConvolver(fftSize)); } else { m_directKernel = adoptPtr(new AudioFloatArray(fftSize / 2)); m_directKernel->copyToRange(impulseResponse + stageOffset, 0, fftSize / 2); m_directConvolver = adoptPtr(new DirectConvolver(renderSliceSize)); } m_temporaryBuffer.allocate(renderSliceSize); size_t totalDelay = stageOffset + reverbTotalLatency; size_t halfSize = fftSize / 2; if (!m_directMode) { ASSERT(totalDelay >= halfSize); if (totalDelay >= halfSize) totalDelay -= halfSize; } int maxPreDelayLength = std::min(halfSize, totalDelay); m_preDelayLength = totalDelay > 0 ? renderPhase % maxPreDelayLength : 0; if (m_preDelayLength > totalDelay) m_preDelayLength = 0; m_postDelayLength = totalDelay - m_preDelayLength; m_preReadWriteIndex = 0; m_framesProcessed = 0; // total frames processed so far size_t delayBufferSize = m_preDelayLength < fftSize ? fftSize : m_preDelayLength; delayBufferSize = delayBufferSize < renderSliceSize ? renderSliceSize : delayBufferSize; m_preDelayBuffer.allocate(delayBufferSize); } Commit Message: Don't read past the end of the impulseResponse array BUG=281480 Review URL: https://chromiumcodereview.appspot.com/23689004 git-svn-id: svn://svn.chromium.org/blink/trunk@157007 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
ReverbConvolverStage::ReverbConvolverStage(const float* impulseResponse, size_t, size_t reverbTotalLatency, size_t stageOffset, size_t stageLength, size_t fftSize, size_t renderPhase, size_t renderSliceSize, ReverbAccumulationBuffer* accumulationBuffer, bool directMode) : m_accumulationBuffer(accumulationBuffer) , m_accumulationReadIndex(0) , m_inputReadIndex(0) , m_directMode(directMode) { ASSERT(impulseResponse); ASSERT(accumulationBuffer); if (!m_directMode) { m_fftKernel = adoptPtr(new FFTFrame(fftSize)); m_fftKernel->doPaddedFFT(impulseResponse + stageOffset, stageLength); m_fftConvolver = adoptPtr(new FFTConvolver(fftSize)); } else { ASSERT(!stageOffset); ASSERT(stageLength <= fftSize / 2); m_directKernel = adoptPtr(new AudioFloatArray(fftSize / 2)); m_directKernel->copyToRange(impulseResponse, 0, stageLength); m_directConvolver = adoptPtr(new DirectConvolver(renderSliceSize)); } m_temporaryBuffer.allocate(renderSliceSize); size_t totalDelay = stageOffset + reverbTotalLatency; size_t halfSize = fftSize / 2; if (!m_directMode) { ASSERT(totalDelay >= halfSize); if (totalDelay >= halfSize) totalDelay -= halfSize; } int maxPreDelayLength = std::min(halfSize, totalDelay); m_preDelayLength = totalDelay > 0 ? renderPhase % maxPreDelayLength : 0; if (m_preDelayLength > totalDelay) m_preDelayLength = 0; m_postDelayLength = totalDelay - m_preDelayLength; m_preReadWriteIndex = 0; m_framesProcessed = 0; // total frames processed so far size_t delayBufferSize = m_preDelayLength < fftSize ? fftSize : m_preDelayLength; delayBufferSize = delayBufferSize < renderSliceSize ? renderSliceSize : delayBufferSize; m_preDelayBuffer.allocate(delayBufferSize); }
171,191
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: ext4_xattr_create_cache(char *name) { return mb_cache_create(name, HASH_BUCKET_BITS); } Commit Message: ext4: convert to mbcache2 The conversion is generally straightforward. The only tricky part is that xattr block corresponding to found mbcache entry can get freed before we get buffer lock for that block. So we have to check whether the entry is still valid after getting buffer lock. Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-19
ext4_xattr_create_cache(char *name) struct mb2_cache * ext4_xattr_create_cache(void) { return mb2_cache_create(HASH_BUCKET_BITS); }
169,993
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 wait_for_fpga_config(void) { int ret = 0, done; /* approx 5 s */ u32 timeout = 500000; printf("PCIe FPGA config:"); do { done = qrio_get_gpio(GPIO_A, FPGA_DONE); if (timeout-- == 0) { printf(" FPGA_DONE timeout\n"); ret = -EFAULT; goto err_out; } udelay(10); } while (!done); printf(" done\n"); err_out: /* deactive CONF_SEL and give the CPU conf EEPROM access */ qrio_set_gpio(GPIO_A, CONF_SEL_L, 1); toggle_fpga_eeprom_bus(true); return ret; } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
static int wait_for_fpga_config(void) { int ret = 0, done; /* approx 5 s */ u32 timeout = 500000; printf("PCIe FPGA config:"); do { done = qrio_get_gpio(QRIO_GPIO_A, FPGA_DONE); if (timeout-- == 0) { printf(" FPGA_DONE timeout\n"); ret = -EFAULT; goto err_out; } udelay(10); } while (!done); printf(" done\n"); err_out: /* deactive CONF_SEL and give the CPU conf EEPROM access */ qrio_set_gpio(QRIO_GPIO_A, CONF_SEL_L, 1); toggle_fpga_eeprom_bus(true); return ret; }
169,636
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 DevToolsWindow::InspectedContentsClosing() { web_contents_->GetRenderViewHost()->ClosePage(); } Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception This patch fixes the crash which happenes under the following conditions: 1. DevTools window is in undocked state 2. DevTools renderer is unresponsive 3. User attempts to close inspected page BUG=322380 Review URL: https://codereview.chromium.org/84883002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void DevToolsWindow::InspectedContentsClosing() { intercepted_page_beforeunload_ = false; web_contents_->GetRenderViewHost()->ClosePage(); }
171,267
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 ChangeInputMethod(const char* name) { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "ChangeInputMethod: IBus connection is not alive"; return false; } if (!name) { return false; } if (!InputMethodIdIsWhitelisted(name)) { LOG(ERROR) << "Input method '" << name << "' is not supported"; return false; } RegisterProperties(NULL); ibus_bus_set_global_engine_async(ibus_, name, -1, // use the default ibus timeout NULL, // cancellable NULL, // callback NULL); // user_data return true; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
bool ChangeInputMethod(const char* name) { // IBusController override. virtual bool ChangeInputMethod(const std::string& name) { if (!IBusConnectionsAreAlive()) { LOG(ERROR) << "ChangeInputMethod: IBus connection is not alive"; return false; } if (name.empty()) { return false; } if (!InputMethodIdIsWhitelisted(name)) { LOG(ERROR) << "Input method '" << name << "' is not supported"; return false; } DoRegisterProperties(NULL); ibus_bus_set_global_engine_async(ibus_, name.c_str(), -1, // use the default ibus timeout NULL, // cancellable NULL, // callback NULL); // user_data return true; }
170,519
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: SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username) { int i; SRP_user_pwd *user; unsigned char digv[SHA_DIGEST_LENGTH]; unsigned char digs[SHA_DIGEST_LENGTH]; EVP_MD_CTX ctxt; if (vb == NULL) return NULL; for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) { user = sk_SRP_user_pwd_value(vb->users_pwd, i); if (strcmp(user->id, username) == 0) return user; } if ((vb->seed_key == NULL) || (vb->default_g == NULL) || (vb->default_N == NULL)) return NULL; if (!(len = t_fromb64(tmp, N))) goto err; N_bn = BN_bin2bn(tmp, len, NULL); if (!(len = t_fromb64(tmp, g))) goto err; g_bn = BN_bin2bn(tmp, len, NULL); defgNid = "*"; } else { SRP_gN *gN = SRP_get_gN_by_id(g, NULL); if (gN == NULL) goto err; N_bn = gN->N; g_bn = gN->g; defgNid = gN->id; } Commit Message: CWE ID: CWE-399
SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username) static SRP_user_pwd *find_user(SRP_VBASE *vb, char *username) { int i; SRP_user_pwd *user; if (vb == NULL) return NULL; for (i = 0; i < sk_SRP_user_pwd_num(vb->users_pwd); i++) { user = sk_SRP_user_pwd_value(vb->users_pwd, i); if (strcmp(user->id, username) == 0) return user; } return NULL; } /* * This method ignores the configured seed and fails for an unknown user. * Ownership of the returned pointer is not released to the caller. * In other words, caller must not free the result. */ SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username) { return find_user(vb, username); } /* * Ownership of the returned pointer is released to the caller. * In other words, caller must free the result once done. */ SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username) { SRP_user_pwd *user; unsigned char digv[SHA_DIGEST_LENGTH]; unsigned char digs[SHA_DIGEST_LENGTH]; EVP_MD_CTX ctxt; if (vb == NULL) return NULL; if ((user = find_user(vb, username)) != NULL) return srp_user_pwd_dup(user); if ((vb->seed_key == NULL) || (vb->default_g == NULL) || (vb->default_N == NULL)) return NULL; if (!(len = t_fromb64(tmp, N))) goto err; N_bn = BN_bin2bn(tmp, len, NULL); if (!(len = t_fromb64(tmp, g))) goto err; g_bn = BN_bin2bn(tmp, len, NULL); defgNid = "*"; } else { SRP_gN *gN = SRP_get_gN_by_id(g, NULL); if (gN == NULL) goto err; N_bn = gN->N; g_bn = gN->g; defgNid = gN->id; }
165,248
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 PrintingMessageFilter::OnCheckForCancel(const std::string& preview_ui_addr, int preview_request_id, bool* cancel) { PrintPreviewUI::GetCurrentPrintPreviewStatus(preview_ui_addr, preview_request_id, cancel); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintingMessageFilter::OnCheckForCancel(const std::string& preview_ui_addr, void PrintingMessageFilter::OnCheckForCancel(int32 preview_ui_id, int preview_request_id, bool* cancel) { PrintPreviewUI::GetCurrentPrintPreviewStatus(preview_ui_id, preview_request_id, cancel); }
170,826
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 basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS && !zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); efree(buf); smart_str_free(&auth); return 1; } return 0; } Commit Message: CWE ID:
int basic_authentication(zval* this_ptr, smart_str* soap_headers TSRMLS_DC) { zval **login, **password; zval **login, **password; if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_login", sizeof("_login"), (void **)&login) == SUCCESS && Z_TYPE_PP(login) == IS_STRING && !zend_hash_exists(Z_OBJPROP_P(this_ptr), "_digest", sizeof("_digest"))) { unsigned char* buf; int len; smart_str auth = {0}; smart_str_appendl(&auth, Z_STRVAL_PP(login), Z_STRLEN_PP(login)); smart_str_appendc(&auth, ':'); if (zend_hash_find(Z_OBJPROP_P(this_ptr), "_password", sizeof("_password"), (void **)&password) == SUCCESS && Z_TYPE_PP(password) == IS_STRING) { smart_str_appendl(&auth, Z_STRVAL_PP(password), Z_STRLEN_PP(password)); } smart_str_0(&auth); efree(buf); smart_str_free(&auth); return 1; } return 0; }
165,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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: StateBase* writeBlob(v8::Handle<v8::Value> value, StateBase* next) { Blob* blob = V8Blob::toNative(value.As<v8::Object>()); if (!blob) return 0; if (blob->hasBeenClosed()) return handleError(DataCloneError, "A Blob object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.add(blob->uuid(), blob->blobDataHandle()); if (appendBlobInfo(blob->uuid(), blob->type(), blob->size(), &blobIndex)) m_writer.writeBlobIndex(blobIndex); else m_writer.writeBlob(blob->uuid(), blob->type(), blob->size()); return 0; } Commit Message: Replace further questionable HashMap::add usages in bindings BUG=390928 R=dcarney@chromium.org Review URL: https://codereview.chromium.org/411273002 git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
StateBase* writeBlob(v8::Handle<v8::Value> value, StateBase* next) { Blob* blob = V8Blob::toNative(value.As<v8::Object>()); if (!blob) return 0; if (blob->hasBeenClosed()) return handleError(DataCloneError, "A Blob object has been closed, and could therefore not be cloned.", next); int blobIndex = -1; m_blobDataHandles.set(blob->uuid(), blob->blobDataHandle()); if (appendBlobInfo(blob->uuid(), blob->type(), blob->size(), &blobIndex)) m_writer.writeBlobIndex(blobIndex); else m_writer.writeBlob(blob->uuid(), blob->type(), blob->size()); return 0; }
171,650
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 blkcg_init_queue(struct request_queue *q) { struct blkcg_gq *new_blkg, *blkg; bool preloaded; int ret; new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL); if (!new_blkg) return -ENOMEM; preloaded = !radix_tree_preload(GFP_KERNEL); /* * Make sure the root blkg exists and count the existing blkgs. As * @q is bypassing at this point, blkg_lookup_create() can't be * used. Open code insertion. */ rcu_read_lock(); spin_lock_irq(q->queue_lock); blkg = blkg_create(&blkcg_root, q, new_blkg); spin_unlock_irq(q->queue_lock); rcu_read_unlock(); if (preloaded) radix_tree_preload_end(); if (IS_ERR(blkg)) { blkg_free(new_blkg); return PTR_ERR(blkg); } q->root_blkg = blkg; q->root_rl.blkg = blkg; ret = blk_throtl_init(q); if (ret) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); } return ret; } Commit Message: blkcg: fix double free of new_blkg in blkcg_init_queue If blkg_create fails, new_blkg passed as an argument will be freed by blkg_create, so there is no need to free it again. Signed-off-by: Hou Tao <houtao1@huawei.com> Signed-off-by: Jens Axboe <axboe@fb.com> CWE ID: CWE-415
int blkcg_init_queue(struct request_queue *q) { struct blkcg_gq *new_blkg, *blkg; bool preloaded; int ret; new_blkg = blkg_alloc(&blkcg_root, q, GFP_KERNEL); if (!new_blkg) return -ENOMEM; preloaded = !radix_tree_preload(GFP_KERNEL); /* * Make sure the root blkg exists and count the existing blkgs. As * @q is bypassing at this point, blkg_lookup_create() can't be * used. Open code insertion. */ rcu_read_lock(); spin_lock_irq(q->queue_lock); blkg = blkg_create(&blkcg_root, q, new_blkg); spin_unlock_irq(q->queue_lock); rcu_read_unlock(); if (preloaded) radix_tree_preload_end(); if (IS_ERR(blkg)) return PTR_ERR(blkg); q->root_blkg = blkg; q->root_rl.blkg = blkg; ret = blk_throtl_init(q); if (ret) { spin_lock_irq(q->queue_lock); blkg_destroy_all(q); spin_unlock_irq(q->queue_lock); } return ret; }
169,318
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 LaunchServiceProcessControl(bool wait) { ServiceProcessControl::GetInstance()->Launch( base::Bind(&ServiceProcessControlBrowserTest::ProcessControlLaunched, base::Unretained(this)), base::Bind( &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed, base::Unretained(this))); if (wait) content::RunMessageLoop(); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <wez@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
void LaunchServiceProcessControl(bool wait) { void LaunchServiceProcessControl(base::RepeatingClosure on_launched) { ServiceProcessControl::GetInstance()->Launch( base::BindOnce( &ServiceProcessControlBrowserTest::ProcessControlLaunched, base::Unretained(this), on_launched), base::BindOnce( &ServiceProcessControlBrowserTest::ProcessControlLaunchFailed,
172,051
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 BluetoothDeviceChooserController::PostErrorCallback( blink::mojom::WebBluetoothResult error) { if (!base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(error_callback_, error))) { LOG(WARNING) << "No TaskRunner."; } } Commit Message: bluetooth: Implement getAvailability() This change implements the getAvailability() method for navigator.bluetooth as defined in the specification. Bug: 707640 Change-Id: I9e9b3e7f8ea7f259e975f71cb6d9570e5f04b479 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1651516 Reviewed-by: Chris Harrelson <chrishtr@chromium.org> Reviewed-by: Giovanni Ortuño Urquidi <ortuno@chromium.org> Reviewed-by: Kinuko Yasuda <kinuko@chromium.org> Commit-Queue: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Auto-Submit: Ovidio de Jesús Ruiz-Henríquez <odejesush@chromium.org> Cr-Commit-Position: refs/heads/master@{#688987} CWE ID: CWE-119
void BluetoothDeviceChooserController::PostErrorCallback( WebBluetoothResult error) { if (!base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(error_callback_, error))) { LOG(WARNING) << "No TaskRunner."; } }
172,445
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 SyncBackendHost::Core::DoInitialize(const DoInitializeOptions& options) { DCHECK(!sync_loop_); sync_loop_ = options.sync_loop; DCHECK(sync_loop_); if (options.delete_sync_data_folder) { DeleteSyncDataFolder(); } bool success = file_util::CreateDirectory(sync_data_folder_path_); DCHECK(success); DCHECK(!registrar_); registrar_ = options.registrar; DCHECK(registrar_); sync_manager_.reset(new sync_api::SyncManager(name_)); sync_manager_->AddObserver(this); success = sync_manager_->Init( sync_data_folder_path_, options.event_handler, options.service_url.host() + options.service_url.path(), options.service_url.EffectiveIntPort(), options.service_url.SchemeIsSecure(), BrowserThread::GetBlockingPool(), options.make_http_bridge_factory_fn.Run(), options.registrar /* as ModelSafeWorkerRegistrar */, options.extensions_activity_monitor, options.registrar /* as SyncManager::ChangeDelegate */, MakeUserAgentForSyncApi(), options.credentials, true, new BridgedSyncNotifier( options.chrome_sync_notification_bridge, options.sync_notifier_factory->CreateSyncNotifier()), options.restored_key_for_bootstrapping, options.testing_mode, &encryptor_, options.unrecoverable_error_handler, options.report_unrecoverable_error_function); LOG_IF(ERROR, !success) << "Syncapi initialization failed!"; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kSyncThrowUnrecoverableError)) { sync_manager_->ThrowUnrecoverableError(); } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncBackendHost::Core::DoInitialize(const DoInitializeOptions& options) { DCHECK(!sync_loop_); sync_loop_ = options.sync_loop; DCHECK(sync_loop_); if (options.delete_sync_data_folder) { DeleteSyncDataFolder(); } bool success = file_util::CreateDirectory(sync_data_folder_path_); DCHECK(success); DCHECK(!registrar_); registrar_ = options.registrar; DCHECK(registrar_); sync_manager_.reset(new sync_api::SyncManager(name_)); sync_manager_->AddObserver(this); success = sync_manager_->Init( sync_data_folder_path_, options.event_handler, options.service_url.host() + options.service_url.path(), options.service_url.EffectiveIntPort(), options.service_url.SchemeIsSecure(), BrowserThread::GetBlockingPool(), options.make_http_bridge_factory_fn.Run(), options.registrar /* as ModelSafeWorkerRegistrar */, options.extensions_activity_monitor, options.registrar /* as SyncManager::ChangeDelegate */, MakeUserAgentForSyncApi(), options.credentials, new BridgedSyncNotifier( options.chrome_sync_notification_bridge, options.sync_notifier_factory->CreateSyncNotifier()), options.restored_key_for_bootstrapping, options.testing_mode, &encryptor_, options.unrecoverable_error_handler, options.report_unrecoverable_error_function); LOG_IF(ERROR, !success) << "Syncapi initialization failed!"; if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kSyncThrowUnrecoverableError)) { sync_manager_->ThrowUnrecoverableError(); } }
170,785
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: INLINE UWORD8 impeg2d_bit_stream_get_bit(stream_t *ps_stream) { UWORD32 u4_bit,u4_offset,u4_temp; UWORD32 u4_curr_bit; u4_offset = ps_stream->u4_offset; u4_curr_bit = u4_offset & 0x1F; u4_bit = ps_stream->u4_buf; /* Move the current bit read from the current word to the least significant bit positions of 'c'.*/ u4_bit >>= BITS_IN_INT - u4_curr_bit - 1; u4_offset++; /* If the last bit of the last word of the buffer has been read update the currrent buf with next, and read next buf from bit stream buffer */ if (u4_curr_bit == 31) { ps_stream->u4_buf = ps_stream->u4_buf_nxt; u4_temp = *(ps_stream->pu4_buf_aligned)++; CONV_LE_TO_BE(ps_stream->u4_buf_nxt,u4_temp) } ps_stream->u4_offset = u4_offset; return (u4_bit & 0x1); } 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
INLINE UWORD8 impeg2d_bit_stream_get_bit(stream_t *ps_stream) { UWORD32 u4_bit,u4_offset,u4_temp; UWORD32 u4_curr_bit; u4_offset = ps_stream->u4_offset; u4_curr_bit = u4_offset & 0x1F; u4_bit = ps_stream->u4_buf; /* Move the current bit read from the current word to the least significant bit positions of 'c'.*/ u4_bit >>= BITS_IN_INT - u4_curr_bit - 1; u4_offset++; /* If the last bit of the last word of the buffer has been read update the currrent buf with next, and read next buf from bit stream buffer */ if (u4_curr_bit == 31) { ps_stream->u4_buf = ps_stream->u4_buf_nxt; if (ps_stream->u4_offset < ps_stream->u4_max_offset) { u4_temp = *(ps_stream->pu4_buf_aligned)++; CONV_LE_TO_BE(ps_stream->u4_buf_nxt,u4_temp) } } ps_stream->u4_offset = u4_offset; return (u4_bit & 0x1); }
173,942
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: OneClickSigninSyncStarter::OneClickSigninSyncStarter( Profile* profile, Browser* browser, const std::string& session_index, const std::string& email, const std::string& password, StartSyncMode start_mode, bool force_same_tab_navigation, ConfirmationRequired confirmation_required) : start_mode_(start_mode), force_same_tab_navigation_(force_same_tab_navigation), confirmation_required_(confirmation_required), weak_pointer_factory_(this) { DCHECK(profile); BrowserList::AddObserver(this); Initialize(profile, browser); SigninManager* manager = SigninManagerFactory::GetForProfile(profile_); SigninManager::OAuthTokenFetchedCallback callback; callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin, weak_pointer_factory_.GetWeakPtr()); manager->StartSignInWithCredentials(session_index, email, password, callback); } Commit Message: Display confirmation dialog for untrusted signins BUG=252062 Review URL: https://chromiumcodereview.appspot.com/17482002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@208520 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
OneClickSigninSyncStarter::OneClickSigninSyncStarter( Profile* profile, Browser* browser, const std::string& session_index, const std::string& email, const std::string& password, StartSyncMode start_mode, bool force_same_tab_navigation, ConfirmationRequired confirmation_required, SyncPromoUI::Source source) : start_mode_(start_mode), force_same_tab_navigation_(force_same_tab_navigation), confirmation_required_(confirmation_required), source_(source), weak_pointer_factory_(this) { DCHECK(profile); BrowserList::AddObserver(this); Initialize(profile, browser); SigninManager* manager = SigninManagerFactory::GetForProfile(profile_); SigninManager::OAuthTokenFetchedCallback callback; callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin, weak_pointer_factory_.GetWeakPtr()); manager->StartSignInWithCredentials(session_index, email, password, callback); }
171,245
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: checked_xmalloc (size_t size) { alloc_limit_assert ("checked_xmalloc", size); return xmalloc (size); } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
checked_xmalloc (size_t size) checked_xmalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); alloc_limit_assert ("checked_xmalloc", res); return xmalloc (num, size); }
168,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: int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } } Commit Message: IB/rxe: Fix mem_check_range integer overflow Update the range check to avoid integer-overflow in edge case. Resolves CVE 2016-8636. Signed-off-by: Eyal Itkin <eyal.itkin@gmail.com> Signed-off-by: Dan Carpenter <dan.carpenter@oracle.com> Reviewed-by: Leon Romanovsky <leonro@mellanox.com> Signed-off-by: Doug Ledford <dledford@redhat.com> CWE ID: CWE-190
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: if (iova < mem->iova || length > mem->length || iova > mem->iova + mem->length - length) return -EFAULT; return 0; default: return -EFAULT; } }
168,773
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 SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( const ModelTypeSet enabled_types) { if (initialized_ && enabled_types.Has(syncable::SESSIONS)) { WriteTransaction trans(FROM_HERE, GetUserShare()); WriteNode node(&trans); if (node.InitByTagLookup(kNigoriTag) != sync_api::BaseNode::INIT_OK) { LOG(WARNING) << "Unable to set 'sync_tabs' bit because Nigori node not " << "found."; return; } sync_pb::NigoriSpecifics specifics(node.GetNigoriSpecifics()); specifics.set_sync_tabs(true); node.SetNigoriSpecifics(specifics); } } Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default. BUG=none TEST= Review URL: https://chromiumcodereview.appspot.com/10443046 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void SyncManager::SyncInternal::MaybeSetSyncTabsInNigoriNode( }
170,795
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 controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } Commit Message: Security: update Lua struct package for security. During an auditing Apple found that the "struct" Lua package we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains a security problem. A bound-checking statement fails because of integer overflow. The bug exists since we initially integrated this package with Lua, when scripting was introduced, so every version of Redis with EVAL/EVALSHA capabilities exposed is affected. Instead of just fixing the bug, the library was updated to the latest version shipped by the author. CWE ID: CWE-190
static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } }
170,164
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: SchedulerObject::_continue(std::string key, std::string &/*reason*/, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster < 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true); return true; } Commit Message: CWE ID: CWE-20
SchedulerObject::_continue(std::string key, std::string &/*reason*/, std::string &text) { PROC_ID id = getProcByString(key.c_str()); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", key.c_str()); text = "Invalid Id"; return false; } scheduler.enqueueActOnJobMyself(id,JA_CONTINUE_JOBS,true); return true; }
164,831
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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 Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { } Commit Message: Don't report OnFirstSurfaceActivation for ui::Compositor Bug: 893850 Change-Id: Iee754cefbd083d0a21a2b672fb8e837eaab81c43 Reviewed-on: https://chromium-review.googlesource.com/c/1293712 Reviewed-by: Antoine Labour <piman@chromium.org> Commit-Queue: Saman Sami <samans@chromium.org> Cr-Commit-Position: refs/heads/master@{#601629} CWE ID: CWE-20
void Compositor::OnFirstSurfaceActivation( const viz::SurfaceInfo& surface_info) { NOTREACHED(); }
172,563
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: my_object_dict_of_dicts (MyObject *obj, GHashTable *in, GHashTable **out, GError **error) { *out = g_hash_table_new_full (g_str_hash, g_str_equal, (GDestroyNotify) g_free, (GDestroyNotify) g_hash_table_destroy); g_hash_table_foreach (in, hash_foreach_mangle_dict_of_strings, *out); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_dict_of_dicts (MyObject *obj, GHashTable *in,
165,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: void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error) { setDeviceOrientationOverride(error, 0, 0, 0); } Commit Message: DevTools: remove references to modules/device_orientation from core BUG=340221 Review URL: https://codereview.chromium.org/150913003 git-svn-id: svn://svn.chromium.org/blink/trunk@166493 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
171,402