instruction
stringclasses
1 value
input
stringlengths
90
9.34k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() { if (render_frame_host_->GetView() && render_frame_host_->render_view_host()->GetWidget()->is_hidden() != delegate_->IsHidden()) { if (delegate_->IsHidden()) { render_frame_host_->GetView()->Hide(); } else { render_frame_host_->GetView()->Show(); } } } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() { RenderWidgetHostView* view = GetRenderWidgetHostView(); if (view && static_cast<RenderWidgetHostImpl*>(view->GetRenderWidgetHost()) ->is_hidden() != delegate_->IsHidden()) { if (delegate_->IsHidden()) { view->Hide(); } else { view->Show(); } } }
172,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf("found! %d\n", (int)(t - p->t));*/ syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, "updateDevice() : memory allocation error"); free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, "new device discovered : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, "updateDevice(): cannot allocate memory"); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; } Commit Message: updateDevice() remove element from the list when realloc fails CWE ID: CWE-416
updateDevice(const struct header * headers, time_t t) { struct device ** pp = &devlist; struct device * p = *pp; /* = devlist; */ while(p) { if( p->headers[HEADER_NT].l == headers[HEADER_NT].l && (0==memcmp(p->headers[HEADER_NT].p, headers[HEADER_NT].p, headers[HEADER_NT].l)) && p->headers[HEADER_USN].l == headers[HEADER_USN].l && (0==memcmp(p->headers[HEADER_USN].p, headers[HEADER_USN].p, headers[HEADER_USN].l)) ) { /*printf("found! %d\n", (int)(t - p->t));*/ syslog(LOG_DEBUG, "device updated : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); p->t = t; /* update Location ! */ if(headers[HEADER_LOCATION].l > p->headers[HEADER_LOCATION].l) { struct device * tmp; tmp = realloc(p, sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l); if(!tmp) /* allocation error */ { syslog(LOG_ERR, "updateDevice() : memory allocation error"); *pp = p->next; /* remove "p" from the list */ free(p); return 0; } p = tmp; *pp = p; } memcpy(p->data + p->headers[0].l + p->headers[1].l, headers[2].p, headers[2].l); /* TODO : check p->headers[HEADER_LOCATION].l */ return 0; } pp = &p->next; p = *pp; /* p = p->next; */ } syslog(LOG_INFO, "new device discovered : %.*s", headers[HEADER_USN].l, headers[HEADER_USN].p); /* add */ { char * pc; int i; p = malloc( sizeof(struct device) + headers[0].l+headers[1].l+headers[2].l ); if(!p) { syslog(LOG_ERR, "updateDevice(): cannot allocate memory"); return -1; } p->next = devlist; p->t = t; pc = p->data; for(i = 0; i < 3; i++) { p->headers[i].p = pc; p->headers[i].l = headers[i].l; memcpy(pc, headers[i].p, headers[i].l); pc += headers[i].l; } devlist = p; sendNotifications(NOTIF_NEW, p, NULL); } return 1; }
169,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, blink::MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), blink::MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, page_request_id, requester_id_, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); } Commit Message: [MediaStream] Pass request ID parameters in the right order for OpenDevice() Prior to this CL, requester_id and page_request_id parameters were passed in incorrect order from MediaStreamDispatcherHost to MediaStreamManager for the OpenDevice() operation, which could lead to errors. Bug: 948564 Change-Id: Iadcf3fe26adaac50564102138ce212269cf32d62 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1569113 Reviewed-by: Marina Ciocea <[email protected]> Commit-Queue: Guido Urdaneta <[email protected]> Cr-Commit-Position: refs/heads/master@{#651255} CWE ID: CWE-119
void MediaStreamDispatcherHost::DoOpenDevice( int32_t page_request_id, const std::string& device_id, blink::MediaStreamType type, OpenDeviceCallback callback, MediaDeviceSaltAndOrigin salt_and_origin) { DCHECK_CURRENTLY_ON(BrowserThread::IO); if (!MediaStreamManager::IsOriginAllowed(render_process_id_, salt_and_origin.origin)) { std::move(callback).Run(false /* success */, std::string(), blink::MediaStreamDevice()); return; } media_stream_manager_->OpenDevice( render_process_id_, render_frame_id_, requester_id_, page_request_id, device_id, type, std::move(salt_and_origin), std::move(callback), base::BindRepeating(&MediaStreamDispatcherHost::OnDeviceStopped, weak_factory_.GetWeakPtr())); }
173,015
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadTILEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image, *tile_image; ImageInfo *read_info; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; tile_image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) return((Image *) NULL); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); if (*image_info->filename == '\0') ThrowReaderException(OptionError,"MustSpecifyAnImageName"); image->colorspace=tile_image->colorspace; image->matte=tile_image->matte; if (image->matte != MagickFalse) (void) SetImageBackgroundColor(image); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); if (LocaleCompare(tile_image->magick,"PATTERN") == 0) { tile_image->tile_offset.x=0; tile_image->tile_offset.y=0; } (void) TextureImage(image,tile_image); tile_image=DestroyImage(tile_image); if (image->colorspace == GRAYColorspace) image->type=GrayscaleType; return(GetFirstImageInList(image)); } Commit Message: CWE ID: CWE-119
static Image *ReadTILEImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image, *tile_image; ImageInfo *read_info; MagickBooleanType status; /* Initialize Image structure. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); read_info=CloneImageInfo(image_info); SetImageInfoBlob(read_info,(void *) NULL,0); *read_info->magick='\0'; tile_image=ReadImage(read_info,exception); read_info=DestroyImageInfo(read_info); if (tile_image == (Image *) NULL) return((Image *) NULL); image=AcquireImage(image_info); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(OptionError,"MustSpecifyImageSize"); status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (*image_info->filename == '\0') ThrowReaderException(OptionError,"MustSpecifyAnImageName"); image->colorspace=tile_image->colorspace; image->matte=tile_image->matte; if (image->matte != MagickFalse) (void) SetImageBackgroundColor(image); (void) CopyMagickString(image->filename,image_info->filename,MaxTextExtent); if (LocaleCompare(tile_image->magick,"PATTERN") == 0) { tile_image->tile_offset.x=0; tile_image->tile_offset.y=0; } (void) TextureImage(image,tile_image); tile_image=DestroyImage(tile_image); if (image->colorspace == GRAYColorspace) image->type=GrayscaleType; return(GetFirstImageInList(image)); }
168,610
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UkmPageLoadMetricsObserver::RecordTimingMetrics( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { ukm::builders::PageLoad builder(info.source_id); bool is_user_initiated_navigation = info.user_initiated_info.browser_initiated || timing.input_to_navigation_start; builder.SetExperimental_Navigation_UserInitiated( is_user_initiated_navigation); if (timing.input_to_navigation_start) { builder.SetExperimental_InputToNavigationStart( timing.input_to_navigation_start.value().InMilliseconds()); } if (timing.parse_timing->parse_start) { builder.SetParseTiming_NavigationToParseStart( timing.parse_timing->parse_start.value().InMilliseconds()); } if (timing.document_timing->dom_content_loaded_event_start) { builder.SetDocumentTiming_NavigationToDOMContentLoadedEventFired( timing.document_timing->dom_content_loaded_event_start.value() .InMilliseconds()); } if (timing.document_timing->load_event_start) { builder.SetDocumentTiming_NavigationToLoadEventFired( timing.document_timing->load_event_start.value().InMilliseconds()); } if (timing.paint_timing->first_paint) { builder.SetPaintTiming_NavigationToFirstPaint( timing.paint_timing->first_paint.value().InMilliseconds()); } if (timing.paint_timing->first_contentful_paint) { builder.SetPaintTiming_NavigationToFirstContentfulPaint( timing.paint_timing->first_contentful_paint.value().InMilliseconds()); } if (timing.paint_timing->first_meaningful_paint) { builder.SetExperimental_PaintTiming_NavigationToFirstMeaningfulPaint( timing.paint_timing->first_meaningful_paint.value().InMilliseconds()); } if (timing.paint_timing->largest_image_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->largest_image_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLargestImagePaint( timing.paint_timing->largest_image_paint.value().InMilliseconds()); } if (timing.paint_timing->last_image_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->last_image_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLastImagePaint( timing.paint_timing->last_image_paint.value().InMilliseconds()); } if (timing.paint_timing->largest_text_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->largest_text_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLargestTextPaint( timing.paint_timing->largest_text_paint.value().InMilliseconds()); } if (timing.paint_timing->last_text_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->last_text_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLastTextPaint( timing.paint_timing->last_text_paint.value().InMilliseconds()); } base::Optional<base::TimeDelta> largest_content_paint_time; uint64_t largest_content_paint_size; AssignTimeAndSizeForLargestContentfulPaint(largest_content_paint_time, largest_content_paint_size, timing.paint_timing); if (largest_content_paint_size > 0 && WasStartedInForegroundOptionalEventInForeground( largest_content_paint_time, info)) { builder.SetExperimental_PaintTiming_NavigationToLargestContentPaint( largest_content_paint_time.value().InMilliseconds()); } if (timing.interactive_timing->interactive) { base::TimeDelta time_to_interactive = timing.interactive_timing->interactive.value(); if (!timing.interactive_timing->first_invalidating_input || timing.interactive_timing->first_invalidating_input.value() > time_to_interactive) { builder.SetExperimental_NavigationToInteractive( time_to_interactive.InMilliseconds()); } } if (timing.interactive_timing->first_input_delay) { base::TimeDelta first_input_delay = timing.interactive_timing->first_input_delay.value(); builder.SetInteractiveTiming_FirstInputDelay2( first_input_delay.InMilliseconds()); } if (timing.interactive_timing->first_input_timestamp) { base::TimeDelta first_input_timestamp = timing.interactive_timing->first_input_timestamp.value(); builder.SetInteractiveTiming_FirstInputTimestamp2( first_input_timestamp.InMilliseconds()); } if (timing.interactive_timing->longest_input_delay) { base::TimeDelta longest_input_delay = timing.interactive_timing->longest_input_delay.value(); builder.SetInteractiveTiming_LongestInputDelay2( longest_input_delay.InMilliseconds()); } if (timing.interactive_timing->longest_input_timestamp) { base::TimeDelta longest_input_timestamp = timing.interactive_timing->longest_input_timestamp.value(); builder.SetInteractiveTiming_LongestInputTimestamp2( longest_input_timestamp.InMilliseconds()); } builder.SetNet_CacheBytes(ukm::GetExponentialBucketMin(cache_bytes_, 1.3)); builder.SetNet_NetworkBytes( ukm::GetExponentialBucketMin(network_bytes_, 1.3)); if (main_frame_timing_) ReportMainResourceTimingMetrics(timing, &builder); builder.Record(ukm::UkmRecorder::Get()); } Commit Message: Add boolean to UserIntiatedInfo noting if an input event led to navigation. Also refactor UkmPageLoadMetricsObserver to use this new boolean to report the user initiated metric in RecordPageLoadExtraInfoMetrics, so that it works correctly in the case when the page load failed. Bug: 925104 Change-Id: Ie08e7d3912cb1da484190d838005e95e57a209ff Reviewed-on: https://chromium-review.googlesource.com/c/1450460 Commit-Queue: Annie Sullivan <[email protected]> Reviewed-by: Bryan McQuade <[email protected]> Cr-Commit-Position: refs/heads/master@{#630870} CWE ID: CWE-79
void UkmPageLoadMetricsObserver::RecordTimingMetrics( const page_load_metrics::mojom::PageLoadTiming& timing, const page_load_metrics::PageLoadExtraInfo& info) { ukm::builders::PageLoad builder(info.source_id); if (timing.input_to_navigation_start) { builder.SetExperimental_InputToNavigationStart( timing.input_to_navigation_start.value().InMilliseconds()); } if (timing.parse_timing->parse_start) { builder.SetParseTiming_NavigationToParseStart( timing.parse_timing->parse_start.value().InMilliseconds()); } if (timing.document_timing->dom_content_loaded_event_start) { builder.SetDocumentTiming_NavigationToDOMContentLoadedEventFired( timing.document_timing->dom_content_loaded_event_start.value() .InMilliseconds()); } if (timing.document_timing->load_event_start) { builder.SetDocumentTiming_NavigationToLoadEventFired( timing.document_timing->load_event_start.value().InMilliseconds()); } if (timing.paint_timing->first_paint) { builder.SetPaintTiming_NavigationToFirstPaint( timing.paint_timing->first_paint.value().InMilliseconds()); } if (timing.paint_timing->first_contentful_paint) { builder.SetPaintTiming_NavigationToFirstContentfulPaint( timing.paint_timing->first_contentful_paint.value().InMilliseconds()); } if (timing.paint_timing->first_meaningful_paint) { builder.SetExperimental_PaintTiming_NavigationToFirstMeaningfulPaint( timing.paint_timing->first_meaningful_paint.value().InMilliseconds()); } if (timing.paint_timing->largest_image_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->largest_image_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLargestImagePaint( timing.paint_timing->largest_image_paint.value().InMilliseconds()); } if (timing.paint_timing->last_image_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->last_image_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLastImagePaint( timing.paint_timing->last_image_paint.value().InMilliseconds()); } if (timing.paint_timing->largest_text_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->largest_text_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLargestTextPaint( timing.paint_timing->largest_text_paint.value().InMilliseconds()); } if (timing.paint_timing->last_text_paint.has_value() && WasStartedInForegroundOptionalEventInForeground( timing.paint_timing->last_text_paint, info)) { builder.SetExperimental_PaintTiming_NavigationToLastTextPaint( timing.paint_timing->last_text_paint.value().InMilliseconds()); } base::Optional<base::TimeDelta> largest_content_paint_time; uint64_t largest_content_paint_size; AssignTimeAndSizeForLargestContentfulPaint(largest_content_paint_time, largest_content_paint_size, timing.paint_timing); if (largest_content_paint_size > 0 && WasStartedInForegroundOptionalEventInForeground( largest_content_paint_time, info)) { builder.SetExperimental_PaintTiming_NavigationToLargestContentPaint( largest_content_paint_time.value().InMilliseconds()); } if (timing.interactive_timing->interactive) { base::TimeDelta time_to_interactive = timing.interactive_timing->interactive.value(); if (!timing.interactive_timing->first_invalidating_input || timing.interactive_timing->first_invalidating_input.value() > time_to_interactive) { builder.SetExperimental_NavigationToInteractive( time_to_interactive.InMilliseconds()); } } if (timing.interactive_timing->first_input_delay) { base::TimeDelta first_input_delay = timing.interactive_timing->first_input_delay.value(); builder.SetInteractiveTiming_FirstInputDelay2( first_input_delay.InMilliseconds()); } if (timing.interactive_timing->first_input_timestamp) { base::TimeDelta first_input_timestamp = timing.interactive_timing->first_input_timestamp.value(); builder.SetInteractiveTiming_FirstInputTimestamp2( first_input_timestamp.InMilliseconds()); } if (timing.interactive_timing->longest_input_delay) { base::TimeDelta longest_input_delay = timing.interactive_timing->longest_input_delay.value(); builder.SetInteractiveTiming_LongestInputDelay2( longest_input_delay.InMilliseconds()); } if (timing.interactive_timing->longest_input_timestamp) { base::TimeDelta longest_input_timestamp = timing.interactive_timing->longest_input_timestamp.value(); builder.SetInteractiveTiming_LongestInputTimestamp2( longest_input_timestamp.InMilliseconds()); } builder.SetNet_CacheBytes(ukm::GetExponentialBucketMin(cache_bytes_, 1.3)); builder.SetNet_NetworkBytes( ukm::GetExponentialBucketMin(network_bytes_, 1.3)); if (main_frame_timing_) ReportMainResourceTimingMetrics(timing, &builder); builder.Record(ukm::UkmRecorder::Get()); }
172,497
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void RegisterPropertiesCallback(IBusPanelService* panel, IBusPropList* prop_list, gpointer user_data) { g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->RegisterProperties(prop_list); } 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
static void RegisterPropertiesCallback(IBusPanelService* panel, void RegisterProperties(IBusPanelService* panel, IBusPropList* prop_list) { DoRegisterProperties(prop_list); }
170,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: delete_principal_2_svc(dprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->princ, NULL)) { ret.code = KADM5_AUTH_DELETE; log_unauth("kadm5_delete_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_delete_principal((void *)handle, arg->princ); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
delete_principal_2_svc(dprinc_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, arg->princ, NULL)) { ret.code = KADM5_AUTH_DELETE; log_unauth("kadm5_delete_principal", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_delete_principal((void *)handle, arg->princ); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_mfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; memset(&l2info, 0, sizeof(l2info)); l2info.pictype = DLT_JUNIPER_MFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* child-link ? */ if (l2info.cookie_len == 0) { mfr_print(ndo, p, l2info.length); return l2info.header_len; } /* first try the LSQ protos */ if (l2info.cookie_len == AS_PIC_COOKIE_LEN) { switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length, l2info.caplen); return l2info.header_len; default: break; } return l2info.header_len; } /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLCSAP_ISONS<<8 | LLCSAP_ISONS): isoclns_print(ndo, p + 1, l2info.length - 1, l2info.caplen - 1); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1, l2info.caplen + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
juniper_mfr_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; memset(&l2info, 0, sizeof(l2info)); l2info.pictype = DLT_JUNIPER_MFR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; /* child-link ? */ if (l2info.cookie_len == 0) { mfr_print(ndo, p, l2info.length); return l2info.header_len; } /* first try the LSQ protos */ if (l2info.cookie_len == AS_PIC_COOKIE_LEN) { switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length); return l2info.header_len; default: break; } return l2info.header_len; } /* suppress Bundle-ID if frame was captured on a child-link */ if (ndo->ndo_eflag && EXTRACT_32BITS(l2info.cookie) != 1) ND_PRINT((ndo, "Bundle-ID %u, ", l2info.bundle)); switch (l2info.proto) { case (LLCSAP_ISONS<<8 | LLCSAP_ISONS): isoclns_print(ndo, p + 1, l2info.length - 1); break; case (LLC_UI<<8 | NLPID_Q933): case (LLC_UI<<8 | NLPID_IP): case (LLC_UI<<8 | NLPID_IP6): /* pass IP{4,6} to the OSI layer for proper link-layer printing */ isoclns_print(ndo, p - 1, l2info.length + 1); break; default: ND_PRINT((ndo, "unknown protocol 0x%04x, length %u", l2info.proto, l2info.length)); } return l2info.header_len; }
167,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MediaInterfaceProxy::OnConnectionError() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); interface_factory_ptr_.reset(); } Commit Message: media: Support hosting mojo CDM in a standalone service Currently when mojo CDM is enabled it is hosted in the MediaService running in the process specified by "mojo_media_host". However, on some platforms we need to run mojo CDM and other mojo media services in different processes. For example, on desktop platforms, we want to run mojo video decoder in the GPU process, but run the mojo CDM in the utility process. This CL adds a new build flag "enable_standalone_cdm_service". When enabled, the mojo CDM service will be hosted in a standalone "cdm" service running in the utility process. All other mojo media services will sill be hosted in the "media" servie running in the process specified by "mojo_media_host". BUG=664364 TEST=Encrypted media browser tests using mojo CDM is still working. Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487 Reviewed-on: https://chromium-review.googlesource.com/567172 Commit-Queue: Xiaohan Wang <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Dan Sanders <[email protected]> Cr-Commit-Position: refs/heads/master@{#486947} CWE ID: CWE-119
void MediaInterfaceProxy::OnConnectionError() { media::mojom::InterfaceFactory* MediaInterfaceProxy::GetCdmInterfaceFactory() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); #if !BUILDFLAG(ENABLE_STANDALONE_CDM_SERVICE) return GetMediaInterfaceFactory(); #else if (!cdm_interface_factory_ptr_) ConnectToCdmService(); DCHECK(cdm_interface_factory_ptr_); return cdm_interface_factory_ptr_.get(); #endif } void MediaInterfaceProxy::OnMediaServiceConnectionError() { DVLOG(1) << __FUNCTION__; DCHECK(thread_checker_.CalledOnValidThread()); interface_factory_ptr_.reset(); }
171,938
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int FindStartOffsetOfFileInZipFile(const char* zip_file, const char* filename) { FileDescriptor fd; if (!fd.OpenReadOnly(zip_file)) { LOG_ERRNO("%s: open failed trying to open zip file %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } struct stat stat_buf; if (stat(zip_file, &stat_buf) == -1) { LOG_ERRNO("%s: stat failed trying to stat zip file %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } if (stat_buf.st_size > kMaxZipFileLength) { LOG("%s: The size %ld of %s is too large to map\n", __FUNCTION__, stat_buf.st_size, zip_file); return CRAZY_OFFSET_FAILED; } void* mem = fd.Map(NULL, stat_buf.st_size, PROT_READ, MAP_PRIVATE, 0); if (mem == MAP_FAILED) { LOG_ERRNO("%s: mmap failed trying to mmap zip file %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } ScopedMMap scoped_mmap(mem, stat_buf.st_size); uint8_t* mem_bytes = static_cast<uint8_t*>(mem); int off; for (off = stat_buf.st_size - sizeof(kEndOfCentralDirectoryMarker); off >= 0; --off) { if (ReadUInt32(mem_bytes, off) == kEndOfCentralDirectoryMarker) { break; } } if (off == -1) { LOG("%s: Failed to find end of central directory in %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } uint32_t length_of_central_dir = ReadUInt32( mem_bytes, off + kOffsetOfCentralDirLengthInEndOfCentralDirectory); uint32_t start_of_central_dir = ReadUInt32( mem_bytes, off + kOffsetOfStartOfCentralDirInEndOfCentralDirectory); if (start_of_central_dir > off) { LOG("%s: Found out of range offset %u for start of directory in %s\n", __FUNCTION__, start_of_central_dir, zip_file); return CRAZY_OFFSET_FAILED; } uint32_t end_of_central_dir = start_of_central_dir + length_of_central_dir; if (end_of_central_dir > off) { LOG("%s: Found out of range offset %u for end of directory in %s\n", __FUNCTION__, end_of_central_dir, zip_file); return CRAZY_OFFSET_FAILED; } uint32_t num_entries = ReadUInt16( mem_bytes, off + kOffsetNumOfEntriesInEndOfCentralDirectory); off = start_of_central_dir; const int target_len = strlen(filename); int n = 0; for (; n < num_entries && off < end_of_central_dir; ++n) { uint32_t marker = ReadUInt32(mem_bytes, off); if (marker != kCentralDirHeaderMarker) { LOG("%s: Failed to find central directory header marker in %s. " "Found 0x%x but expected 0x%x\n", __FUNCTION__, zip_file, marker, kCentralDirHeaderMarker); return CRAZY_OFFSET_FAILED; } uint32_t file_name_length = ReadUInt16(mem_bytes, off + kOffsetFilenameLengthInCentralDirectory); uint32_t extra_field_length = ReadUInt16(mem_bytes, off + kOffsetExtraFieldLengthInCentralDirectory); uint32_t comment_field_length = ReadUInt16(mem_bytes, off + kOffsetCommentLengthInCentralDirectory); uint32_t header_length = kOffsetFilenameInCentralDirectory + file_name_length + extra_field_length + comment_field_length; uint32_t local_header_offset = ReadUInt32(mem_bytes, off + kOffsetLocalHeaderOffsetInCentralDirectory); uint8_t* filename_bytes = mem_bytes + off + kOffsetFilenameInCentralDirectory; if (file_name_length == target_len && memcmp(filename_bytes, filename, target_len) == 0) { uint32_t marker = ReadUInt32(mem_bytes, local_header_offset); if (marker != kLocalHeaderMarker) { LOG("%s: Failed to find local file header marker in %s. " "Found 0x%x but expected 0x%x\n", __FUNCTION__, zip_file, marker, kLocalHeaderMarker); return CRAZY_OFFSET_FAILED; } uint32_t compression_method = ReadUInt16( mem_bytes, local_header_offset + kOffsetCompressionMethodInLocalHeader); if (compression_method != kCompressionMethodStored) { LOG("%s: %s is compressed within %s. " "Found compression method %u but expected %u\n", __FUNCTION__, filename, zip_file, compression_method, kCompressionMethodStored); return CRAZY_OFFSET_FAILED; } uint32_t file_name_length = ReadUInt16( mem_bytes, local_header_offset + kOffsetFilenameLengthInLocalHeader); uint32_t extra_field_length = ReadUInt16( mem_bytes, local_header_offset + kOffsetExtraFieldLengthInLocalHeader); uint32_t header_length = kOffsetFilenameInLocalHeader + file_name_length + extra_field_length; return local_header_offset + header_length; } off += header_length; } if (n < num_entries) { LOG("%s: Did not find all the expected entries in the central directory. " "Found %d but expected %d\n", __FUNCTION__, n, num_entries); } if (off < end_of_central_dir) { LOG("%s: There are %d extra bytes at the end of the central directory.\n", __FUNCTION__, end_of_central_dir - off); } LOG("%s: Did not find %s in %s\n", __FUNCTION__, filename, zip_file); return CRAZY_OFFSET_FAILED; } Commit Message: crazy linker: Alter search for zip EOCD start When loading directly from APK, begin searching backwards for the zip EOCD record signature at size of EOCD record bytes before the end of the file. BUG=537205 [email protected] Review URL: https://codereview.chromium.org/1390553002 . Cr-Commit-Position: refs/heads/master@{#352577} CWE ID: CWE-20
int FindStartOffsetOfFileInZipFile(const char* zip_file, const char* filename) { FileDescriptor fd; if (!fd.OpenReadOnly(zip_file)) { LOG_ERRNO("%s: open failed trying to open zip file %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } struct stat stat_buf; if (stat(zip_file, &stat_buf) == -1) { LOG_ERRNO("%s: stat failed trying to stat zip file %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } if (stat_buf.st_size > kMaxZipFileLength) { LOG("%s: The size %ld of %s is too large to map\n", __FUNCTION__, stat_buf.st_size, zip_file); return CRAZY_OFFSET_FAILED; } void* mem = fd.Map(NULL, stat_buf.st_size, PROT_READ, MAP_PRIVATE, 0); if (mem == MAP_FAILED) { LOG_ERRNO("%s: mmap failed trying to mmap zip file %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } ScopedMMap scoped_mmap(mem, stat_buf.st_size); // central directory marker. The earliest occurrence we accept is // size of end of central directory bytes back from from the end of the // file. uint8_t* mem_bytes = static_cast<uint8_t*>(mem); int off = stat_buf.st_size - kEndOfCentralDirectoryRecordSize; for (; off >= 0; --off) { if (ReadUInt32(mem_bytes, off) == kEndOfCentralDirectoryMarker) { break; } } if (off == -1) { LOG("%s: Failed to find end of central directory in %s\n", __FUNCTION__, zip_file); return CRAZY_OFFSET_FAILED; } uint32_t length_of_central_dir = ReadUInt32( mem_bytes, off + kOffsetOfCentralDirLengthInEndOfCentralDirectory); uint32_t start_of_central_dir = ReadUInt32( mem_bytes, off + kOffsetOfStartOfCentralDirInEndOfCentralDirectory); if (start_of_central_dir > off) { LOG("%s: Found out of range offset %u for start of directory in %s\n", __FUNCTION__, start_of_central_dir, zip_file); return CRAZY_OFFSET_FAILED; } uint32_t end_of_central_dir = start_of_central_dir + length_of_central_dir; if (end_of_central_dir > off) { LOG("%s: Found out of range offset %u for end of directory in %s\n", __FUNCTION__, end_of_central_dir, zip_file); return CRAZY_OFFSET_FAILED; } uint32_t num_entries = ReadUInt16( mem_bytes, off + kOffsetNumOfEntriesInEndOfCentralDirectory); off = start_of_central_dir; const int target_len = strlen(filename); int n = 0; for (; n < num_entries && off < end_of_central_dir; ++n) { uint32_t marker = ReadUInt32(mem_bytes, off); if (marker != kCentralDirHeaderMarker) { LOG("%s: Failed to find central directory header marker in %s. " "Found 0x%x but expected 0x%x\n", __FUNCTION__, zip_file, marker, kCentralDirHeaderMarker); return CRAZY_OFFSET_FAILED; } uint32_t file_name_length = ReadUInt16(mem_bytes, off + kOffsetFilenameLengthInCentralDirectory); uint32_t extra_field_length = ReadUInt16(mem_bytes, off + kOffsetExtraFieldLengthInCentralDirectory); uint32_t comment_field_length = ReadUInt16(mem_bytes, off + kOffsetCommentLengthInCentralDirectory); uint32_t header_length = kOffsetFilenameInCentralDirectory + file_name_length + extra_field_length + comment_field_length; uint32_t local_header_offset = ReadUInt32(mem_bytes, off + kOffsetLocalHeaderOffsetInCentralDirectory); uint8_t* filename_bytes = mem_bytes + off + kOffsetFilenameInCentralDirectory; if (file_name_length == target_len && memcmp(filename_bytes, filename, target_len) == 0) { uint32_t marker = ReadUInt32(mem_bytes, local_header_offset); if (marker != kLocalHeaderMarker) { LOG("%s: Failed to find local file header marker in %s. " "Found 0x%x but expected 0x%x\n", __FUNCTION__, zip_file, marker, kLocalHeaderMarker); return CRAZY_OFFSET_FAILED; } uint32_t compression_method = ReadUInt16( mem_bytes, local_header_offset + kOffsetCompressionMethodInLocalHeader); if (compression_method != kCompressionMethodStored) { LOG("%s: %s is compressed within %s. " "Found compression method %u but expected %u\n", __FUNCTION__, filename, zip_file, compression_method, kCompressionMethodStored); return CRAZY_OFFSET_FAILED; } uint32_t file_name_length = ReadUInt16( mem_bytes, local_header_offset + kOffsetFilenameLengthInLocalHeader); uint32_t extra_field_length = ReadUInt16( mem_bytes, local_header_offset + kOffsetExtraFieldLengthInLocalHeader); uint32_t header_length = kOffsetFilenameInLocalHeader + file_name_length + extra_field_length; return local_header_offset + header_length; } off += header_length; } if (n < num_entries) { LOG("%s: Did not find all the expected entries in the central directory. " "Found %d but expected %d\n", __FUNCTION__, n, num_entries); } if (off < end_of_central_dir) { LOG("%s: There are %d extra bytes at the end of the central directory.\n", __FUNCTION__, end_of_central_dir - off); } LOG("%s: Did not find %s in %s\n", __FUNCTION__, filename, zip_file); return CRAZY_OFFSET_FAILED; }
171,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __exit ipgre_fini(void) { rtnl_link_unregister(&ipgre_tap_ops); rtnl_link_unregister(&ipgre_link_ops); unregister_pernet_device(&ipgre_net_ops); if (inet_del_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) printk(KERN_INFO "ipgre close: can't remove protocol\n"); } Commit Message: gre: fix netns vs proto registration ordering GRE protocol receive hook can be called right after protocol addition is done. If netns stuff is not yet initialized, we're going to oops in net_generic(). This is remotely oopsable if ip_gre is compiled as module and packet comes at unfortunate moment of module loading. Signed-off-by: Alexey Dobriyan <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static void __exit ipgre_fini(void) { rtnl_link_unregister(&ipgre_tap_ops); rtnl_link_unregister(&ipgre_link_ops); if (inet_del_protocol(&ipgre_protocol, IPPROTO_GRE) < 0) printk(KERN_INFO "ipgre close: can't remove protocol\n"); unregister_pernet_device(&ipgre_net_ops); }
165,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _fep_open_control_socket (Fep *fep) { struct sockaddr_un sun; char *path; int fd; ssize_t sun_len; fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { perror ("socket"); return -1; } path = create_socket_name ("fep-XXXXXX/control"); if (strlen (path) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (path), sizeof (sun.sun_path)); free (path); return -1; } memset (&sun, 0, sizeof(sun)); sun.sun_family = AF_UNIX; #ifdef __linux__ sun.sun_path[0] = '\0'; memcpy (sun.sun_path + 1, path, strlen (path)); sun_len = offsetof (struct sockaddr_un, sun_path) + strlen (path) + 1; remove_control_socket (path); #else memcpy (sun.sun_path, path, strlen (path)); sun_len = sizeof (struct sockaddr_un); #endif if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0) { perror ("bind"); free (path); close (fd); return -1; } if (listen (fd, 5) < 0) { perror ("listen"); free (path); close (fd); return -1; } fep->server = fd; fep->control_socket_path = path; return 0; } Commit Message: Don't use abstract Unix domain sockets CWE ID: CWE-264
_fep_open_control_socket (Fep *fep) { struct sockaddr_un sun; char *path; int fd; ssize_t sun_len; fd = socket (AF_UNIX, SOCK_STREAM, 0); if (fd < 0) { perror ("socket"); return -1; } path = create_socket_name ("fep-XXXXXX/control"); if (strlen (path) + 1 >= sizeof(sun.sun_path)) { fep_log (FEP_LOG_LEVEL_WARNING, "unix domain socket path too long: %d + 1 >= %d", strlen (path), sizeof (sun.sun_path)); free (path); return -1; } memset (&sun, 0, sizeof(sun)); sun.sun_family = AF_UNIX; memcpy (sun.sun_path, path, strlen (path)); sun_len = sizeof (struct sockaddr_un); if (bind (fd, (const struct sockaddr *) &sun, sun_len) < 0) { perror ("bind"); free (path); close (fd); return -1; } if (listen (fd, 5) < 0) { perror ("listen"); free (path); close (fd); return -1; } fep->server = fd; fep->control_socket_path = path; return 0; }
166,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len) { guint8 key_version; guint8 *key_data; guint8 *szEncryptedKey; guint16 key_bytes_len = 0; /* Length of the total key data field */ guint16 key_len; /* Actual group key length */ static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */ AIRPDCAP_SEC_ASSOCIATION *tmp_sa; /* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */ /* Preparation for decrypting the group key - determine group key data length */ /* depending on whether the pairwise key is TKIP or AES encryption key */ key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]); if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ /* TKIP */ key_bytes_len = pntoh16(pEAPKey->key_length); }else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ /* AES */ key_bytes_len = pntoh16(pEAPKey->key_data_len); /* AES keys must be at least 128 bits = 16 bytes. */ if (key_bytes_len < 16) { return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } } if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) { return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Encrypted key is in the information element field of the EAPOL key packet */ key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY); szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len); DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len); DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16); DEBUG_DUMP("decryption_key:", decryption_key, 16); /* We are rekeying, save old sa */ tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION)); memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); sa->next=tmp_sa; /* As we have no concept of the prior association request at this point, we need to deduce the */ /* group key cipher from the length of the key bytes. In WPA this is straightforward as the */ /* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */ /* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */ /* does not. Also there are other (variable length) items in the keybytes which we need to account */ /* for to determine the true key length, and thus the group cipher. */ if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ guint8 new_key[32]; guint8 dummy[256]; /* TKIP key */ /* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */ /* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */ rc4_state_struct rc4_state; /* The WPA group key just contains the GTK bytes so deducing the type is straightforward */ /* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */ sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP; /* Build the full decryption key based on the IV and part of the pairwise key */ memcpy(new_key, pEAPKey->key_iv, 16); memcpy(new_key+16, decryption_key, 16); DEBUG_DUMP("FullDecrKey:", new_key, 32); crypt_rc4_init(&rc4_state, new_key, sizeof(new_key)); /* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */ crypt_rc4(&rc4_state, dummy, 256); crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len); } else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ /* AES CCMP key */ guint8 key_found; guint8 key_length; guint16 key_index; guint8 *decrypted_data; /* Unwrap the key; the result is key_bytes_len in length */ decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len); /* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure. The key itself is stored as a GTK KDE WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to pass pointer to the actual key with 8 bytes offset */ key_found = FALSE; key_index = 0; /* Parse Key data until we found GTK KDE */ /* GTK KDE = 00-0F-AC 01 */ while(key_index < (key_bytes_len - 6) && !key_found){ guint8 rsn_id; guint32 type; /* Get RSN ID */ rsn_id = decrypted_data[key_index]; type = ((decrypted_data[key_index + 2] << 24) + (decrypted_data[key_index + 3] << 16) + (decrypted_data[key_index + 4] << 8) + (decrypted_data[key_index + 5])); if (rsn_id == 0xdd && type == 0x000fac01) { key_found = TRUE; } else { key_index += decrypted_data[key_index+1]+2; } } if (key_found){ key_length = decrypted_data[key_index+1] - 6; if (key_index+8 >= key_bytes_len || key_length > key_bytes_len - key_index - 8) { g_free(decrypted_data); g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Skip over the GTK header info, and don't copy past the end of the encrypted data */ memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length); } else { g_free(decrypted_data); g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } if (key_length == TKIP_GROUP_KEY_LEN) sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP; else sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP; g_free(decrypted_data); } key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN; if (key_len > key_bytes_len) { /* the key required for this protocol is longer than the key that we just calculated */ g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Decrypted key is now in szEncryptedKey with len of key_len */ DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len); /* Load the proper key material info into the SA */ sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */ sa->validKey = TRUE; /* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */ /* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */ memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk)); memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len); g_free(szEncryptedKey); return AIRPDCAP_RET_SUCCESS_HANDSHAKE; } Commit Message: Sanity check eapol_len in AirPDcapDecryptWPABroadcastKey Bug: 12175 Change-Id: Iaf977ba48f8668bf8095800a115ff9a3472dd893 Reviewed-on: https://code.wireshark.org/review/15326 Petri-Dish: Michael Mann <[email protected]> Tested-by: Petri Dish Buildbot <[email protected]> Reviewed-by: Alexis La Goutte <[email protected]> Reviewed-by: Peter Wu <[email protected]> Tested-by: Peter Wu <[email protected]> CWE ID: CWE-125
AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len) { guint8 key_version; guint8 *key_data; guint8 *szEncryptedKey; guint16 key_bytes_len = 0; /* Length of the total key data field */ guint16 key_len; /* Actual group key length */ static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */ AIRPDCAP_SEC_ASSOCIATION *tmp_sa; /* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */ /* Preparation for decrypting the group key - determine group key data length */ /* depending on whether the pairwise key is TKIP or AES encryption key */ key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]); if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ /* TKIP */ key_bytes_len = pntoh16(pEAPKey->key_length); }else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ /* AES */ key_bytes_len = pntoh16(pEAPKey->key_data_len); /* AES keys must be at least 128 bits = 16 bytes. */ if (key_bytes_len < 16) { return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } } if ((key_bytes_len < GROUP_KEY_MIN_LEN) || (eapol_len < sizeof(EAPOL_RSN_KEY)) || (key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) { return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Encrypted key is in the information element field of the EAPOL key packet */ key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY); szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len); DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len); DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16); DEBUG_DUMP("decryption_key:", decryption_key, 16); /* We are rekeying, save old sa */ tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION)); memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); sa->next=tmp_sa; /* As we have no concept of the prior association request at this point, we need to deduce the */ /* group key cipher from the length of the key bytes. In WPA this is straightforward as the */ /* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */ /* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */ /* does not. Also there are other (variable length) items in the keybytes which we need to account */ /* for to determine the true key length, and thus the group cipher. */ if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){ guint8 new_key[32]; guint8 dummy[256]; /* TKIP key */ /* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */ /* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */ rc4_state_struct rc4_state; /* The WPA group key just contains the GTK bytes so deducing the type is straightforward */ /* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */ sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP; /* Build the full decryption key based on the IV and part of the pairwise key */ memcpy(new_key, pEAPKey->key_iv, 16); memcpy(new_key+16, decryption_key, 16); DEBUG_DUMP("FullDecrKey:", new_key, 32); crypt_rc4_init(&rc4_state, new_key, sizeof(new_key)); /* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */ crypt_rc4(&rc4_state, dummy, 256); crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len); } else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){ /* AES CCMP key */ guint8 key_found; guint8 key_length; guint16 key_index; guint8 *decrypted_data; /* Unwrap the key; the result is key_bytes_len in length */ decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len); /* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure. The key itself is stored as a GTK KDE WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to pass pointer to the actual key with 8 bytes offset */ key_found = FALSE; key_index = 0; /* Parse Key data until we found GTK KDE */ /* GTK KDE = 00-0F-AC 01 */ while(key_index < (key_bytes_len - 6) && !key_found){ guint8 rsn_id; guint32 type; /* Get RSN ID */ rsn_id = decrypted_data[key_index]; type = ((decrypted_data[key_index + 2] << 24) + (decrypted_data[key_index + 3] << 16) + (decrypted_data[key_index + 4] << 8) + (decrypted_data[key_index + 5])); if (rsn_id == 0xdd && type == 0x000fac01) { key_found = TRUE; } else { key_index += decrypted_data[key_index+1]+2; } } if (key_found){ key_length = decrypted_data[key_index+1] - 6; if (key_index+8 >= key_bytes_len || key_length > key_bytes_len - key_index - 8) { g_free(decrypted_data); g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Skip over the GTK header info, and don't copy past the end of the encrypted data */ memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length); } else { g_free(decrypted_data); g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } if (key_length == TKIP_GROUP_KEY_LEN) sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP; else sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP; g_free(decrypted_data); } key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN; if (key_len > key_bytes_len) { /* the key required for this protocol is longer than the key that we just calculated */ g_free(szEncryptedKey); return AIRPDCAP_RET_NO_VALID_HANDSHAKE; } /* Decrypted key is now in szEncryptedKey with len of key_len */ DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len); /* Load the proper key material info into the SA */ sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */ sa->validKey = TRUE; /* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */ /* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */ memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk)); memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len); g_free(szEncryptedKey); return AIRPDCAP_RET_SUCCESS_HANDSHAKE; }
167,157
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Start() { DVLOG(2) << "Starting SafeBrowsing download check for: " << item_->DebugString(true); DCHECK_CURRENTLY_ON(BrowserThread::UI); DownloadCheckResultReason reason = REASON_MAX; if (!IsSupportedDownload( *item_, item_->GetTargetFilePath(), &reason, &type_)) { switch (reason) { case REASON_EMPTY_URL_CHAIN: case REASON_INVALID_URL: case REASON_UNSUPPORTED_URL_SCHEME: PostFinishTask(UNKNOWN, reason); return; case REASON_NOT_BINARY_FILE: RecordFileExtensionType(item_->GetTargetFilePath()); PostFinishTask(UNKNOWN, reason); return; default: NOTREACHED(); } } RecordFileExtensionType(item_->GetTargetFilePath()); if (item_->GetTargetFilePath().MatchesExtension( FILE_PATH_LITERAL(".zip"))) { StartExtractZipFeatures(); } else { DCHECK(!download_protection_util::IsArchiveFile( item_->GetTargetFilePath())); StartExtractFileFeatures(); } } Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService. BUG=496898,464083 [email protected], [email protected], [email protected], [email protected] Review URL: https://codereview.chromium.org/1299223006 . Cr-Commit-Position: refs/heads/master@{#344876} CWE ID:
void Start() { DVLOG(2) << "Starting SafeBrowsing download check for: " << item_->DebugString(true); DCHECK_CURRENTLY_ON(BrowserThread::UI); DownloadCheckResultReason reason = REASON_MAX; if (!IsSupportedDownload( *item_, item_->GetTargetFilePath(), &reason, &type_)) { switch (reason) { case REASON_EMPTY_URL_CHAIN: case REASON_INVALID_URL: case REASON_UNSUPPORTED_URL_SCHEME: PostFinishTask(UNKNOWN, reason); return; case REASON_NOT_BINARY_FILE: RecordFileExtensionType(item_->GetTargetFilePath()); PostFinishTask(UNKNOWN, reason); return; default: NOTREACHED(); } } RecordFileExtensionType(item_->GetTargetFilePath()); if (item_->GetTargetFilePath().MatchesExtension( FILE_PATH_LITERAL(".zip"))) { StartExtractZipFeatures(); #if defined(OS_MACOSX) } else if (item_->GetTargetFilePath().MatchesExtension( FILE_PATH_LITERAL(".dmg"))) { StartExtractDmgFeatures(); #endif } else { DCHECK(!download_protection_util::IsArchiveFile( item_->GetTargetFilePath())); StartExtractFileFeatures(); } }
171,715
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SessionRestore::IsRestoring(const Profile* profile) { return (profiles_getting_restored && profiles_getting_restored->find(profile) != profiles_getting_restored->end()); } Commit Message: Lands http://codereview.chromium.org/9316065/ for Marja. I reviewed this, so I'm using TBR to land it. Don't crash if multiple SessionRestoreImpl:s refer to the same Profile. It shouldn't ever happen but it seems to happen anyway. BUG=111238 TEST=NONE [email protected] [email protected] Review URL: https://chromiumcodereview.appspot.com/9343005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@120648 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool SessionRestore::IsRestoring(const Profile* profile) { if (active_session_restorers == NULL) return false; for (std::set<SessionRestoreImpl*>::const_iterator it = active_session_restorers->begin(); it != active_session_restorers->end(); ++it) { if ((*it)->profile() == profile) return true; } return false; }
171,036
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void test_parser(void) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); /*printf("parsing Ret val is %x index is %d\n", retval, i);*/ /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } } bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception CWE ID: CWE-254
void test_parser(void) { void test_parser_param(uint8_t hvi_trick) { int i, retval; bzrtpPacket_t *zrtpPacket; /* Create zrtp Context to use H0-H3 chains and others */ bzrtpContext_t *context87654321 = bzrtp_createBzrtpContext(0x87654321); bzrtpContext_t *context12345678 = bzrtp_createBzrtpContext(0x12345678); /* replace created H by the patterns one to be able to generate the correct packet */ memcpy (context12345678->channelContext[0]->selfH[0], H12345678[0], 32); memcpy (context12345678->channelContext[0]->selfH[1], H12345678[1], 32); memcpy (context12345678->channelContext[0]->selfH[2], H12345678[2], 32); memcpy (context12345678->channelContext[0]->selfH[3], H12345678[3], 32); memcpy (context87654321->channelContext[0]->selfH[0], H87654321[0], 32); memcpy (context87654321->channelContext[0]->selfH[1], H87654321[1], 32); memcpy (context87654321->channelContext[0]->selfH[2], H87654321[2], 32); memcpy (context87654321->channelContext[0]->selfH[3], H87654321[3], 32); /* preset the key agreement algo in the contexts */ context87654321->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context12345678->channelContext[0]->keyAgreementAlgo = ZRTP_KEYAGREEMENT_DH3k; context87654321->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context12345678->channelContext[0]->cipherAlgo = ZRTP_CIPHER_AES1; context87654321->channelContext[0]->hashAlgo = ZRTP_HASH_S256; context12345678->channelContext[0]->hashAlgo = ZRTP_HASH_S256; updateCryptoFunctionPointers(context87654321->channelContext[0]); updateCryptoFunctionPointers(context12345678->channelContext[0]); /* set the zrtp and mac keys */ context87654321->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyi = (uint8_t *)malloc(32); context87654321->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context12345678->channelContext[0]->mackeyr = (uint8_t *)malloc(32); context87654321->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyi = (uint8_t *)malloc(16); context87654321->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); context12345678->channelContext[0]->zrtpkeyr = (uint8_t *)malloc(16); memcpy(context12345678->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context12345678->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context12345678->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context12345678->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); memcpy(context87654321->channelContext[0]->mackeyi, mackeyi, 32); memcpy(context87654321->channelContext[0]->mackeyr, mackeyr, 32); memcpy(context87654321->channelContext[0]->zrtpkeyi, zrtpkeyi, 16); memcpy(context87654321->channelContext[0]->zrtpkeyr, zrtpkeyr, 16); /* set the role: 87654321 is initiator in our exchange pattern */ context12345678->channelContext[0]->role = RESPONDER; for (i=0; i<TEST_PACKET_NUMBER; i++) { uint8_t freePacketFlag = 1; /* parse a packet string from patterns */ zrtpPacket = bzrtp_packetCheck(patternZRTPPackets[i], patternZRTPMetaData[i][0], (patternZRTPMetaData[i][1])-1, &retval); retval += bzrtp_packetParser((patternZRTPMetaData[i][2]==0x87654321)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x87654321)?context12345678->channelContext[0]:context87654321->channelContext[0], patternZRTPPackets[i], patternZRTPMetaData[i][0], zrtpPacket); if (hvi_trick==0) { CU_ASSERT_EQUAL_FATAL(retval,0); } else { /* when hvi trick is enable, the DH2 parsing shall fail and return BZRTP_PARSER_ERROR_UNMATCHINGHVI */ if (zrtpPacket->messageType==MSGTYPE_DHPART2) { CU_ASSERT_EQUAL_FATAL(retval, BZRTP_PARSER_ERROR_UNMATCHINGHVI); /* We shall then anyway skip the end of the test */ /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); return; } else { CU_ASSERT_EQUAL_FATAL(retval,0); } } bzrtp_message("parsing Ret val is %x index is %d\n", retval, i); /* We must store some packets in the context if we want to be able to parse further packets */ if (zrtpPacket->messageType==MSGTYPE_HELLO) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[COMMIT_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } if (zrtpPacket->messageType==MSGTYPE_DHPART1 || zrtpPacket->messageType==MSGTYPE_DHPART2) { if (patternZRTPMetaData[i][2]==0x87654321) { context12345678->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } else { context87654321->channelContext[0]->peerPackets[DHPART_MESSAGE_STORE_ID] = zrtpPacket; } freePacketFlag = 0; } /* free the packet string as will be created again by the packetBuild function and might have been copied by packetParser */ free(zrtpPacket->packetString); /* build a packet string from the parser packet*/ retval = bzrtp_packetBuild((patternZRTPMetaData[i][2]==0x12345678)?context12345678:context87654321, (patternZRTPMetaData[i][2]==0x12345678)?context12345678->channelContext[0]:context87654321->channelContext[0], zrtpPacket, patternZRTPMetaData[i][1]); /* if (retval ==0) { packetDump(zrtpPacket, 1); } else { bzrtp_message("Ret val is %x index is %d\n", retval, i); }*/ /* check they are the same */ if (zrtpPacket->packetString != NULL) { CU_ASSERT_TRUE(memcmp(zrtpPacket->packetString, patternZRTPPackets[i], patternZRTPMetaData[i][0]) == 0); } else { CU_FAIL("Unable to build packet"); } if (freePacketFlag == 1) { bzrtp_freeZrtpPacket(zrtpPacket); } /* modify the hvi stored in the peerPackets, this shall result in parsing failure on DH2 packet */ if (hvi_trick == 1) { if (zrtpPacket->messageType==MSGTYPE_COMMIT) { if (patternZRTPMetaData[i][2]==0x87654321) { bzrtpCommitMessage_t *peerCommitMessageData; peerCommitMessageData = (bzrtpCommitMessage_t *)zrtpPacket->messageData; peerCommitMessageData->hvi[0]=0xFF; } } } } /* reset pointers to selfHello packet in order to avoid double free */ context87654321->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; context12345678->channelContext[0]->selfPackets[HELLO_MESSAGE_STORE_ID] = NULL; bzrtp_destroyBzrtpContext(context87654321, 0x87654321); bzrtp_destroyBzrtpContext(context12345678, 0x12345678); }
168,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void jslGetTokenString(char *str, size_t len) { if (lex->tk == LEX_ID) { strncpy(str, "ID:", len); strncat(str, jslGetTokenValueAsString(), len); } else if (lex->tk == LEX_STR) { strncpy(str, "String:'", len); strncat(str, jslGetTokenValueAsString(), len); strncat(str, "'", len); } else jslTokenAsString(lex->tk, str, len); } Commit Message: Fix strncat/cpy bounding issues (fix #1425) CWE ID: CWE-119
void jslGetTokenString(char *str, size_t len) { if (lex->tk == LEX_ID) { espruino_snprintf(str, len, "ID:%s", jslGetTokenValueAsString()); } else if (lex->tk == LEX_STR) { espruino_snprintf(str, len, "String:'%s'", jslGetTokenValueAsString()); } else jslTokenAsString(lex->tk, str, len); }
169,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int ret = 0, size = 0; const char *name = NULL; char *value = NULL; struct iattr newattrs; umode_t new_mode = inode->i_mode, old_mode = inode->i_mode; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { ret = posix_acl_equiv_mode(acl, &new_mode); if (ret < 0) goto out; if (ret == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) { ret = acl ? -EINVAL : 0; goto out; } name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: ret = -EINVAL; goto out; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_NOFS); if (!value) { ret = -ENOMEM; goto out; } ret = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (ret < 0) goto out_free; } if (new_mode != old_mode) { newattrs.ia_mode = new_mode; newattrs.ia_valid = ATTR_MODE; ret = __ceph_setattr(inode, &newattrs); if (ret) goto out_free; } ret = __ceph_setxattr(inode, name, value, size, 0); if (ret) { if (new_mode != old_mode) { newattrs.ia_mode = old_mode; newattrs.ia_valid = ATTR_MODE; __ceph_setattr(inode, &newattrs); } goto out_free; } ceph_set_cached_acl(inode, type, acl); out_free: kfree(value); out: return ret; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
int ceph_set_acl(struct inode *inode, struct posix_acl *acl, int type) { int ret = 0, size = 0; const char *name = NULL; char *value = NULL; struct iattr newattrs; umode_t new_mode = inode->i_mode, old_mode = inode->i_mode; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { ret = posix_acl_update_mode(inode, &new_mode, &acl); if (ret) goto out; } break; case ACL_TYPE_DEFAULT: if (!S_ISDIR(inode->i_mode)) { ret = acl ? -EINVAL : 0; goto out; } name = XATTR_NAME_POSIX_ACL_DEFAULT; break; default: ret = -EINVAL; goto out; } if (acl) { size = posix_acl_xattr_size(acl->a_count); value = kmalloc(size, GFP_NOFS); if (!value) { ret = -ENOMEM; goto out; } ret = posix_acl_to_xattr(&init_user_ns, acl, value, size); if (ret < 0) goto out_free; } if (new_mode != old_mode) { newattrs.ia_mode = new_mode; newattrs.ia_valid = ATTR_MODE; ret = __ceph_setattr(inode, &newattrs); if (ret) goto out_free; } ret = __ceph_setxattr(inode, name, value, size, 0); if (ret) { if (new_mode != old_mode) { newattrs.ia_mode = old_mode; newattrs.ia_valid = ATTR_MODE; __ceph_setattr(inode, &newattrs); } goto out_free; } ceph_set_cached_acl(inode, type, acl); out_free: kfree(value); out: return ret; }
166,968
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IDNSpoofChecker::Check(base::StringPiece16 label) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII || (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string))) return true; if (non_ascii_latin_letters_.containsSome(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]" "[\\u30ce\\u30f3\\u30bd\\u30be]" "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|" "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|" "\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|" "^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|" "^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|" "[a-z]\\u30fb|\\u30fb[a-z]|" "^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|" "[a-z][\\u0585\\u0581]+[a-z]|" "^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|" "[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Commit Message: Block domain labels made of Cyrillic letters that look alike Latin Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф. BUG=683314 TEST=components_unittests --gtest_filter=U*IDN* Review-Url: https://codereview.chromium.org/2683793010 Cr-Commit-Position: refs/heads/master@{#459226} CWE ID: CWE-20
bool IDNSpoofChecker::Check(base::StringPiece16 label) { bool IDNSpoofChecker::Check(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; // extra check unless it contains Kana letter exceptions or it's made entirely // of Cyrillic letters that look like Latin letters. Note that the following // combinations of scripts are treated as a 'logical' single script. result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string)) { // Check Cyrillic confusable only for ASCII TLDs. return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]" "[\\u30ce\\u30f3\\u30bd\\u30be]" "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|" "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|" "\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|" "^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|" "^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|" "[a-z]\\u30fb|\\u30fb[a-z]|" "^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|" "[a-z][\\u0585\\u0581]+[a-z]|" "^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|" "[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); }
172,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc, uint32_t prefix, int length) { if (!bitstream_read_bit(bc)) { // Leaf if(hc->current >= 256){ av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n"); return AVERROR_INVALIDDATA; } if(length){ hc->bits[hc->current] = prefix; hc->lengths[hc->current] = length; } else { hc->bits[hc->current] = 0; hc->lengths[hc->current] = 0; } hc->values[hc->current] = bitstream_read(bc, 8); hc->current++; if(hc->maxlength < length) hc->maxlength = length; return 0; } else { //Node int r; length++; r = smacker_decode_tree(bc, hc, prefix, length); if(r) return r; return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length); } } Commit Message: smacker: add sanity check for length in smacker_decode_tree() Signed-off-by: Michael Niedermayer <[email protected]> Bug-Id: 1098 Cc: [email protected] Signed-off-by: Sean McGovern <[email protected]> CWE ID: CWE-119
static int smacker_decode_tree(BitstreamContext *bc, HuffContext *hc, uint32_t prefix, int length) { if (length > SMKTREE_DECODE_MAX_RECURSION) { av_log(NULL, AV_LOG_ERROR, "Maximum tree recursion level exceeded.\n"); return AVERROR_INVALIDDATA; } if (!bitstream_read_bit(bc)) { // Leaf if(hc->current >= 256){ av_log(NULL, AV_LOG_ERROR, "Tree size exceeded!\n"); return AVERROR_INVALIDDATA; } if(length){ hc->bits[hc->current] = prefix; hc->lengths[hc->current] = length; } else { hc->bits[hc->current] = 0; hc->lengths[hc->current] = 0; } hc->values[hc->current] = bitstream_read(bc, 8); hc->current++; if(hc->maxlength < length) hc->maxlength = length; return 0; } else { //Node int r; length++; r = smacker_decode_tree(bc, hc, prefix, length); if(r) return r; return smacker_decode_tree(bc, hc, prefix | (1 << (length - 1)), length); } }
167,671
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h) { uint32_t *buf32; uint32_t pix32; int shift[3]; int *prev; int here[3], upper[3], left[3], upperleft[3]; int prediction; int x, y, c; buf32 = (uint32_t *)buf; memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int)); if ((vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) == (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG)) { shift[0] = vs->clientds.pf.rshift; shift[1] = vs->clientds.pf.gshift; shift[2] = vs->clientds.pf.bshift; } else { shift[0] = 24 - vs->clientds.pf.rshift; shift[1] = 24 - vs->clientds.pf.gshift; shift[2] = 24 - vs->clientds.pf.bshift; } for (y = 0; y < h; y++) { for (c = 0; c < 3; c++) { upper[c] = 0; here[c] = 0; } prev = (int *)vs->tight.gradient.buffer; for (x = 0; x < w; x++) { pix32 = *buf32++; for (c = 0; c < 3; c++) { upperleft[c] = upper[c]; left[c] = here[c]; upper[c] = *prev; here[c] = (int)(pix32 >> shift[c] & 0xFF); *prev++ = here[c]; prediction = left[c] + upper[c] - upperleft[c]; if (prediction < 0) { prediction = 0; } else if (prediction > 0xFF) { prediction = 0xFF; } *buf++ = (char)(here[c] - prediction); } } } } Commit Message: CWE ID: CWE-125
tight_filter_gradient24(VncState *vs, uint8_t *buf, int w, int h) { uint32_t *buf32; uint32_t pix32; int shift[3]; int *prev; int here[3], upper[3], left[3], upperleft[3]; int prediction; int x, y, c; buf32 = (uint32_t *)buf; memset(vs->tight.gradient.buffer, 0, w * 3 * sizeof(int)); if (1 /* FIXME: (vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG) == (vs->ds->surface->flags & QEMU_BIG_ENDIAN_FLAG) */) { shift[0] = vs->client_pf.rshift; shift[1] = vs->client_pf.gshift; shift[2] = vs->client_pf.bshift; } else { shift[0] = 24 - vs->client_pf.rshift; shift[1] = 24 - vs->client_pf.gshift; shift[2] = 24 - vs->client_pf.bshift; } for (y = 0; y < h; y++) { for (c = 0; c < 3; c++) { upper[c] = 0; here[c] = 0; } prev = (int *)vs->tight.gradient.buffer; for (x = 0; x < w; x++) { pix32 = *buf32++; for (c = 0; c < 3; c++) { upperleft[c] = upper[c]; left[c] = here[c]; upper[c] = *prev; here[c] = (int)(pix32 >> shift[c] & 0xFF); *prev++ = here[c]; prediction = left[c] + upper[c] - upperleft[c]; if (prediction < 0) { prediction = 0; } else if (prediction > 0xFF) { prediction = 0xFF; } *buf++ = (char)(here[c] - prediction); } } } }
165,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, PluginFinder* plugin_finder, ChromeViewHostMsg_GetPluginInfo_Status* status, std::string* group_identifier, string16* group_name) const { PluginInstaller* installer = plugin_finder->GetPluginInstaller(plugin); *group_name = installer->name(); *group_identifier = installer->identifier(); ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; GetPluginContentSetting(plugin, params.top_origin_url, params.url, *group_identifier, &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); #if defined(ENABLE_PLUGIN_INSTALLATION) PluginInstaller::SecurityStatus plugin_status = installer->GetSecurityStatus(plugin); if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } if ((plugin_status == PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION || PluginService::GetInstance()->IsPluginUnstable(plugin.path)) && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } #endif if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; } Commit Message: Handle crashing Pepper plug-ins the same as crashing NPAPI plug-ins. BUG=151895 Review URL: https://chromiumcodereview.appspot.com/10956065 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158364 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void PluginInfoMessageFilter::Context::DecidePluginStatus( const GetPluginInfo_Params& params, const WebPluginInfo& plugin, PluginFinder* plugin_finder, ChromeViewHostMsg_GetPluginInfo_Status* status, std::string* group_identifier, string16* group_name) const { PluginInstaller* installer = plugin_finder->GetPluginInstaller(plugin); *group_name = installer->name(); *group_identifier = installer->identifier(); ContentSetting plugin_setting = CONTENT_SETTING_DEFAULT; bool uses_default_content_setting = true; GetPluginContentSetting(plugin, params.top_origin_url, params.url, *group_identifier, &plugin_setting, &uses_default_content_setting); DCHECK(plugin_setting != CONTENT_SETTING_DEFAULT); #if defined(ENABLE_PLUGIN_INSTALLATION) PluginInstaller::SecurityStatus plugin_status = installer->GetSecurityStatus(plugin); if (plugin_status == PluginInstaller::SECURITY_STATUS_OUT_OF_DATE && !allow_outdated_plugins_.GetValue()) { if (allow_outdated_plugins_.IsManaged()) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedDisallowed; } else { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kOutdatedBlocked; } return; } if (plugin_status == PluginInstaller::SECURITY_STATUS_REQUIRES_AUTHORIZATION && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_IN_PROCESS && plugin.type != WebPluginInfo::PLUGIN_TYPE_PEPPER_OUT_OF_PROCESS && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } // Check if the plug-in is crashing too much. if (PluginService::GetInstance()->IsPluginUnstable(plugin.path) && !always_authorize_plugins_.GetValue() && plugin_setting != CONTENT_SETTING_BLOCK && uses_default_content_setting) { status->value = ChromeViewHostMsg_GetPluginInfo_Status::kUnauthorized; return; } #endif if (plugin_setting == CONTENT_SETTING_ASK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kClickToPlay; else if (plugin_setting == CONTENT_SETTING_BLOCK) status->value = ChromeViewHostMsg_GetPluginInfo_Status::kBlocked; }
170,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files, rpmpsm psm, int nodigest, int *setmeta, int * firsthardlink) { int rc = 0; int numHardlinks = rpmfiFNlink(fi); if (numHardlinks > 1) { /* Create first hardlinked file empty */ if (*firsthardlink < 0) { *firsthardlink = rpmfiFX(fi); rc = expandRegular(fi, dest, psm, nodigest, 1); } else { /* Create hard links for others */ char *fn = rpmfilesFN(files, *firsthardlink); rc = link(fn, dest); if (rc < 0) { rc = RPMERR_LINK_FAILED; } free(fn); } } /* Write normal files or fill the last hardlinked (already existing) file with content */ if (numHardlinks<=1) { if (!rc) rc = expandRegular(fi, dest, psm, nodigest, 0); } else if (rpmfiArchiveHasContent(fi)) { if (!rc) rc = expandRegular(fi, dest, psm, nodigest, 0); *firsthardlink = -1; } else { *setmeta = 0; } return rc; } Commit Message: Don't follow symlinks on file creation (CVE-2017-7501) Open newly created files with O_EXCL to prevent symlink tricks. When reopening hardlinks for writing the actual content, use append mode instead. This is compatible with the write-only permissions but is not destructive in case we got redirected to somebody elses file, verify the target before actually writing anything. As these are files with the temporary suffix, errors mean a local user with sufficient privileges to break the installation of the package anyway is trying to goof us on purpose, don't bother trying to mend it (we couldn't fix the hardlink case anyhow) but just bail out. Based on a patch by Florian Festi. CWE ID: CWE-59
static int fsmMkfile(rpmfi fi, const char *dest, rpmfiles files, rpmpsm psm, int nodigest, int *setmeta, int * firsthardlink) { int rc = 0; int numHardlinks = rpmfiFNlink(fi); if (numHardlinks > 1) { /* Create first hardlinked file empty */ if (*firsthardlink < 0) { *firsthardlink = rpmfiFX(fi); rc = expandRegular(fi, dest, psm, 1, nodigest, 1); } else { /* Create hard links for others */ char *fn = rpmfilesFN(files, *firsthardlink); rc = link(fn, dest); if (rc < 0) { rc = RPMERR_LINK_FAILED; } free(fn); } } /* Write normal files or fill the last hardlinked (already existing) file with content */ if (numHardlinks<=1) { if (!rc) rc = expandRegular(fi, dest, psm, 1, nodigest, 0); } else if (rpmfiArchiveHasContent(fi)) { if (!rc) rc = expandRegular(fi, dest, psm, 0, nodigest, 0); *firsthardlink = -1; } else { *setmeta = 0; } return rc; }
168,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ScriptValue ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus) { String sourceURL = sourceCode.url(); const String* savedSourceURL = m_sourceURL; m_sourceURL = &sourceURL; v8::HandleScope handleScope; v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame); if (v8Context.IsEmpty()) return ScriptValue(); v8::Context::Scope scope(v8Context); RefPtr<Frame> protect(m_frame); v8::Local<v8::Value> object = compileAndRunScript(sourceCode, corsStatus); m_sourceURL = savedSourceURL; if (object.IsEmpty()) return ScriptValue(); return ScriptValue(object); } Commit Message: Call didAccessInitialDocument when javascript: URLs are used. BUG=265221 TEST=See bug for repro. Review URL: https://chromiumcodereview.appspot.com/22572004 git-svn-id: svn://svn.chromium.org/blink/trunk@155790 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
ScriptValue ScriptController::executeScriptInMainWorld(const ScriptSourceCode& sourceCode, AccessControlStatus corsStatus) { String sourceURL = sourceCode.url(); const String* savedSourceURL = m_sourceURL; m_sourceURL = &sourceURL; v8::HandleScope handleScope; v8::Handle<v8::Context> v8Context = ScriptController::mainWorldContext(m_frame); if (v8Context.IsEmpty()) return ScriptValue(); RefPtr<Frame> protect(m_frame); if (m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument()) m_frame->loader()->didAccessInitialDocument(); v8::Context::Scope scope(v8Context); v8::Local<v8::Value> object = compileAndRunScript(sourceCode, corsStatus); m_sourceURL = savedSourceURL; if (object.IsEmpty()) return ScriptValue(); return ScriptValue(object); }
171,179
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_Parse( const char *value ) { cJSON *c; ep = 0; if ( ! ( c = cJSON_New_Item() ) ) return 0; /* memory fail */ if ( ! parse_value( c, skip( value ) ) ) { cJSON_Delete( c ); return 0; } return c; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_Parse( const char *value ) cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated) { const char *end=0,**ep=return_parse_end?return_parse_end:&global_ep; cJSON *c=cJSON_New_Item(); *ep=0; if (!c) return 0; /* memory fail */ end=parse_value(c,skip(value),ep); if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */ /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);*ep=end;return 0;}} if (return_parse_end) *return_parse_end=end; return c; }
167,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ShellSurface::OnSurfaceCommit() { surface_->CheckIfSurfaceHierarchyNeedsCommitToNewSurfaces(); surface_->CommitSurfaceHierarchy(); if (enabled() && !widget_) CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL); origin_ += pending_origin_offset_; pending_origin_offset_ = gfx::Vector2d(); resize_component_ = pending_resize_component_; if (widget_) { geometry_ = pending_geometry_; UpdateWidgetBounds(); gfx::Point surface_origin = GetSurfaceOrigin(); gfx::Rect hit_test_bounds = surface_->GetHitTestBounds() + surface_origin.OffsetFromOrigin(); bool activatable = activatable_ && !hit_test_bounds.IsEmpty(); if (activatable != CanActivate()) { set_can_activate(activatable); aura::client::ActivationClient* activation_client = ash::Shell::GetInstance()->activation_client(); if (activatable) activation_client->ActivateWindow(widget_->GetNativeWindow()); else if (widget_->IsActive()) activation_client->DeactivateWindow(widget_->GetNativeWindow()); } surface_->window()->SetBounds( gfx::Rect(surface_origin, surface_->window()->layer()->size())); if (pending_scale_ != scale_) { gfx::Transform transform; DCHECK_NE(pending_scale_, 0.0); transform.Scale(1.0 / pending_scale_, 1.0 / pending_scale_); surface_->window()->SetTransform(transform); scale_ = pending_scale_; } if (pending_show_widget_) { DCHECK(!widget_->IsClosed()); DCHECK(!widget_->IsVisible()); pending_show_widget_ = false; widget_->Show(); } } } Commit Message: exo: Reduce side-effects of dynamic activation code. This code exists for clients that need to managed their own system modal dialogs. Since the addition of the remote surface API we can limit the impact of this to surfaces created for system modal container. BUG=29528396 Review-Url: https://codereview.chromium.org/2084023003 Cr-Commit-Position: refs/heads/master@{#401115} CWE ID: CWE-416
void ShellSurface::OnSurfaceCommit() { surface_->CheckIfSurfaceHierarchyNeedsCommitToNewSurfaces(); surface_->CommitSurfaceHierarchy(); if (enabled() && !widget_) CreateShellSurfaceWidget(ui::SHOW_STATE_NORMAL); origin_ += pending_origin_offset_; pending_origin_offset_ = gfx::Vector2d(); resize_component_ = pending_resize_component_; if (widget_) { geometry_ = pending_geometry_; UpdateWidgetBounds(); gfx::Point surface_origin = GetSurfaceOrigin(); // System modal container is used by clients to implement client side // managed system modal dialogs using a single ShellSurface instance. // Hit-test region will be non-empty when at least one dialog exists on // the client side. Here we detect the transition between no client side // dialog and at least one dialog so activatable state is properly // updated. if (container_ == ash::kShellWindowId_SystemModalContainer) { gfx::Rect hit_test_bounds = surface_->GetHitTestBounds() + surface_origin.OffsetFromOrigin(); // Prevent window from being activated when hit test bounds are empty. bool activatable = activatable_ && !hit_test_bounds.IsEmpty(); if (activatable != CanActivate()) { set_can_activate(activatable); // Activate or deactivate window if activation state changed. aura::client::ActivationClient* activation_client = ash::Shell::GetInstance()->activation_client(); if (activatable) activation_client->ActivateWindow(widget_->GetNativeWindow()); else if (widget_->IsActive()) activation_client->DeactivateWindow(widget_->GetNativeWindow()); } } surface_->window()->SetBounds( gfx::Rect(surface_origin, surface_->window()->layer()->size())); if (pending_scale_ != scale_) { gfx::Transform transform; DCHECK_NE(pending_scale_, 0.0); transform.Scale(1.0 / pending_scale_, 1.0 / pending_scale_); surface_->window()->SetTransform(transform); scale_ = pending_scale_; } if (pending_show_widget_) { DCHECK(!widget_->IsClosed()); DCHECK(!widget_->IsVisible()); pending_show_widget_ = false; widget_->Show(); } } }
171,639
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long AudioTrack::GetBitDepth() const { return m_bitDepth; } 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 AudioTrack::GetBitDepth() const
174,283
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool NavigationRateLimiter::CanProceed() { if (!enabled) return true; static constexpr int kStateUpdateLimit = 200; static constexpr base::TimeDelta kStateUpdateLimitResetInterval = base::TimeDelta::FromSeconds(10); if (++count_ <= kStateUpdateLimit) return true; const base::TimeTicks now = base::TimeTicks::Now(); if (now - time_first_count_ > kStateUpdateLimitResetInterval) { time_first_count_ = now; count_ = 1; error_message_sent_ = false; return true; } if (!error_message_sent_) { error_message_sent_ = true; if (auto* local_frame = DynamicTo<LocalFrame>(frame_.Get())) { local_frame->Console().AddMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kWarning, "Throttling navigation to prevent the browser from hanging. See " "https://crbug.com/882238. Command line switch " "--disable-ipc-flooding-protection can be used to bypass the " "protection")); } } return false; } Commit Message: Convert FrameHostMsg_DidAddMessageToConsole to Mojo. Note: Since this required changing the test RenderViewImplTest.DispatchBeforeUnloadCanDetachFrame, I manually re-introduced https://crbug.com/666714 locally (the bug the test was added for), and reran the test to confirm that it still covers the bug. Bug: 786836 Change-Id: I110668fa6f0f261fd2ac36bb91a8d8b31c99f4f1 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1526270 Commit-Queue: Lowell Manners <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Camille Lamy <[email protected]> Cr-Commit-Position: refs/heads/master@{#653137} CWE ID: CWE-416
bool NavigationRateLimiter::CanProceed() { if (!enabled) return true; static constexpr int kStateUpdateLimit = 200; static constexpr base::TimeDelta kStateUpdateLimitResetInterval = base::TimeDelta::FromSeconds(10); if (++count_ <= kStateUpdateLimit) return true; const base::TimeTicks now = base::TimeTicks::Now(); if (now - time_first_count_ > kStateUpdateLimitResetInterval) { time_first_count_ = now; count_ = 1; error_message_sent_ = false; return true; } // the browser process with the DidAddMessageToConsole Mojo call. if (!error_message_sent_) { error_message_sent_ = true; if (auto* local_frame = DynamicTo<LocalFrame>(frame_.Get())) { local_frame->Console().AddMessage(ConsoleMessage::Create( mojom::ConsoleMessageSource::kJavaScript, mojom::ConsoleMessageLevel::kWarning, "Throttling navigation to prevent the browser from hanging. See " "https://crbug.com/882238. Command line switch " "--disable-ipc-flooding-protection can be used to bypass the " "protection")); } } return false; }
172,491
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); } Commit Message: Add bounds validation to AsyncPixelTransfersCompletedQuery::End BUG=351852 [email protected], [email protected] Review URL: https://codereview.chromium.org/198253002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@256723 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); uint32 end = mem_params.shm_data_offset + mem_params.shm_data_size; if (end > mem_params.shm_size || end < mem_params.shm_data_offset) return false; observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); }
171,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int clie_5_attach(struct usb_serial *serial) { struct usb_serial_port *port; unsigned int pipe; int j; /* TH55 registers 2 ports. Communication in from the UX50/TH55 uses bulk_in_endpointAddress from port 0. Communication out to the UX50/TH55 uses bulk_out_endpointAddress from port 1 Lets do a quick and dirty mapping */ /* some sanity check */ if (serial->num_ports < 2) return -1; /* port 0 now uses the modified endpoint Address */ port = serial->port[0]; port->bulk_out_endpointAddress = serial->port[1]->bulk_out_endpointAddress; pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress); for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j) port->write_urbs[j]->pipe = pipe; return 0; } Commit Message: USB: serial: visor: fix crash on detecting device without write_urbs The visor driver crashes in clie_5_attach() when a specially crafted USB device without bulk-out endpoint is detected. This fix adds a check that the device has proper configuration expected by the driver. Reported-by: Ralf Spenneberg <[email protected]> Signed-off-by: Vladis Dronov <[email protected]> Fixes: cfb8da8f69b8 ("USB: visor: fix initialisation of UX50/TH55 devices") Cc: stable <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID:
static int clie_5_attach(struct usb_serial *serial) { struct usb_serial_port *port; unsigned int pipe; int j; /* TH55 registers 2 ports. Communication in from the UX50/TH55 uses bulk_in_endpointAddress from port 0. Communication out to the UX50/TH55 uses bulk_out_endpointAddress from port 1 Lets do a quick and dirty mapping */ /* some sanity check */ if (serial->num_bulk_out < 2) { dev_err(&serial->interface->dev, "missing bulk out endpoints\n"); return -ENODEV; } /* port 0 now uses the modified endpoint Address */ port = serial->port[0]; port->bulk_out_endpointAddress = serial->port[1]->bulk_out_endpointAddress; pipe = usb_sndbulkpipe(serial->dev, port->bulk_out_endpointAddress); for (j = 0; j < ARRAY_SIZE(port->write_urbs); ++j) port->write_urbs[j]->pipe = pipe; return 0; }
167,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int rose_parse_facilities(unsigned char *p, struct rose_facilities_struct *facilities) { int facilities_len, len; facilities_len = *p++; if (facilities_len == 0) return 0; while (facilities_len > 0) { if (*p == 0x00) { facilities_len--; p++; switch (*p) { case FAC_NATIONAL: /* National */ len = rose_parse_national(p + 1, facilities, facilities_len - 1); facilities_len -= len + 1; p += len + 1; break; case FAC_CCITT: /* CCITT */ len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1); facilities_len -= len + 1; p += len + 1; break; default: printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p); facilities_len--; p++; break; } } else break; /* Error in facilities format */ } return 1; } Commit Message: ROSE: prevent heap corruption with bad facilities When parsing the FAC_NATIONAL_DIGIS facilities field, it's possible for a remote host to provide more digipeaters than expected, resulting in heap corruption. Check against ROSE_MAX_DIGIS to prevent overflows, and abort facilities parsing on failure. Additionally, when parsing the FAC_CCITT_DEST_NSAP and FAC_CCITT_SRC_NSAP facilities fields, a remote host can provide a length of less than 10, resulting in an underflow in a memcpy size, causing a kernel panic due to massive heap corruption. A length of greater than 20 results in a stack overflow of the callsign array. Abort facilities parsing on these invalid length values. Signed-off-by: Dan Rosenberg <[email protected]> Cc: [email protected] Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
int rose_parse_facilities(unsigned char *p, struct rose_facilities_struct *facilities) { int facilities_len, len; facilities_len = *p++; if (facilities_len == 0) return 0; while (facilities_len > 0) { if (*p == 0x00) { facilities_len--; p++; switch (*p) { case FAC_NATIONAL: /* National */ len = rose_parse_national(p + 1, facilities, facilities_len - 1); if (len < 0) return 0; facilities_len -= len + 1; p += len + 1; break; case FAC_CCITT: /* CCITT */ len = rose_parse_ccitt(p + 1, facilities, facilities_len - 1); if (len < 0) return 0; facilities_len -= len + 1; p += len + 1; break; default: printk(KERN_DEBUG "ROSE: rose_parse_facilities - unknown facilities family %02X\n", *p); facilities_len--; p++; break; } } else break; /* Error in facilities format */ } return 1; }
165,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zlib_run(struct zlib *zlib) /* Like zlib_advance but also handles a stream of IDAT chunks. */ { /* The 'extra_bytes' field is set by zlib_advance if there is extra * compressed data in the chunk it handles (if it sees Z_STREAM_END before * all the input data has been used.) This function uses the value to update * the correct chunk length, so the problem should only ever be detected once * for each chunk. zlib_advance outputs the error message, though see the * IDAT specific check below. */ zlib->extra_bytes = 0; if (zlib->idat != NULL) { struct IDAT_list *list = zlib->idat->idat_list_head; struct IDAT_list *last = zlib->idat->idat_list_tail; int skip = 0; /* 'rewrite_offset' is the offset of the LZ data within the chunk, for * IDAT it should be 0: */ assert(zlib->rewrite_offset == 0); /* Process each IDAT_list in turn; the caller has left the stream * positioned at the start of the first IDAT chunk data. */ for (;;) { const unsigned int count = list->count; unsigned int i; for (i = 0; i<count; ++i) { int rc; if (skip > 0) /* Skip CRC and next IDAT header */ skip_12(zlib->file); skip = 12; /* for the next time */ rc = zlib_advance(zlib, list->lengths[i]); switch (rc) { case ZLIB_OK: /* keep going */ break; case ZLIB_STREAM_END: /* stop */ /* There may be extra chunks; if there are and one of them is * not zero length output the 'extra data' message. Only do * this check if errors are being output. */ if (zlib->global->errors && zlib->extra_bytes == 0) { struct IDAT_list *check = list; int j = i+1, jcount = count; for (;;) { for (; j<jcount; ++j) if (check->lengths[j] > 0) { chunk_message(zlib->chunk, "extra compressed data"); goto end_check; } if (check == last) break; check = check->next; jcount = check->count; j = 0; } } end_check: /* Terminate the list at the current position, reducing the * length of the last IDAT too if required. */ list->lengths[i] -= zlib->extra_bytes; list->count = i+1; zlib->idat->idat_list_tail = list; /* FALL THROUGH */ default: return rc; } } /* At the end of the compressed data and Z_STREAM_END was not seen. */ if (list == last) return ZLIB_OK; list = list->next; } } else { struct chunk *chunk = zlib->chunk; int rc; assert(zlib->rewrite_offset < chunk->chunk_length); rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset); /* The extra bytes in the chunk are handled now by adjusting the chunk * length to exclude them; the zlib data is always stored at the end of * the PNG chunk (although clearly this is not necessary.) zlib_advance * has already output a warning message. */ chunk->chunk_length -= zlib->extra_bytes; return rc; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
zlib_run(struct zlib *zlib) /* Like zlib_advance but also handles a stream of IDAT chunks. */ { /* The 'extra_bytes' field is set by zlib_advance if there is extra * compressed data in the chunk it handles (if it sees Z_STREAM_END before * all the input data has been used.) This function uses the value to update * the correct chunk length, so the problem should only ever be detected once * for each chunk. zlib_advance outputs the error message, though see the * IDAT specific check below. */ zlib->extra_bytes = 0; if (zlib->idat != NULL) { struct IDAT_list *list = zlib->idat->idat_list_head; struct IDAT_list *last = zlib->idat->idat_list_tail; int skip = 0; /* 'rewrite_offset' is the offset of the LZ data within the chunk, for * IDAT it should be 0: */ assert(zlib->rewrite_offset == 0); /* Process each IDAT_list in turn; the caller has left the stream * positioned at the start of the first IDAT chunk data. */ for (;;) { const unsigned int count = list->count; unsigned int i; for (i = 0; i<count; ++i) { int rc; if (skip > 0) /* Skip CRC and next IDAT header */ skip_12(zlib->file); skip = 12; /* for the next time */ rc = zlib_advance(zlib, list->lengths[i]); switch (rc) { case ZLIB_OK: /* keep going */ break; case ZLIB_STREAM_END: /* stop */ /* There may be extra chunks; if there are and one of them is * not zero length output the 'extra data' message. Only do * this check if errors are being output. */ if (zlib->global->errors && zlib->extra_bytes == 0) { struct IDAT_list *check = list; int j = i+1, jcount = count; for (;;) { for (; j<jcount; ++j) if (check->lengths[j] > 0) { chunk_message(zlib->chunk, "extra compressed data"); goto end_check; } if (check == last) break; check = check->next; jcount = check->count; j = 0; } } end_check: /* Terminate the list at the current position, reducing the * length of the last IDAT too if required. */ list->lengths[i] -= zlib->extra_bytes; list->count = i+1; zlib->idat->idat_list_tail = list; /* FALL THROUGH */ default: return rc; } } /* At the end of the compressed data and Z_STREAM_END was not seen. */ if (list == last) return ZLIB_OK; list = list->next; } } else { struct chunk *chunk = zlib->chunk; int rc; assert(zlib->rewrite_offset < chunk->chunk_length); rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset); /* The extra bytes in the chunk are handled now by adjusting the chunk * length to exclude them; the zlib data is always stored at the end of * the PNG chunk (although clearly this is not necessary.) zlib_advance * has already output a warning message. */ chunk->chunk_length -= zlib->extra_bytes; return rc; } }
173,743
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TypingCommand::insertText(Document& document, const String& text, const VisibleSelection& selectionForInsertion, Options options, TextCompositionType compositionType, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); VisibleSelection currentSelection = frame->selection().computeVisibleSelectionInDOMTreeDeprecated(); String newText = text; if (compositionType != TextCompositionUpdate) newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion); if (compositionType == TextCompositionConfirm) { if (dispatchTextInputEvent(frame, newText) != DispatchEventResult::NotCanceled) return; } if (selectionForInsertion.isCaret() && newText.isEmpty()) return; document.updateStyleAndLayoutIgnorePendingStylesheets(); const PlainTextRange selectionOffsets = getSelectionOffsets(frame); if (selectionOffsets.isNull()) return; const size_t selectionStart = selectionOffsets.start(); if (TypingCommand* lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) { if (lastTypingCommand->endingSelection() != selectionForInsertion) { lastTypingCommand->setStartingSelection(selectionForInsertion); lastTypingCommand->setEndingVisibleSelection(selectionForInsertion); } lastTypingCommand->setCompositionType(compositionType); lastTypingCommand->setShouldRetainAutocorrectionIndicator( options & RetainAutocorrectionIndicator); lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking); lastTypingCommand->m_isIncrementalInsertion = isIncrementalInsertion; lastTypingCommand->m_selectionStart = selectionStart; EditingState editingState; EventQueueScope eventQueueScope; lastTypingCommand->insertText(newText, options & SelectInsertedText, &editingState); return; } TypingCommand* command = TypingCommand::create(document, InsertText, newText, options, compositionType); bool changeSelection = selectionForInsertion != currentSelection; if (changeSelection) { command->setStartingSelection(selectionForInsertion); command->setEndingVisibleSelection(selectionForInsertion); } command->m_isIncrementalInsertion = isIncrementalInsertion; command->m_selectionStart = selectionStart; command->apply(); if (changeSelection) { command->setEndingVisibleSelection(currentSelection); frame->selection().setSelection(currentSelection.asSelection()); } } Commit Message: Make TypingCommand::insertText() to take SelectionInDOMTree instead of VisibleSelection This patch makes |TypingCommand::insertText()| to take |SelectionInDOMTree| instead of |VisibleSelection| to reduce usage of |VisibleSelection| for improving code health. BUG=657237 TEST=n/a Review-Url: https://codereview.chromium.org/2733183002 Cr-Commit-Position: refs/heads/master@{#455368} CWE ID:
void TypingCommand::insertText(Document& document, void TypingCommand::insertText( Document& document, const String& text, const SelectionInDOMTree& passedSelectionForInsertion, Options options, TextCompositionType compositionType, const bool isIncrementalInsertion) { LocalFrame* frame = document.frame(); DCHECK(frame); VisibleSelection currentSelection = frame->selection().computeVisibleSelectionInDOMTreeDeprecated(); const VisibleSelection& selectionForInsertion = createVisibleSelection(passedSelectionForInsertion); String newText = text; if (compositionType != TextCompositionUpdate) newText = dispatchBeforeTextInsertedEvent(text, selectionForInsertion); if (compositionType == TextCompositionConfirm) { if (dispatchTextInputEvent(frame, newText) != DispatchEventResult::NotCanceled) return; } if (selectionForInsertion.isCaret() && newText.isEmpty()) return; document.updateStyleAndLayoutIgnorePendingStylesheets(); const PlainTextRange selectionOffsets = getSelectionOffsets(frame); if (selectionOffsets.isNull()) return; const size_t selectionStart = selectionOffsets.start(); if (TypingCommand* lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) { if (lastTypingCommand->endingSelection() != selectionForInsertion) { lastTypingCommand->setStartingSelection(selectionForInsertion); lastTypingCommand->setEndingVisibleSelection(selectionForInsertion); } lastTypingCommand->setCompositionType(compositionType); lastTypingCommand->setShouldRetainAutocorrectionIndicator( options & RetainAutocorrectionIndicator); lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking); lastTypingCommand->m_isIncrementalInsertion = isIncrementalInsertion; lastTypingCommand->m_selectionStart = selectionStart; EditingState editingState; EventQueueScope eventQueueScope; lastTypingCommand->insertText(newText, options & SelectInsertedText, &editingState); return; } TypingCommand* command = TypingCommand::create(document, InsertText, newText, options, compositionType); bool changeSelection = selectionForInsertion != currentSelection; if (changeSelection) { command->setStartingSelection(selectionForInsertion); command->setEndingVisibleSelection(selectionForInsertion); } command->m_isIncrementalInsertion = isIncrementalInsertion; command->m_selectionStart = selectionStart; command->apply(); if (changeSelection) { command->setEndingVisibleSelection(currentSelection); frame->selection().setSelection(currentSelection.asSelection()); } }
172,032
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); RenderViewHostTestHarness::TearDown(); } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
virtual void TearDown() { content::GetContentClient()->set_browser(old_browser_client_); content::SetContentClient(old_client_); RenderViewHostTestHarness::TearDown(); }
171,016
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; } Commit Message: Staging: sb105x: info leak in mp_get_count() The icount.reserved[] array isn't initialized so it leaks stack information to userspace. Reported-by: Nico Golde <[email protected]> Reported-by: Fabian Yamaguchi <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
static int mp_get_count(struct sb_uart_state *state, struct serial_icounter_struct *icnt) { struct serial_icounter_struct icount = {}; struct sb_uart_icount cnow; struct sb_uart_port *port = state->port; spin_lock_irq(&port->lock); memcpy(&cnow, &port->icount, sizeof(struct sb_uart_icount)); spin_unlock_irq(&port->lock); icount.cts = cnow.cts; icount.dsr = cnow.dsr; icount.rng = cnow.rng; icount.dcd = cnow.dcd; icount.rx = cnow.rx; icount.tx = cnow.tx; icount.frame = cnow.frame; icount.overrun = cnow.overrun; icount.parity = cnow.parity; icount.brk = cnow.brk; icount.buf_overrun = cnow.buf_overrun; return copy_to_user(icnt, &icount, sizeof(icount)) ? -EFAULT : 0; }
165,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { full_itxfm_ = GET_PARAM(0); partial_itxfm_ = GET_PARAM(1); tx_size_ = GET_PARAM(2); last_nonzero_ = GET_PARAM(3); } 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() { ftxfm_ = GET_PARAM(0); full_itxfm_ = GET_PARAM(1); partial_itxfm_ = GET_PARAM(2); tx_size_ = GET_PARAM(3); last_nonzero_ = GET_PARAM(4); }
174,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } } Commit Message: CWE ID: CWE-119
void _xml_startElementHandler(void *userData, const XML_Char *name, const XML_Char **attributes) { xml_parser *parser = (xml_parser *)userData; const char **attrs = (const char **) attributes; char *tag_name; char *att, *val; int val_len; zval *retval, *args[3]; if (parser) { parser->level++; tag_name = _xml_decode_tag(parser, name); if (parser->startElementHandler) { args[0] = _xml_resource_zval(parser->index); args[1] = _xml_string_zval(((char *) tag_name) + parser->toffset); MAKE_STD_ZVAL(args[2]); array_init(args[2]); while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(args[2], att, val, val_len, 0); attributes += 2; efree(att); } if ((retval = xml_call_handler(parser, parser->startElementHandler, parser->startElementPtr, 3, args))) { zval_ptr_dtor(&retval); } } if (parser->data) { if (parser->level <= XML_MAXLEVEL) { zval *tag, *atr; int atcnt = 0; MAKE_STD_ZVAL(tag); MAKE_STD_ZVAL(atr); array_init(tag); array_init(atr); _xml_add_to_info(parser,((char *) tag_name) + parser->toffset); add_assoc_string(tag,"tag",((char *) tag_name) + parser->toffset,1); /* cast to avoid gcc-warning */ add_assoc_string(tag,"type","open",1); add_assoc_long(tag,"level",parser->level); parser->ltags[parser->level-1] = estrdup(tag_name); parser->lastwasopen = 1; attributes = (const XML_Char **) attrs; while (attributes && *attributes) { att = _xml_decode_tag(parser, attributes[0]); val = xml_utf8_decode(attributes[1], strlen(attributes[1]), &val_len, parser->target_encoding); add_assoc_stringl(atr,att,val,val_len,0); atcnt++; attributes += 2; efree(att); } if (atcnt) { zend_hash_add(Z_ARRVAL_P(tag),"attributes",sizeof("attributes"),&atr,sizeof(zval*),NULL); } else { zval_ptr_dtor(&atr); } zend_hash_next_index_insert(Z_ARRVAL_P(parser->data),&tag,sizeof(zval*),(void *) &parser->ctag); } else if (parser->level == (XML_MAXLEVEL + 1)) { TSRMLS_FETCH(); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Maximum depth exceeded - Results truncated"); } } efree(tag_name); } }
165,042
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int handle_exception(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_run *kvm_run = vcpu->run; u32 intr_info, ex_no, error_code; unsigned long cr2, rip, dr6; u32 vect_info; enum emulation_result er; vect_info = vmx->idt_vectoring_info; intr_info = vmx->exit_intr_info; if (is_machine_check(intr_info)) return handle_machine_check(vcpu); if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) return 1; /* already handled by vmx_vcpu_run() */ if (is_no_device(intr_info)) { vmx_fpu_activate(vcpu); return 1; } if (is_invalid_opcode(intr_info)) { if (is_guest_mode(vcpu)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD); if (er != EMULATE_DONE) kvm_queue_exception(vcpu, UD_VECTOR); return 1; } error_code = 0; if (intr_info & INTR_INFO_DELIVER_CODE_MASK) error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); /* * The #PF with PFEC.RSVD = 1 indicates the guest is accessing * MMIO, it is better to report an internal error. * See the comments in vmx_handle_exit. */ if ((vect_info & VECTORING_INFO_VALID_MASK) && !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; vcpu->run->internal.ndata = 3; vcpu->run->internal.data[0] = vect_info; vcpu->run->internal.data[1] = intr_info; vcpu->run->internal.data[2] = error_code; return 0; } if (is_page_fault(intr_info)) { /* EPT won't cause page fault directly */ BUG_ON(enable_ept); cr2 = vmcs_readl(EXIT_QUALIFICATION); trace_kvm_page_fault(cr2, error_code); if (kvm_event_needs_reinjection(vcpu)) kvm_mmu_unprotect_page_virt(vcpu, cr2); return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0); } ex_no = intr_info & INTR_INFO_VECTOR_MASK; if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) return handle_rmode_exception(vcpu, ex_no, error_code); switch (ex_no) { case AC_VECTOR: kvm_queue_exception_e(vcpu, AC_VECTOR, error_code); return 1; case DB_VECTOR: dr6 = vmcs_readl(EXIT_QUALIFICATION); if (!(vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { vcpu->arch.dr6 &= ~15; vcpu->arch.dr6 |= dr6 | DR6_RTM; if (!(dr6 & ~DR6_RESERVED)) /* icebp */ skip_emulated_instruction(vcpu); kvm_queue_exception(vcpu, DB_VECTOR); return 1; } kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1; kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); /* fall through */ case BP_VECTOR: /* * Update instruction length as we may reinject #BP from * user space while in guest debugging mode. Reading it for * #DB as well causes no harm, it is not used in that case. */ vmx->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_run->exit_reason = KVM_EXIT_DEBUG; rip = kvm_rip_read(vcpu); kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip; kvm_run->debug.arch.exception = ex_no; break; default: kvm_run->exit_reason = KVM_EXIT_EXCEPTION; kvm_run->ex.exception = ex_no; kvm_run->ex.error_code = error_code; break; } return 0; } Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF) When L2 exits to L0 due to "exception or NMI", software exceptions (#BP and #OF) for which L1 has requested an intercept should be handled by L1 rather than L0. Previously, only hardware exceptions were forwarded to L1. Signed-off-by: Jim Mattson <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-388
static int handle_exception(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_run *kvm_run = vcpu->run; u32 intr_info, ex_no, error_code; unsigned long cr2, rip, dr6; u32 vect_info; enum emulation_result er; vect_info = vmx->idt_vectoring_info; intr_info = vmx->exit_intr_info; if (is_machine_check(intr_info)) return handle_machine_check(vcpu); if (is_nmi(intr_info)) return 1; /* already handled by vmx_vcpu_run() */ if (is_no_device(intr_info)) { vmx_fpu_activate(vcpu); return 1; } if (is_invalid_opcode(intr_info)) { if (is_guest_mode(vcpu)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD); if (er != EMULATE_DONE) kvm_queue_exception(vcpu, UD_VECTOR); return 1; } error_code = 0; if (intr_info & INTR_INFO_DELIVER_CODE_MASK) error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); /* * The #PF with PFEC.RSVD = 1 indicates the guest is accessing * MMIO, it is better to report an internal error. * See the comments in vmx_handle_exit. */ if ((vect_info & VECTORING_INFO_VALID_MASK) && !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; vcpu->run->internal.ndata = 3; vcpu->run->internal.data[0] = vect_info; vcpu->run->internal.data[1] = intr_info; vcpu->run->internal.data[2] = error_code; return 0; } if (is_page_fault(intr_info)) { /* EPT won't cause page fault directly */ BUG_ON(enable_ept); cr2 = vmcs_readl(EXIT_QUALIFICATION); trace_kvm_page_fault(cr2, error_code); if (kvm_event_needs_reinjection(vcpu)) kvm_mmu_unprotect_page_virt(vcpu, cr2); return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0); } ex_no = intr_info & INTR_INFO_VECTOR_MASK; if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) return handle_rmode_exception(vcpu, ex_no, error_code); switch (ex_no) { case AC_VECTOR: kvm_queue_exception_e(vcpu, AC_VECTOR, error_code); return 1; case DB_VECTOR: dr6 = vmcs_readl(EXIT_QUALIFICATION); if (!(vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { vcpu->arch.dr6 &= ~15; vcpu->arch.dr6 |= dr6 | DR6_RTM; if (!(dr6 & ~DR6_RESERVED)) /* icebp */ skip_emulated_instruction(vcpu); kvm_queue_exception(vcpu, DB_VECTOR); return 1; } kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1; kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); /* fall through */ case BP_VECTOR: /* * Update instruction length as we may reinject #BP from * user space while in guest debugging mode. Reading it for * #DB as well causes no harm, it is not used in that case. */ vmx->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_run->exit_reason = KVM_EXIT_DEBUG; rip = kvm_rip_read(vcpu); kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip; kvm_run->debug.arch.exception = ex_no; break; default: kvm_run->exit_reason = KVM_EXIT_EXCEPTION; kvm_run->ex.exception = ex_no; kvm_run->ex.error_code = error_code; break; } return 0; }
166,854
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void dtls1_clear_queues(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; dtls1_hm_fragment_free(frag); pitem_free(item); } while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; pqueue_free(s->d1->buffered_messages); } } Commit Message: CWE ID: CWE-399
static void dtls1_clear_queues(SSL *s) { dtls1_clear_received_buffer(s); dtls1_clear_sent_buffer(s); } void dtls1_clear_received_buffer(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; dtls1_hm_fragment_free(frag); pitem_free(item); } } void dtls1_clear_sent_buffer(SSL *s) { pitem *item = NULL; hm_fragment *frag = NULL; while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) { frag = (hm_fragment *)item->data; pqueue_free(s->d1->buffered_messages); } }
165,195
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int i; f2fs_quota_off_umount(sb); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi); if (f2fs_discard_en(sbi) && !sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_writes(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); f2fs_unregister_sysfs(sbi); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif destroy_percpu_info(sbi); for (i = 0; i < NR_PAGE_TYPE; i++) kfree(sbi->write_io[i]); kfree(sbi); } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-20
static void f2fs_put_super(struct super_block *sb) { struct f2fs_sb_info *sbi = F2FS_SB(sb); int i; f2fs_quota_off_umount(sb); /* prevent remaining shrinker jobs */ mutex_lock(&sbi->umount_mutex); /* * We don't need to do checkpoint when superblock is clean. * But, the previous checkpoint was not done by umount, it needs to do * clean checkpoint again. */ if (is_sbi_flag_set(sbi, SBI_IS_DIRTY) || !is_set_ckpt_flags(sbi, CP_UMOUNT_FLAG)) { struct cp_control cpc = { .reason = CP_UMOUNT, }; write_checkpoint(sbi, &cpc); } /* be sure to wait for any on-going discard commands */ f2fs_wait_discard_bios(sbi, true); if (f2fs_discard_en(sbi) && !sbi->discard_blks) { struct cp_control cpc = { .reason = CP_UMOUNT | CP_TRIMMED, }; write_checkpoint(sbi, &cpc); } /* write_checkpoint can update stat informaion */ f2fs_destroy_stats(sbi); /* * normally superblock is clean, so we need to release this. * In addition, EIO will skip do checkpoint, we need this as well. */ release_ino_entry(sbi, true); f2fs_leave_shrinker(sbi); mutex_unlock(&sbi->umount_mutex); /* our cp_error case, we can wait for any writeback page */ f2fs_flush_merged_writes(sbi); iput(sbi->node_inode); iput(sbi->meta_inode); /* destroy f2fs internal modules */ destroy_node_manager(sbi); destroy_segment_manager(sbi); kfree(sbi->ckpt); f2fs_unregister_sysfs(sbi); sb->s_fs_info = NULL; if (sbi->s_chksum_driver) crypto_free_shash(sbi->s_chksum_driver); kfree(sbi->raw_super); destroy_device_list(sbi); mempool_destroy(sbi->write_io_dummy); #ifdef CONFIG_QUOTA for (i = 0; i < MAXQUOTAS; i++) kfree(sbi->s_qf_names[i]); #endif destroy_percpu_info(sbi); for (i = 0; i < NR_PAGE_TYPE; i++) kfree(sbi->write_io[i]); kfree(sbi); }
169,415
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftG711::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) { return OMX_ErrorUndefined; } if(pcmParams->nPortIndex == 0) { mNumChannels = pcmParams->nChannels; } mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (mIsMLaw) { if (strncmp((const char *)roleParams->cRole, "audio_decoder.g711mlaw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } else { if (strncmp((const char *)roleParams->cRole, "audio_decoder.g711alaw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftG711::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamAudioPcm: { OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams = (OMX_AUDIO_PARAM_PCMMODETYPE *)params; if (!isValidOMXParam(pcmParams)) { return OMX_ErrorBadParameter; } if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) { return OMX_ErrorUndefined; } if (pcmParams->nChannels < 1 || pcmParams->nChannels > 2) { return OMX_ErrorUndefined; } if(pcmParams->nPortIndex == 0) { mNumChannels = pcmParams->nChannels; } mSamplingRate = pcmParams->nSamplingRate; return OMX_ErrorNone; } case OMX_IndexParamStandardComponentRole: { const OMX_PARAM_COMPONENTROLETYPE *roleParams = (const OMX_PARAM_COMPONENTROLETYPE *)params; if (!isValidOMXParam(roleParams)) { return OMX_ErrorBadParameter; } if (mIsMLaw) { if (strncmp((const char *)roleParams->cRole, "audio_decoder.g711mlaw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } else { if (strncmp((const char *)roleParams->cRole, "audio_decoder.g711alaw", OMX_MAX_STRINGNAME_SIZE - 1)) { return OMX_ErrorUndefined; } } return OMX_ErrorNone; } default: return SimpleSoftOMXComponent::internalSetParameter(index, params); } }
174,206
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *parse_scheme(struct parse_state *state) { size_t mb; const char *tmp = state->ptr; do { switch (*state->ptr) { case ':': /* scheme delimiter */ state->url.scheme = &state->buffer[0]; state->buffer[state->offset++] = 0; return ++state->ptr; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': case '.': if (state->ptr == tmp) { return tmp; } /* no break */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': /* scheme part */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) { /* soft fail; parse path next */ return tmp; } state->ptr += mb - 1; } } while (++state->ptr != state->end); return state->ptr = tmp; } Commit Message: fix bug #71719 (Buffer overflow in HTTP url parsing functions) The parser's offset was not reset when we softfail in scheme parsing and continue to parse a path. Thanks to hlt99 at blinkenshell dot org for the report. CWE ID: CWE-119
static const char *parse_scheme(struct parse_state *state) { size_t mb; const char *tmp = state->ptr; do { switch (*state->ptr) { case ':': /* scheme delimiter */ state->url.scheme = &state->buffer[0]; state->buffer[state->offset++] = 0; return ++state->ptr; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '+': case '-': case '.': if (state->ptr == tmp) { goto softfail; } /* no break */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': /* scheme part */ state->buffer[state->offset++] = *state->ptr; break; default: if (!(mb = parse_mb(state, PARSE_SCHEME, state->ptr, state->end, tmp, 1))) { goto softfail; } state->ptr += mb - 1; } } while (++state->ptr != state->end); softfail: state->offset = 0; return state->ptr = tmp; }
168,833
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int send_write_chunks(struct svcxprt_rdma *xprt, struct rpcrdma_write_array *wr_ary, struct rpcrdma_msg *rdma_resp, struct svc_rqst *rqstp, struct svc_rdma_req_map *vec) { u32 xfer_len = rqstp->rq_res.page_len; int write_len; u32 xdr_off; int chunk_off; int chunk_no; int nchunks; struct rpcrdma_write_array *res_ary; int ret; res_ary = (struct rpcrdma_write_array *) &rdma_resp->rm_body.rm_chunks[1]; /* Write chunks start at the pagelist */ nchunks = be32_to_cpu(wr_ary->wc_nchunks); for (xdr_off = rqstp->rq_res.head[0].iov_len, chunk_no = 0; xfer_len && chunk_no < nchunks; chunk_no++) { struct rpcrdma_segment *arg_ch; u64 rs_offset; arg_ch = &wr_ary->wc_array[chunk_no].wc_target; write_len = min(xfer_len, be32_to_cpu(arg_ch->rs_length)); /* Prepare the response chunk given the length actually * written */ xdr_decode_hyper((__be32 *)&arg_ch->rs_offset, &rs_offset); svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no, arg_ch->rs_handle, arg_ch->rs_offset, write_len); chunk_off = 0; while (write_len) { ret = send_write(xprt, rqstp, be32_to_cpu(arg_ch->rs_handle), rs_offset + chunk_off, xdr_off, write_len, vec); if (ret <= 0) goto out_err; chunk_off += ret; xdr_off += ret; xfer_len -= ret; write_len -= ret; } } /* Update the req with the number of chunks actually used */ svc_rdma_xdr_encode_write_list(rdma_resp, chunk_no); return rqstp->rq_res.page_len; out_err: pr_err("svcrdma: failed to send write chunks, rc=%d\n", ret); return -EIO; } 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
static int send_write_chunks(struct svcxprt_rdma *xprt, /* Load the xdr_buf into the ctxt's sge array, and DMA map each * element as it is added. * * Returns the number of sge elements loaded on success, or * a negative errno on failure. */ static int svc_rdma_map_reply_msg(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, struct xdr_buf *xdr, __be32 *wr_lst) { unsigned int len, sge_no, remaining, page_off; struct page **ppages; unsigned char *base; u32 xdr_pad; int ret; sge_no = 1; ret = svc_rdma_dma_map_buf(rdma, ctxt, sge_no++, xdr->head[0].iov_base, xdr->head[0].iov_len); if (ret < 0) return ret; /* If a Write chunk is present, the xdr_buf's page list * is not included inline. However the Upper Layer may * have added XDR padding in the tail buffer, and that * should not be included inline. */ if (wr_lst) { base = xdr->tail[0].iov_base; len = xdr->tail[0].iov_len; xdr_pad = xdr_padsize(xdr->page_len); if (len && xdr_pad) { base += xdr_pad; len -= xdr_pad; } goto tail; } ppages = xdr->pages + (xdr->page_base >> PAGE_SHIFT); page_off = xdr->page_base & ~PAGE_MASK; remaining = xdr->page_len; while (remaining) { len = min_t(u32, PAGE_SIZE - page_off, remaining); ret = svc_rdma_dma_map_page(rdma, ctxt, sge_no++, *ppages++, page_off, len); if (ret < 0) return ret; remaining -= len; page_off = 0; } base = xdr->tail[0].iov_base; len = xdr->tail[0].iov_len; tail: if (len) { ret = svc_rdma_dma_map_buf(rdma, ctxt, sge_no++, base, len); if (ret < 0) return ret; } return sge_no - 1; }
168,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int hci_uart_set_proto(struct hci_uart *hu, int id) { const struct hci_uart_proto *p; int err; p = hci_uart_get_proto(id); if (!p) return -EPROTONOSUPPORT; hu->proto = p; set_bit(HCI_UART_PROTO_READY, &hu->flags); err = hci_uart_register_dev(hu); if (err) { clear_bit(HCI_UART_PROTO_READY, &hu->flags); return err; } return 0; } Commit Message: Bluetooth: hci_ldisc: Postpone HCI_UART_PROTO_READY bit set in hci_uart_set_proto() task A: task B: hci_uart_set_proto flush_to_ldisc - p->open(hu) -> h5_open //alloc h5 - receive_buf - set_bit HCI_UART_PROTO_READY - tty_port_default_receive_buf - hci_uart_register_dev - tty_ldisc_receive_buf - hci_uart_tty_receive - test_bit HCI_UART_PROTO_READY - h5_recv - clear_bit HCI_UART_PROTO_READY while() { - p->open(hu) -> h5_close //free h5 - h5_rx_3wire_hdr - h5_reset() //use-after-free } It could use ioctl to set hci uart proto, but there is a use-after-free issue when hci_uart_register_dev() fail in hci_uart_set_proto(), see stack above, fix this by setting HCI_UART_PROTO_READY bit only when hci_uart_register_dev() return success. Reported-by: [email protected] Signed-off-by: Kefeng Wang <[email protected]> Reviewed-by: Jeremy Cline <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> CWE ID: CWE-416
static int hci_uart_set_proto(struct hci_uart *hu, int id) { const struct hci_uart_proto *p; int err; p = hci_uart_get_proto(id); if (!p) return -EPROTONOSUPPORT; hu->proto = p; err = hci_uart_register_dev(hu); if (err) { return err; } set_bit(HCI_UART_PROTO_READY, &hu->flags); return 0; }
169,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = (x >> 56) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { psf->header.ptr [psf->header.indx++] = (x >> 56) ; psf->header.ptr [psf->header.indx++] = (x >> 48) ; psf->header.ptr [psf->header.indx++] = (x >> 40) ; psf->header.ptr [psf->header.indx++] = (x >> 32) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_8byte */
170,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void request_key_auth_describe(const struct key *key, struct seq_file *m) { struct request_key_auth *rka = key->payload.data[0]; seq_puts(m, "key:"); seq_puts(m, key->description); if (key_is_instantiated(key)) seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len); } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
static void request_key_auth_describe(const struct key *key, struct seq_file *m) { struct request_key_auth *rka = key->payload.data[0]; seq_puts(m, "key:"); seq_puts(m, key->description); if (key_is_positive(key)) seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len); }
167,707
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::ClearAllPreviewData() { print_preview_data_service()->RemoveEntry(preview_ui_addr_str_); } 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 PrintPreviewUI::ClearAllPreviewData() { print_preview_data_service()->RemoveEntry(id_); }
170,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int treo_attach(struct usb_serial *serial) { struct usb_serial_port *swap_port; /* Only do this endpoint hack for the Handspring devices with * interrupt in endpoints, which for now are the Treo devices. */ if (!((le16_to_cpu(serial->dev->descriptor.idVendor) == HANDSPRING_VENDOR_ID) || (le16_to_cpu(serial->dev->descriptor.idVendor) == KYOCERA_VENDOR_ID)) || (serial->num_interrupt_in == 0)) return 0; /* * It appears that Treos and Kyoceras want to use the * 1st bulk in endpoint to communicate with the 2nd bulk out endpoint, * so let's swap the 1st and 2nd bulk in and interrupt endpoints. * Note that swapping the bulk out endpoints would break lots of * apps that want to communicate on the second port. */ #define COPY_PORT(dest, src) \ do { \ int i; \ \ for (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) { \ dest->read_urbs[i] = src->read_urbs[i]; \ dest->read_urbs[i]->context = dest; \ dest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \ } \ dest->read_urb = src->read_urb; \ dest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\ dest->bulk_in_buffer = src->bulk_in_buffer; \ dest->bulk_in_size = src->bulk_in_size; \ dest->interrupt_in_urb = src->interrupt_in_urb; \ dest->interrupt_in_urb->context = dest; \ dest->interrupt_in_endpointAddress = \ src->interrupt_in_endpointAddress;\ dest->interrupt_in_buffer = src->interrupt_in_buffer; \ } while (0); swap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL); if (!swap_port) return -ENOMEM; COPY_PORT(swap_port, serial->port[0]); COPY_PORT(serial->port[0], serial->port[1]); COPY_PORT(serial->port[1], swap_port); kfree(swap_port); return 0; } Commit Message: USB: visor: fix null-deref at probe Fix null-pointer dereference at probe should a (malicious) Treo device lack the expected endpoints. Specifically, the Treo port-setup hack was dereferencing the bulk-in and interrupt-in urbs without first making sure they had been allocated by core. Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2") Cc: stable <[email protected]> Signed-off-by: Johan Hovold <[email protected]> CWE ID:
static int treo_attach(struct usb_serial *serial) { struct usb_serial_port *swap_port; /* Only do this endpoint hack for the Handspring devices with * interrupt in endpoints, which for now are the Treo devices. */ if (!((le16_to_cpu(serial->dev->descriptor.idVendor) == HANDSPRING_VENDOR_ID) || (le16_to_cpu(serial->dev->descriptor.idVendor) == KYOCERA_VENDOR_ID)) || (serial->num_interrupt_in == 0)) return 0; if (serial->num_bulk_in < 2 || serial->num_interrupt_in < 2) { dev_err(&serial->interface->dev, "missing endpoints\n"); return -ENODEV; } /* * It appears that Treos and Kyoceras want to use the * 1st bulk in endpoint to communicate with the 2nd bulk out endpoint, * so let's swap the 1st and 2nd bulk in and interrupt endpoints. * Note that swapping the bulk out endpoints would break lots of * apps that want to communicate on the second port. */ #define COPY_PORT(dest, src) \ do { \ int i; \ \ for (i = 0; i < ARRAY_SIZE(src->read_urbs); ++i) { \ dest->read_urbs[i] = src->read_urbs[i]; \ dest->read_urbs[i]->context = dest; \ dest->bulk_in_buffers[i] = src->bulk_in_buffers[i]; \ } \ dest->read_urb = src->read_urb; \ dest->bulk_in_endpointAddress = src->bulk_in_endpointAddress;\ dest->bulk_in_buffer = src->bulk_in_buffer; \ dest->bulk_in_size = src->bulk_in_size; \ dest->interrupt_in_urb = src->interrupt_in_urb; \ dest->interrupt_in_urb->context = dest; \ dest->interrupt_in_endpointAddress = \ src->interrupt_in_endpointAddress;\ dest->interrupt_in_buffer = src->interrupt_in_buffer; \ } while (0); swap_port = kmalloc(sizeof(*swap_port), GFP_KERNEL); if (!swap_port) return -ENOMEM; COPY_PORT(swap_port, serial->port[0]); COPY_PORT(serial->port[0], serial->port[1]); COPY_PORT(serial->port[1], swap_port); kfree(swap_port); return 0; }
167,390
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; } Commit Message: Fix write heap buffer overflow in opj_mqc_byteout(). Discovered by Ke Liu of Tencent's Xuanwu LAB (#835) CWE ID: CWE-119
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { /* We refer to data - 1 since below we incremented it */ opj_free(p_code_block->data - 1); } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1); if (! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; /* We reserve the initial byte as a fake byte to a non-FF value */ /* and increment the data pointer, so that opj_mqc_init_enc() */ /* can do bp = data - 1, and opj_mqc_byteout() can safely dereference */ /* it. */ p_code_block->data[0] = 0; p_code_block->data += 1; /*why +1 ?*/ } return OPJ_TRUE; }
168,458
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: destroy_one_secret (gpointer data) { char *secret = (char *) data; /* Don't leave the secret lying around in memory */ g_message ("%s: destroying %s", __func__, secret); memset (secret, 0, strlen (secret)); g_free (secret); } Commit Message: CWE ID: CWE-200
destroy_one_secret (gpointer data) { char *secret = (char *) data; /* Don't leave the secret lying around in memory */ memset (secret, 0, strlen (secret)); g_free (secret); }
164,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void 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. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutofillPopupBaseView::DoShow() { const bool initialize_widget = !GetWidget(); if (initialize_widget) { if (parent_widget_) parent_widget_->AddObserver(this); views::Widget* widget = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.delegate = this; params.parent = parent_widget_ ? parent_widget_->GetNativeView() : delegate_->container_view(); AddExtraInitParams(&params); widget->Init(params); std::unique_ptr<views::View> wrapper = CreateWrapperView(); if (wrapper) widget->SetContentsView(wrapper.release()); widget->AddObserver(this); widget->SetVisibilityAnimationTransition(views::Widget::ANIMATE_HIDE); show_time_ = base::Time::Now(); } GetWidget()->GetRootView()->SetBorder(CreateBorder()); DoUpdateBoundsAndRedrawPopup(); GetWidget()->Show(); if (initialize_widget) views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this); } 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 <[email protected]> Reviewed-by: Vasilii Sukhanov <[email protected]> Reviewed-by: Fabio Tirelo <[email protected]> Reviewed-by: Tommy Martino <[email protected]> Commit-Queue: Mathieu Perreault <[email protected]> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
void AutofillPopupBaseView::DoShow() { const bool initialize_widget = !GetWidget(); if (initialize_widget) { if (parent_widget_) parent_widget_->AddObserver(this); views::Widget* widget = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.delegate = this; params.parent = parent_widget_ ? parent_widget_->GetNativeView() : delegate_->container_view(); // Ensure the bubble border is not painted on an opaque background. params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; widget->Init(params); widget->AddObserver(this); widget->SetVisibilityAnimationTransition(views::Widget::ANIMATE_HIDE); show_time_ = base::Time::Now(); } GetWidget()->GetRootView()->SetBorder(CreateBorder()); DoUpdateBoundsAndRedrawPopup(); GetWidget()->Show(); if (initialize_widget) views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this); }
172,096
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_attr3_leaf_add_work( struct xfs_buf *bp, struct xfs_attr3_icleaf_hdr *ichdr, struct xfs_da_args *args, int mapindex) { struct xfs_attr_leafblock *leaf; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_mount *mp; int tmp; int i; trace_xfs_attr_leaf_add_work(args); leaf = bp->b_addr; ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE); ASSERT(args->index >= 0 && args->index <= ichdr->count); /* * Force open some space in the entry array and fill it in. */ entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (args->index < ichdr->count) { tmp = ichdr->count - args->index; tmp *= sizeof(xfs_attr_leaf_entry_t); memmove(entry + 1, entry, tmp); xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry))); } ichdr->count++; /* * Allocate space for the new string (at the end of the run). */ mp = args->trans->t_mountp; ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0); ASSERT(ichdr->freemap[mapindex].size >= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, NULL)); ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0); ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, &tmp); entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base + ichdr->freemap[mapindex].size); entry->hashval = cpu_to_be32(args->hashval); entry->flags = tmp ? XFS_ATTR_LOCAL : 0; entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags); if (args->op_flags & XFS_DA_OP_RENAME) { entry->flags |= XFS_ATTR_INCOMPLETE; if ((args->blkno2 == args->blkno) && (args->index2 <= args->index)) { args->index2++; } } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry))); ASSERT((args->index == 0) || (be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval))); ASSERT((args->index == ichdr->count - 1) || (be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval))); /* * For "remote" attribute values, simply note that we need to * allocate space for the "remote" value. We can't actually * allocate the extents in this transaction, and we can't decide * which blocks they should be as we might allocate more blocks * as part of this transaction (a split operation for example). */ if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); name_loc->namelen = args->namelen; name_loc->valuelen = cpu_to_be16(args->valuelen); memcpy((char *)name_loc->nameval, args->name, args->namelen); memcpy((char *)&name_loc->nameval[args->namelen], args->value, be16_to_cpu(name_loc->valuelen)); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); name_rmt->namelen = args->namelen; memcpy((char *)name_rmt->name, args->name, args->namelen); entry->flags |= XFS_ATTR_INCOMPLETE; /* just in case */ name_rmt->valuelen = 0; name_rmt->valueblk = 0; args->rmtblkno = 1; args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index), xfs_attr_leaf_entsize(leaf, args->index))); /* * Update the control info for this leaf node */ if (be16_to_cpu(entry->nameidx) < ichdr->firstused) ichdr->firstused = be16_to_cpu(entry->nameidx); ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf)); tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf); for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { if (ichdr->freemap[i].base == tmp) { ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t); ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t); } } ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index); return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19
xfs_attr3_leaf_add_work( struct xfs_buf *bp, struct xfs_attr3_icleaf_hdr *ichdr, struct xfs_da_args *args, int mapindex) { struct xfs_attr_leafblock *leaf; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; struct xfs_mount *mp; int tmp; int i; trace_xfs_attr_leaf_add_work(args); leaf = bp->b_addr; ASSERT(mapindex >= 0 && mapindex < XFS_ATTR_LEAF_MAPSIZE); ASSERT(args->index >= 0 && args->index <= ichdr->count); /* * Force open some space in the entry array and fill it in. */ entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (args->index < ichdr->count) { tmp = ichdr->count - args->index; tmp *= sizeof(xfs_attr_leaf_entry_t); memmove(entry + 1, entry, tmp); xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, tmp + sizeof(*entry))); } ichdr->count++; /* * Allocate space for the new string (at the end of the run). */ mp = args->trans->t_mountp; ASSERT(ichdr->freemap[mapindex].base < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].base & 0x3) == 0); ASSERT(ichdr->freemap[mapindex].size >= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, NULL)); ASSERT(ichdr->freemap[mapindex].size < XFS_LBSIZE(mp)); ASSERT((ichdr->freemap[mapindex].size & 0x3) == 0); ichdr->freemap[mapindex].size -= xfs_attr_leaf_newentsize(args->namelen, args->valuelen, mp->m_sb.sb_blocksize, &tmp); entry->nameidx = cpu_to_be16(ichdr->freemap[mapindex].base + ichdr->freemap[mapindex].size); entry->hashval = cpu_to_be32(args->hashval); entry->flags = tmp ? XFS_ATTR_LOCAL : 0; entry->flags |= XFS_ATTR_NSP_ARGS_TO_ONDISK(args->flags); if (args->op_flags & XFS_DA_OP_RENAME) { entry->flags |= XFS_ATTR_INCOMPLETE; if ((args->blkno2 == args->blkno) && (args->index2 <= args->index)) { args->index2++; } } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, entry, sizeof(*entry))); ASSERT((args->index == 0) || (be32_to_cpu(entry->hashval) >= be32_to_cpu((entry-1)->hashval))); ASSERT((args->index == ichdr->count - 1) || (be32_to_cpu(entry->hashval) <= be32_to_cpu((entry+1)->hashval))); /* * For "remote" attribute values, simply note that we need to * allocate space for the "remote" value. We can't actually * allocate the extents in this transaction, and we can't decide * which blocks they should be as we might allocate more blocks * as part of this transaction (a split operation for example). */ if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); name_loc->namelen = args->namelen; name_loc->valuelen = cpu_to_be16(args->valuelen); memcpy((char *)name_loc->nameval, args->name, args->namelen); memcpy((char *)&name_loc->nameval[args->namelen], args->value, be16_to_cpu(name_loc->valuelen)); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); name_rmt->namelen = args->namelen; memcpy((char *)name_rmt->name, args->name, args->namelen); entry->flags |= XFS_ATTR_INCOMPLETE; /* just in case */ name_rmt->valuelen = 0; name_rmt->valueblk = 0; args->rmtblkno = 1; args->rmtblkcnt = xfs_attr3_rmt_blocks(mp, args->valuelen); args->rmtvaluelen = args->valuelen; } xfs_trans_log_buf(args->trans, bp, XFS_DA_LOGRANGE(leaf, xfs_attr3_leaf_name(leaf, args->index), xfs_attr_leaf_entsize(leaf, args->index))); /* * Update the control info for this leaf node */ if (be16_to_cpu(entry->nameidx) < ichdr->firstused) ichdr->firstused = be16_to_cpu(entry->nameidx); ASSERT(ichdr->firstused >= ichdr->count * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf)); tmp = (ichdr->count - 1) * sizeof(xfs_attr_leaf_entry_t) + xfs_attr3_leaf_hdr_size(leaf); for (i = 0; i < XFS_ATTR_LEAF_MAPSIZE; i++) { if (ichdr->freemap[i].base == tmp) { ichdr->freemap[i].base += sizeof(xfs_attr_leaf_entry_t); ichdr->freemap[i].size -= sizeof(xfs_attr_leaf_entry_t); } } ichdr->usedbytes += xfs_attr_leaf_entsize(leaf, args->index); return 0; }
166,733
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssh_packet_set_postauth(struct ssh *ssh) { struct sshcomp *comp; int r, mode; debug("%s: called", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; for (mode = 0; mode < MODE_MAX; mode++) { if (ssh->state->newkeys[mode] == NULL) continue; comp = &ssh->state->newkeys[mode]->comp; if (comp && comp->enabled && (r = ssh_packet_init_compression(ssh)) != 0) return r; } return 0; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
ssh_packet_set_postauth(struct ssh *ssh) { int r; debug("%s: called", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0) return r; return 0; }
168,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cdef_t *cdef = &box->data.cdef; jp2_cdefchan_t *chan; unsigned int channo; if (jp2_getuint16(in, &cdef->numchans)) { return -1; } if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) { return -1; } for (channo = 0; channo < cdef->numchans; ++channo) { chan = &cdef->ents[channo]; if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) || jp2_getuint16(in, &chan->assoc)) { return -1; } } return 0; } Commit Message: Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems. CWE ID: CWE-476
static int jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cdef_t *cdef = &box->data.cdef; jp2_cdefchan_t *chan; unsigned int channo; cdef->ents = 0; if (jp2_getuint16(in, &cdef->numchans)) { return -1; } if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) { return -1; } for (channo = 0; channo < cdef->numchans; ++channo) { chan = &cdef->ents[channo]; if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) || jp2_getuint16(in, &chan->assoc)) { return -1; } } return 0; }
168,321
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __f2fs_set_acl(struct inode *inode, int type, struct posix_acl *acl, struct page *ipage) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; set_acl_inode(inode, inode->i_mode); if (error == 0) acl = NULL; } break; case ACL_TYPE_DEFAULT: name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = f2fs_acl_to_disk(acl, &size); if (IS_ERR(value)) { clear_inode_flag(inode, FI_ACL_MODE); return (int)PTR_ERR(value); } } error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); clear_inode_flag(inode, FI_ACL_MODE); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <[email protected]> Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Andreas Gruenbacher <[email protected]> CWE ID: CWE-285
static int __f2fs_set_acl(struct inode *inode, int type, struct posix_acl *acl, struct page *ipage) { int name_index; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name_index = F2FS_XATTR_INDEX_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; set_acl_inode(inode, inode->i_mode); } break; case ACL_TYPE_DEFAULT: name_index = F2FS_XATTR_INDEX_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = f2fs_acl_to_disk(acl, &size); if (IS_ERR(value)) { clear_inode_flag(inode, FI_ACL_MODE); return (int)PTR_ERR(value); } } error = f2fs_setxattr(inode, name_index, "", value, size, ipage, 0); kfree(value); if (!error) set_cached_acl(inode, type, acl); clear_inode_flag(inode, FI_ACL_MODE); return error; }
166,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; const long long seekIdId = ReadUInt(pReader, pos, len); if (seekIdId != 0x13AB) // SeekID ID return false; if ((pos + len) > stop) return false; pos += len; // consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size of field if ((pos + seekIdSize) > stop) return false; pEntry->id = ReadUInt(pReader, pos, len); // payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; // consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) // SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; // consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; // consume payload if (pos != stop) return false; return true; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
bool SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_, Entry* pEntry) { if (size_ <= 0) return false; long long pos = start; const long long stop = start + size_; long len; const long long seekIdId = ReadID(pReader, pos, len); if (seekIdId < 0) return false; if (seekIdId != 0x13AB) // SeekID ID return false; if ((pos + len) > stop) return false; pos += len; // consume SeekID id const long long seekIdSize = ReadUInt(pReader, pos, len); if (seekIdSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size of field if ((pos + seekIdSize) > stop) return false; pEntry->id = ReadUInt(pReader, pos, len); // payload if (pEntry->id <= 0) return false; if (len != seekIdSize) return false; pos += seekIdSize; // consume SeekID payload const long long seekPosId = ReadUInt(pReader, pos, len); if (seekPosId != 0x13AC) // SeekPos ID return false; if ((pos + len) > stop) return false; pos += len; // consume id const long long seekPosSize = ReadUInt(pReader, pos, len); if (seekPosSize <= 0) return false; if ((pos + len) > stop) return false; pos += len; // consume size if ((pos + seekPosSize) > stop) return false; pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); if (pEntry->pos < 0) return false; pos += seekPosSize; // consume payload if (pos != stop) return false; return true; }
173,855
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate, Handle<JSObject> receiver, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver)); Handle<SeededNumberDictionary> dictionary( SeededNumberDictionary::cast(receiver->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { int entry = dictionary->FindEntry(isolate, k); if (entry == SeededNumberDictionary::kNotFound) { continue; } PropertyDetails details = GetDetailsImpl(*dictionary, entry); switch (details.kind()) { case kData: { Object* element_k = dictionary->ValueAt(entry); if (value->StrictEquals(element_k)) { return Just<int64_t>(k); } break; } case kAccessor: { LookupIterator it(isolate, receiver, k, LookupIterator::OWN_SKIP_INTERCEPTOR); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); Handle<Object> element_k; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element_k, JSObject::GetPropertyWithAccessor(&it), Nothing<int64_t>()); if (value->StrictEquals(*element_k)) return Just<int64_t>(k); if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } if (*dictionary == receiver->elements()) continue; if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } dictionary = handle( SeededNumberDictionary::cast(receiver->elements()), isolate); break; } } } return Just<int64_t>(-1); } Commit Message: Backport: Fix Object.entries/values with changing elements Bug: 111274046 Test: m -j proxy_resolver_v8_unittest && adb sync && adb shell \ /data/nativetest64/proxy_resolver_v8_unittest/proxy_resolver_v8_unittest Change-Id: I705fc512cc5837e9364ed187559cc75d079aa5cb (cherry picked from commit d8be9a10287afed07705ac8af027d6a46d4def99) CWE ID: CWE-704
static Maybe<int64_t> IndexOfValueImpl(Isolate* isolate, Handle<JSObject> receiver, Handle<Object> value, uint32_t start_from, uint32_t length) { DCHECK(JSObject::PrototypeHasNoElements(isolate, *receiver)); Handle<Map> original_map(receiver->map(), isolate); Handle<SeededNumberDictionary> dictionary( SeededNumberDictionary::cast(receiver->elements()), isolate); for (uint32_t k = start_from; k < length; ++k) { DCHECK_EQ(receiver->map(), *original_map); int entry = dictionary->FindEntry(isolate, k); if (entry == SeededNumberDictionary::kNotFound) { continue; } PropertyDetails details = GetDetailsImpl(*dictionary, entry); switch (details.kind()) { case kData: { Object* element_k = dictionary->ValueAt(entry); if (value->StrictEquals(element_k)) { return Just<int64_t>(k); } break; } case kAccessor: { LookupIterator it(isolate, receiver, k, LookupIterator::OWN_SKIP_INTERCEPTOR); DCHECK(it.IsFound()); DCHECK_EQ(it.state(), LookupIterator::ACCESSOR); Handle<Object> element_k; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, element_k, JSObject::GetPropertyWithAccessor(&it), Nothing<int64_t>()); if (value->StrictEquals(*element_k)) return Just<int64_t>(k); if (!JSObject::PrototypeHasNoElements(isolate, *receiver)) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } if (*dictionary == receiver->elements()) continue; if (receiver->GetElementsKind() != DICTIONARY_ELEMENTS) { return IndexOfValueSlowPath(isolate, receiver, value, k + 1, length); } dictionary = handle( SeededNumberDictionary::cast(receiver->elements()), isolate); break; } } } return Just<int64_t>(-1); }
174,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool SerializeNotificationDatabaseData(const NotificationDatabaseData& input, std::string* output) { DCHECK(output); scoped_ptr<NotificationDatabaseDataProto::NotificationData> payload( new NotificationDatabaseDataProto::NotificationData()); const PlatformNotificationData& notification_data = input.notification_data; payload->set_title(base::UTF16ToUTF8(notification_data.title)); switch (notification_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT); break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT); break; case PlatformNotificationData::DIRECTION_AUTO: payload->set_direction( NotificationDatabaseDataProto::NotificationData::AUTO); break; } payload->set_lang(notification_data.lang); payload->set_body(base::UTF16ToUTF8(notification_data.body)); payload->set_tag(notification_data.tag); payload->set_icon(notification_data.icon.spec()); for (size_t i = 0; i < notification_data.vibration_pattern.size(); ++i) payload->add_vibration_pattern(notification_data.vibration_pattern[i]); payload->set_timestamp(notification_data.timestamp.ToInternalValue()); payload->set_silent(notification_data.silent); payload->set_require_interaction(notification_data.require_interaction); if (notification_data.data.size()) { payload->set_data(&notification_data.data.front(), notification_data.data.size()); } for (const PlatformNotificationAction& action : notification_data.actions) { NotificationDatabaseDataProto::NotificationAction* payload_action = payload->add_actions(); payload_action->set_action(action.action); payload_action->set_title(base::UTF16ToUTF8(action.title)); } NotificationDatabaseDataProto message; message.set_notification_id(input.notification_id); message.set_origin(input.origin.spec()); message.set_service_worker_registration_id( input.service_worker_registration_id); message.set_allocated_notification_data(payload.release()); return message.SerializeToString(output); } Commit Message: Notification actions may have an icon url. This is behind a runtime flag for two reasons: * The implementation is incomplete. * We're still evaluating the API design. Intent to Implement and Ship: Notification Action Icons https://groups.google.com/a/chromium.org/d/msg/blink-dev/IM0HxOP7HOA/y8tu6iq1CgAJ BUG=581336 Review URL: https://codereview.chromium.org/1644573002 Cr-Commit-Position: refs/heads/master@{#374649} CWE ID:
bool SerializeNotificationDatabaseData(const NotificationDatabaseData& input, std::string* output) { DCHECK(output); scoped_ptr<NotificationDatabaseDataProto::NotificationData> payload( new NotificationDatabaseDataProto::NotificationData()); const PlatformNotificationData& notification_data = input.notification_data; payload->set_title(base::UTF16ToUTF8(notification_data.title)); switch (notification_data.direction) { case PlatformNotificationData::DIRECTION_LEFT_TO_RIGHT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::LEFT_TO_RIGHT); break; case PlatformNotificationData::DIRECTION_RIGHT_TO_LEFT: payload->set_direction( NotificationDatabaseDataProto::NotificationData::RIGHT_TO_LEFT); break; case PlatformNotificationData::DIRECTION_AUTO: payload->set_direction( NotificationDatabaseDataProto::NotificationData::AUTO); break; } payload->set_lang(notification_data.lang); payload->set_body(base::UTF16ToUTF8(notification_data.body)); payload->set_tag(notification_data.tag); payload->set_icon(notification_data.icon.spec()); for (size_t i = 0; i < notification_data.vibration_pattern.size(); ++i) payload->add_vibration_pattern(notification_data.vibration_pattern[i]); payload->set_timestamp(notification_data.timestamp.ToInternalValue()); payload->set_silent(notification_data.silent); payload->set_require_interaction(notification_data.require_interaction); if (notification_data.data.size()) { payload->set_data(&notification_data.data.front(), notification_data.data.size()); } for (const PlatformNotificationAction& action : notification_data.actions) { NotificationDatabaseDataProto::NotificationAction* payload_action = payload->add_actions(); payload_action->set_action(action.action); payload_action->set_title(base::UTF16ToUTF8(action.title)); payload_action->set_icon(action.icon.spec()); } NotificationDatabaseDataProto message; message.set_notification_id(input.notification_id); message.set_origin(input.origin.spec()); message.set_service_worker_registration_id( input.service_worker_registration_id); message.set_allocated_notification_data(payload.release()); return message.SerializeToString(output); }
171,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: tChecksumCheckResult ParaNdis_CheckRxChecksum( PARANDIS_ADAPTER *pContext, ULONG virtioFlags, tCompletePhysicalAddress *pPacketPages, ULONG ulPacketLength, ULONG ulDataOffset) { tOffloadSettingsFlags f = pContext->Offload.flags; tChecksumCheckResult res; tTcpIpPacketParsingResult ppr; ULONG flagsToCalculate = 0; res.value = 0; if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) { if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; } else { if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; } } ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete) { res.flags.IpOK = FALSE; res.flags.IpFailed = TRUE; return res; } if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) { pContext->extraStatistics.framesRxCSHwOK++; ppr.xxpCheckSum = ppresCSOK; } if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) { if (f.fRxIPChecksum) { res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; } if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPChecksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPChecksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } else if (ppr.ipStatus == ppresIPV6) { if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPv6Checksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPv6Checksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } return res; } Commit Message: NetKVM: BZ#1169718: Checking the length only on read Signed-off-by: Joseph Hindin <[email protected]> CWE ID: CWE-20
tChecksumCheckResult ParaNdis_CheckRxChecksum( PARANDIS_ADAPTER *pContext, ULONG virtioFlags, tCompletePhysicalAddress *pPacketPages, ULONG ulPacketLength, ULONG ulDataOffset, BOOLEAN verifyLength) { tOffloadSettingsFlags f = pContext->Offload.flags; tChecksumCheckResult res; tTcpIpPacketParsingResult ppr; ULONG flagsToCalculate = 0; res.value = 0; if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) { if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; } else { if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; } } ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, verifyLength, __FUNCTION__); if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete) { res.flags.IpOK = FALSE; res.flags.IpFailed = TRUE; return res; } if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) { pContext->extraStatistics.framesRxCSHwOK++; ppr.xxpCheckSum = ppresCSOK; } if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) { if (f.fRxIPChecksum) { res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; } if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPChecksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPChecksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } else if (ppr.ipStatus == ppresIPV6) { if(ppr.xxpStatus == ppresXxpKnown) { if(ppr.TcpUdp == ppresIsTCP) /* TCP */ { if (f.fRxTCPv6Checksum) { res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.TcpFailed = !res.flags.TcpOK; } } else /* UDP */ { if (f.fRxUDPv6Checksum) { res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; res.flags.UdpFailed = !res.flags.UdpOK; } } } } return res; }
170,139
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int pppol2tp_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int val; int err; if (level != SOL_PPPOL2TP) return udp_prot.setsockopt(sk, level, optname, optval, optlen); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get session context from the socket */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_setsockopt(sk, session, optname, val); err = 0; end_put_sess: sock_put(sk); end: return err; } Commit Message: net/l2tp: don't fall back on UDP [get|set]sockopt The l2tp [get|set]sockopt() code has fallen back to the UDP functions for socket option levels != SOL_PPPOL2TP since day one, but that has never actually worked, since the l2tp socket isn't an inet socket. As David Miller points out: "If we wanted this to work, it'd have to look up the tunnel and then use tunnel->sk, but I wonder how useful that would be" Since this can never have worked so nobody could possibly have depended on that functionality, just remove the broken code and return -EINVAL. Reported-by: Sasha Levin <[email protected]> Acked-by: James Chapman <[email protected]> Acked-by: David Miller <[email protected]> Cc: Phil Turnbull <[email protected]> Cc: Vegard Nossum <[email protected]> Cc: Willy Tarreau <[email protected]> Cc: [email protected] Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static int pppol2tp_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2tp_session *session; struct l2tp_tunnel *tunnel; struct pppol2tp_session *ps; int val; int err; if (level != SOL_PPPOL2TP) return -EINVAL; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; err = -ENOTCONN; if (sk->sk_user_data == NULL) goto end; /* Get session context from the socket */ err = -EBADF; session = pppol2tp_sock_to_session(sk); if (session == NULL) goto end; /* Special case: if session_id == 0x0000, treat as operation on tunnel */ ps = l2tp_session_priv(session); if ((session->session_id == 0) && (session->peer_session_id == 0)) { err = -EBADF; tunnel = l2tp_sock_to_tunnel(ps->tunnel_sock); if (tunnel == NULL) goto end_put_sess; err = pppol2tp_tunnel_setsockopt(sk, tunnel, optname, val); sock_put(ps->tunnel_sock); } else err = pppol2tp_session_setsockopt(sk, session, optname, val); err = 0; end_put_sess: sock_put(sk); end: return err; }
166,287
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sp<IMemoryHeap> BpMemory::getMemory(ssize_t* offset, size_t* size) const { if (mHeap == 0) { Parcel data, reply; data.writeInterfaceToken(IMemory::getInterfaceDescriptor()); if (remote()->transact(GET_MEMORY, data, &reply) == NO_ERROR) { sp<IBinder> heap = reply.readStrongBinder(); ssize_t o = reply.readInt32(); size_t s = reply.readInt32(); if (heap != 0) { mHeap = interface_cast<IMemoryHeap>(heap); if (mHeap != 0) { mOffset = o; mSize = s; } } } } if (offset) *offset = mOffset; if (size) *size = mSize; return mHeap; } Commit Message: Sanity check IMemory access versus underlying mmap Bug 26877992 Change-Id: Ibbf4b1061e4675e4e96bc944a865b53eaf6984fe CWE ID: CWE-264
sp<IMemoryHeap> BpMemory::getMemory(ssize_t* offset, size_t* size) const { if (mHeap == 0) { Parcel data, reply; data.writeInterfaceToken(IMemory::getInterfaceDescriptor()); if (remote()->transact(GET_MEMORY, data, &reply) == NO_ERROR) { sp<IBinder> heap = reply.readStrongBinder(); ssize_t o = reply.readInt32(); size_t s = reply.readInt32(); if (heap != 0) { mHeap = interface_cast<IMemoryHeap>(heap); if (mHeap != 0) { size_t heapSize = mHeap->getSize(); if (s <= heapSize && o >= 0 && (static_cast<size_t>(o) <= heapSize - s)) { mOffset = o; mSize = s; } else { // Hm. android_errorWriteWithInfoLog(0x534e4554, "26877992", -1, NULL, 0); mOffset = 0; mSize = 0; } } } } } if (offset) *offset = mOffset; if (size) *size = mSize; return (mSize > 0) ? mHeap : 0; }
173,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NetworkHandler::ClearBrowserCookies( std::unique_ptr<ClearBrowserCookiesCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &ClearCookiesOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), std::move(callback))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::ClearBrowserCookies( std::unique_ptr<ClearBrowserCookiesCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &ClearCookiesOnIO, base::Unretained(storage_partition_->GetURLRequestContext()), std::move(callback))); }
172,753
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zephyr_print(netdissect_options *ndo, const u_char *cp, int length) { struct z_packet z; const char *parse = (const char *) cp; int parselen = length; const char *s; int lose = 0; /* squelch compiler warnings */ z.kind = 0; z.class = 0; z.inst = 0; z.opcode = 0; z.sender = 0; z.recipient = 0; #define PARSE_STRING \ s = parse_field(ndo, &parse, &parselen); \ if (!s) lose = 1; #define PARSE_FIELD_INT(field) \ PARSE_STRING \ if (!lose) field = strtol(s, 0, 16); #define PARSE_FIELD_STR(field) \ PARSE_STRING \ if (!lose) field = s; PARSE_FIELD_STR(z.version); if (lose) return; if (strncmp(z.version, "ZEPH", 4)) return; PARSE_FIELD_INT(z.numfields); PARSE_FIELD_INT(z.kind); PARSE_FIELD_STR(z.uid); PARSE_FIELD_INT(z.port); PARSE_FIELD_INT(z.auth); PARSE_FIELD_INT(z.authlen); PARSE_FIELD_STR(z.authdata); PARSE_FIELD_STR(z.class); PARSE_FIELD_STR(z.inst); PARSE_FIELD_STR(z.opcode); PARSE_FIELD_STR(z.sender); PARSE_FIELD_STR(z.recipient); PARSE_FIELD_STR(z.format); PARSE_FIELD_INT(z.cksum); PARSE_FIELD_INT(z.multi); PARSE_FIELD_STR(z.multi_uid); if (lose) { ND_PRINT((ndo, " [|zephyr] (%d)", length)); return; } ND_PRINT((ndo, " zephyr")); if (strncmp(z.version+4, "0.2", 3)) { ND_PRINT((ndo, " v%s", z.version+4)); return; } ND_PRINT((ndo, " %s", tok2str(z_types, "type %d", z.kind))); if (z.kind == Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *ackdata = NULL; PARSE_FIELD_STR(ackdata); if (!lose && strcmp(ackdata, "SENT")) ND_PRINT((ndo, "/%s", str_to_lower(ackdata))); } if (*z.sender) ND_PRINT((ndo, " %s", z.sender)); if (!strcmp(z.class, "USER_LOCATE")) { if (!strcmp(z.opcode, "USER_HIDE")) ND_PRINT((ndo, " hide")); else if (!strcmp(z.opcode, "USER_UNHIDE")) ND_PRINT((ndo, " unhide")); else ND_PRINT((ndo, " locate %s", z.inst)); return; } if (!strcmp(z.class, "ZEPHYR_ADMIN")) { ND_PRINT((ndo, " zephyr-admin %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "ZEPHYR_CTL")) { if (!strcmp(z.inst, "CLIENT")) { if (!strcmp(z.opcode, "SUBSCRIBE") || !strcmp(z.opcode, "SUBSCRIBE_NODEFS") || !strcmp(z.opcode, "UNSUBSCRIBE")) { ND_PRINT((ndo, " %ssub%s", strcmp(z.opcode, "SUBSCRIBE") ? "un" : "", strcmp(z.opcode, "SUBSCRIBE_NODEFS") ? "" : "-nodefs")); if (z.kind != Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *c = NULL, *i = NULL, *r = NULL; PARSE_FIELD_STR(c); PARSE_FIELD_STR(i); PARSE_FIELD_STR(r); if (!lose) ND_PRINT((ndo, " %s", z_triple(c, i, r))); } return; } if (!strcmp(z.opcode, "GIMME")) { ND_PRINT((ndo, " ret")); return; } if (!strcmp(z.opcode, "GIMMEDEFS")) { ND_PRINT((ndo, " gimme-defs")); return; } if (!strcmp(z.opcode, "CLEARSUB")) { ND_PRINT((ndo, " clear-subs")); return; } ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "HM")) { ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "REALM")) { if (!strcmp(z.opcode, "ADD_SUBSCRIBE")) ND_PRINT((ndo, " realm add-subs")); if (!strcmp(z.opcode, "REQ_SUBSCRIBE")) ND_PRINT((ndo, " realm req-subs")); if (!strcmp(z.opcode, "RLM_SUBSCRIBE")) ND_PRINT((ndo, " realm rlm-sub")); if (!strcmp(z.opcode, "RLM_UNSUBSCRIBE")) ND_PRINT((ndo, " realm rlm-unsub")); return; } } if (!strcmp(z.class, "HM_CTL")) { ND_PRINT((ndo, " hm_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "HM_STAT")) { if (!strcmp(z.inst, "HMST_CLIENT") && !strcmp(z.opcode, "GIMMESTATS")) { ND_PRINT((ndo, " get-client-stats")); return; } } if (!strcmp(z.class, "WG_CTL")) { ND_PRINT((ndo, " wg_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "LOGIN")) { if (!strcmp(z.opcode, "USER_FLUSH")) { ND_PRINT((ndo, " flush_locs")); return; } if (!strcmp(z.opcode, "NONE") || !strcmp(z.opcode, "OPSTAFF") || !strcmp(z.opcode, "REALM-VISIBLE") || !strcmp(z.opcode, "REALM-ANNOUNCED") || !strcmp(z.opcode, "NET-VISIBLE") || !strcmp(z.opcode, "NET-ANNOUNCED")) { ND_PRINT((ndo, " set-exposure %s", str_to_lower(z.opcode))); return; } } if (!*z.recipient) z.recipient = "*"; ND_PRINT((ndo, " to %s", z_triple(z.class, z.inst, z.recipient))); if (*z.opcode) ND_PRINT((ndo, " op %s", z.opcode)); } Commit Message: CVE-2017-12902/Zephyr: Fix bounds checking. Use ND_TTEST() rather than comparing against ndo->ndo_snapend ourselves; it's easy to get the tests wrong. Check for running out of packet data before checking for running out of captured data, and distinguish between running out of packet data (which might just mean "no more strings") and running out of captured data (which means "truncated"). This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
zephyr_print(netdissect_options *ndo, const u_char *cp, int length) { struct z_packet z; const char *parse = (const char *) cp; int parselen = length; const char *s; int lose = 0; int truncated = 0; /* squelch compiler warnings */ z.kind = 0; z.class = 0; z.inst = 0; z.opcode = 0; z.sender = 0; z.recipient = 0; #define PARSE_STRING \ s = parse_field(ndo, &parse, &parselen, &truncated); \ if (truncated) goto trunc; \ if (!s) lose = 1; #define PARSE_FIELD_INT(field) \ PARSE_STRING \ if (!lose) field = strtol(s, 0, 16); #define PARSE_FIELD_STR(field) \ PARSE_STRING \ if (!lose) field = s; PARSE_FIELD_STR(z.version); if (lose) return; if (strncmp(z.version, "ZEPH", 4)) return; PARSE_FIELD_INT(z.numfields); PARSE_FIELD_INT(z.kind); PARSE_FIELD_STR(z.uid); PARSE_FIELD_INT(z.port); PARSE_FIELD_INT(z.auth); PARSE_FIELD_INT(z.authlen); PARSE_FIELD_STR(z.authdata); PARSE_FIELD_STR(z.class); PARSE_FIELD_STR(z.inst); PARSE_FIELD_STR(z.opcode); PARSE_FIELD_STR(z.sender); PARSE_FIELD_STR(z.recipient); PARSE_FIELD_STR(z.format); PARSE_FIELD_INT(z.cksum); PARSE_FIELD_INT(z.multi); PARSE_FIELD_STR(z.multi_uid); if (lose) goto trunc; ND_PRINT((ndo, " zephyr")); if (strncmp(z.version+4, "0.2", 3)) { ND_PRINT((ndo, " v%s", z.version+4)); return; } ND_PRINT((ndo, " %s", tok2str(z_types, "type %d", z.kind))); if (z.kind == Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *ackdata = NULL; PARSE_FIELD_STR(ackdata); if (!lose && strcmp(ackdata, "SENT")) ND_PRINT((ndo, "/%s", str_to_lower(ackdata))); } if (*z.sender) ND_PRINT((ndo, " %s", z.sender)); if (!strcmp(z.class, "USER_LOCATE")) { if (!strcmp(z.opcode, "USER_HIDE")) ND_PRINT((ndo, " hide")); else if (!strcmp(z.opcode, "USER_UNHIDE")) ND_PRINT((ndo, " unhide")); else ND_PRINT((ndo, " locate %s", z.inst)); return; } if (!strcmp(z.class, "ZEPHYR_ADMIN")) { ND_PRINT((ndo, " zephyr-admin %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "ZEPHYR_CTL")) { if (!strcmp(z.inst, "CLIENT")) { if (!strcmp(z.opcode, "SUBSCRIBE") || !strcmp(z.opcode, "SUBSCRIBE_NODEFS") || !strcmp(z.opcode, "UNSUBSCRIBE")) { ND_PRINT((ndo, " %ssub%s", strcmp(z.opcode, "SUBSCRIBE") ? "un" : "", strcmp(z.opcode, "SUBSCRIBE_NODEFS") ? "" : "-nodefs")); if (z.kind != Z_PACKET_SERVACK) { /* Initialization to silence warnings */ const char *c = NULL, *i = NULL, *r = NULL; PARSE_FIELD_STR(c); PARSE_FIELD_STR(i); PARSE_FIELD_STR(r); if (!lose) ND_PRINT((ndo, " %s", z_triple(c, i, r))); } return; } if (!strcmp(z.opcode, "GIMME")) { ND_PRINT((ndo, " ret")); return; } if (!strcmp(z.opcode, "GIMMEDEFS")) { ND_PRINT((ndo, " gimme-defs")); return; } if (!strcmp(z.opcode, "CLEARSUB")) { ND_PRINT((ndo, " clear-subs")); return; } ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "HM")) { ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.inst, "REALM")) { if (!strcmp(z.opcode, "ADD_SUBSCRIBE")) ND_PRINT((ndo, " realm add-subs")); if (!strcmp(z.opcode, "REQ_SUBSCRIBE")) ND_PRINT((ndo, " realm req-subs")); if (!strcmp(z.opcode, "RLM_SUBSCRIBE")) ND_PRINT((ndo, " realm rlm-sub")); if (!strcmp(z.opcode, "RLM_UNSUBSCRIBE")) ND_PRINT((ndo, " realm rlm-unsub")); return; } } if (!strcmp(z.class, "HM_CTL")) { ND_PRINT((ndo, " hm_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "HM_STAT")) { if (!strcmp(z.inst, "HMST_CLIENT") && !strcmp(z.opcode, "GIMMESTATS")) { ND_PRINT((ndo, " get-client-stats")); return; } } if (!strcmp(z.class, "WG_CTL")) { ND_PRINT((ndo, " wg_ctl %s", str_to_lower(z.inst))); ND_PRINT((ndo, " %s", str_to_lower(z.opcode))); return; } if (!strcmp(z.class, "LOGIN")) { if (!strcmp(z.opcode, "USER_FLUSH")) { ND_PRINT((ndo, " flush_locs")); return; } if (!strcmp(z.opcode, "NONE") || !strcmp(z.opcode, "OPSTAFF") || !strcmp(z.opcode, "REALM-VISIBLE") || !strcmp(z.opcode, "REALM-ANNOUNCED") || !strcmp(z.opcode, "NET-VISIBLE") || !strcmp(z.opcode, "NET-ANNOUNCED")) { ND_PRINT((ndo, " set-exposure %s", str_to_lower(z.opcode))); return; } } if (!*z.recipient) z.recipient = "*"; ND_PRINT((ndo, " to %s", z_triple(z.class, z.inst, z.recipient))); if (*z.opcode) ND_PRINT((ndo, " op %s", z.opcode)); return; trunc: ND_PRINT((ndo, " [|zephyr] (%d)", length)); return; }
167,936
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ssl3_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) { CERT *cert; cert = ctx->cert; switch (cmd) { #ifndef OPENSSL_NO_RSA case SSL_CTRL_NEED_TMP_RSA: if ((cert->rsa_tmp == NULL) && ((cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || (EVP_PKEY_size(cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512 / 8))) ) return (1); else return (0); /* break; */ case SSL_CTRL_SET_TMP_RSA: { RSA *rsa; int i; rsa = (RSA *)parg; i = 1; if (rsa == NULL) i = 0; else { if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) i = 0; } if (!i) { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_RSA_LIB); return (0); } else { if (cert->rsa_tmp != NULL) RSA_free(cert->rsa_tmp); cert->rsa_tmp = rsa; return (1); } } /* break; */ case SSL_CTRL_SET_TMP_RSA_CB: { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return (0); } break; #endif SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB); return 0; } if (!(ctx->options & SSL_OP_SINGLE_DH_USE)) { if (!DH_generate_key(new)) { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB); DH_free(new); return 0; } } if (cert->dh_tmp != NULL) DH_free(cert->dh_tmp); cert->dh_tmp = new; if ((new = DHparams_dup(dh)) == NULL) { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB); return 0; } if (!(ctx->options & SSL_OP_SINGLE_DH_USE)) { if (!DH_generate_key(new)) { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB); DH_free(new); return 0; } } if (cert->dh_tmp != NULL) DH_free(cert->dh_tmp); cert->dh_tmp = new; return 1; } Commit Message: CWE ID: CWE-200
long ssl3_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg) { CERT *cert; cert = ctx->cert; switch (cmd) { #ifndef OPENSSL_NO_RSA case SSL_CTRL_NEED_TMP_RSA: if ((cert->rsa_tmp == NULL) && ((cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL) || (EVP_PKEY_size(cert->pkeys[SSL_PKEY_RSA_ENC].privatekey) > (512 / 8))) ) return (1); else return (0); /* break; */ case SSL_CTRL_SET_TMP_RSA: { RSA *rsa; int i; rsa = (RSA *)parg; i = 1; if (rsa == NULL) i = 0; else { if ((rsa = RSAPrivateKey_dup(rsa)) == NULL) i = 0; } if (!i) { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_RSA_LIB); return (0); } else { if (cert->rsa_tmp != NULL) RSA_free(cert->rsa_tmp); cert->rsa_tmp = rsa; return (1); } } /* break; */ case SSL_CTRL_SET_TMP_RSA_CB: { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); return (0); } break; #endif SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB); return 0; } if (cert->dh_tmp != NULL) DH_free(cert->dh_tmp); cert->dh_tmp = new; if ((new = DHparams_dup(dh)) == NULL) { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB); return 0; } if (!(ctx->options & SSL_OP_SINGLE_DH_USE)) { if (!DH_generate_key(new)) { SSLerr(SSL_F_SSL3_CTX_CTRL, ERR_R_DH_LIB); DH_free(new); return 0; } } if (cert->dh_tmp != NULL) DH_free(cert->dh_tmp); cert->dh_tmp = new; return 1; }
165,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int imagetobmp(opj_image_t * image, const char *outfile) { int w, h; int i, pad; FILE *fdest = NULL; int adjustR, adjustG, adjustB; if (image->comps[0].prec < 8) { fprintf(stderr, "Unsupported number of components: %d\n", image->comps[0].prec); return 1; } if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx && image->comps[1].dx == image->comps[2].dx && image->comps[0].dy == image->comps[1].dy && image->comps[1].dy == image->comps[2].dy && image->comps[0].prec == image->comps[1].prec && image->comps[1].prec == image->comps[2].prec) { /* -->> -->> -->> -->> 24 bits color <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (3 * h * w + 3 * h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); } else adjustR = 0; if (image->comps[1].prec > 8) { adjustG = (int)image->comps[1].prec - 8; printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec); } else adjustG = 0; if (image->comps[2].prec > 8) { adjustB = (int)image->comps[2].prec - 8; printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec); } else adjustB = 0; for (i = 0; i < w * h; i++) { OPJ_UINT8 rc, gc, bc; int r, g, b; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; rc = (OPJ_UINT8)r; g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); g = ((g >> adjustG)+((g >> (adjustG-1))%2)); if(g > 255) g = 255; else if(g < 0) g = 0; gc = (OPJ_UINT8)g; b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); b = ((b >> adjustB)+((b >> (adjustB-1))%2)); if(b > 255) b = 255; else if(b < 0) b = 0; bc = (OPJ_UINT8)b; fprintf(fdest, "%c%c%c", bc, gc, rc); if ((i + 1) % w == 0) { for (pad = ((3 * w) % 4) ? (4 - (3 * w) % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } else { /* Gray-scale */ /* -->> -->> -->> -->> 8 bits non code (Gray scale) <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + 54 + 1024 + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, ((54 + 1024) >> 16) & 0xff, ((54 + 1024) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); }else adjustR = 0; for (i = 0; i < 256; i++) { fprintf(fdest, "%c%c%c%c", i, i, i, 0); } for (i = 0; i < w * h; i++) { int r; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; fprintf(fdest, "%c", (OPJ_UINT8)r); if ((i + 1) % w == 0) { for ((pad = w % 4) ? (4 - w % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } return 0; } 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
int imagetobmp(opj_image_t * image, const char *outfile) { int w, h; int i, pad; FILE *fdest = NULL; int adjustR, adjustG, adjustB; if (image->comps[0].prec < 8) { fprintf(stderr, "Unsupported number of components: %d\n", image->comps[0].prec); return 1; } if (image->numcomps >= 3 && image->comps[0].dx == image->comps[1].dx && image->comps[1].dx == image->comps[2].dx && image->comps[0].dy == image->comps[1].dy && image->comps[1].dy == image->comps[2].dy && image->comps[0].prec == image->comps[1].prec && image->comps[1].prec == image->comps[2].prec) { /* -->> -->> -->> -->> 24 bits color <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w * 3 + 3 * h * (w % 2) + 54) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2) + 54) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54) & 0xff, ((54) >> 8) & 0xff,((54) >> 16) & 0xff, ((54) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (24) & 0xff, ((24) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (3 * h * w + 3 * h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w * 3 + 3 * h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); } else adjustR = 0; if (image->comps[1].prec > 8) { adjustG = (int)image->comps[1].prec - 8; printf("BMP CONVERSION: Truncating component 1 from %d bits to 8 bits\n", image->comps[1].prec); } else adjustG = 0; if (image->comps[2].prec > 8) { adjustB = (int)image->comps[2].prec - 8; printf("BMP CONVERSION: Truncating component 2 from %d bits to 8 bits\n", image->comps[2].prec); } else adjustB = 0; for (i = 0; i < w * h; i++) { OPJ_UINT8 rc, gc, bc; int r, g, b; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; rc = (OPJ_UINT8)r; g = image->comps[1].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; g += (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0); g = ((g >> adjustG)+((g >> (adjustG-1))%2)); if(g > 255) g = 255; else if(g < 0) g = 0; gc = (OPJ_UINT8)g; b = image->comps[2].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; b += (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0); b = ((b >> adjustB)+((b >> (adjustB-1))%2)); if(b > 255) b = 255; else if(b < 0) b = 0; bc = (OPJ_UINT8)b; fprintf(fdest, "%c%c%c", bc, gc, rc); if ((i + 1) % w == 0) { for (pad = ((3 * w) % 4) ? (4 - (3 * w) % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } else { /* Gray-scale */ /* -->> -->> -->> -->> 8 bits non code (Gray scale) <<-- <<-- <<-- <<-- */ fdest = fopen(outfile, "wb"); if (!fdest) { fprintf(stderr, "ERROR -> failed to open %s for writing\n", outfile); return 1; } w = (int)image->comps[0].w; h = (int)image->comps[0].h; fprintf(fdest, "BM"); /* FILE HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + 54 + 1024 + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + 54 + 1024 + w * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (54 + 1024) & 0xff, ((54 + 1024) >> 8) & 0xff, ((54 + 1024) >> 16) & 0xff, ((54 + 1024) >> 24) & 0xff); /* INFO HEADER */ /* ------------- */ fprintf(fdest, "%c%c%c%c", (40) & 0xff, ((40) >> 8) & 0xff, ((40) >> 16) & 0xff, ((40) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((w) & 0xff), (OPJ_UINT8) ((w) >> 8) & 0xff, (OPJ_UINT8) ((w) >> 16) & 0xff, (OPJ_UINT8) ((w) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) ((h) & 0xff), (OPJ_UINT8) ((h) >> 8) & 0xff, (OPJ_UINT8) ((h) >> 16) & 0xff, (OPJ_UINT8) ((h) >> 24) & 0xff); fprintf(fdest, "%c%c", (1) & 0xff, ((1) >> 8) & 0xff); fprintf(fdest, "%c%c", (8) & 0xff, ((8) >> 8) & 0xff); fprintf(fdest, "%c%c%c%c", (0) & 0xff, ((0) >> 8) & 0xff, ((0) >> 16) & 0xff, ((0) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (OPJ_UINT8) (h * w + h * (w % 2)) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 8) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 16) & 0xff, (OPJ_UINT8) ((h * w + h * (w % 2)) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (7834) & 0xff, ((7834) >> 8) & 0xff, ((7834) >> 16) & 0xff, ((7834) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); fprintf(fdest, "%c%c%c%c", (256) & 0xff, ((256) >> 8) & 0xff, ((256) >> 16) & 0xff, ((256) >> 24) & 0xff); if (image->comps[0].prec > 8) { adjustR = (int)image->comps[0].prec - 8; printf("BMP CONVERSION: Truncating component 0 from %d bits to 8 bits\n", image->comps[0].prec); }else adjustR = 0; for (i = 0; i < 256; i++) { fprintf(fdest, "%c%c%c%c", i, i, i, 0); } for (i = 0; i < w * h; i++) { int r; r = image->comps[0].data[w * h - ((i) / (w) + 1) * w + (i) % (w)]; r += (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0); r = ((r >> adjustR)+((r >> (adjustR-1))%2)); if(r > 255) r = 255; else if(r < 0) r = 0; fprintf(fdest, "%c", (OPJ_UINT8)r); if ((i + 1) % w == 0) { for (pad = (w % 4) ? (4 - w % 4) : 0; pad > 0; pad--) /* ADD */ fprintf(fdest, "%c", 0); } } fclose(fdest); } return 0; }
168,842
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void __exit exit_ext2_fs(void) { unregister_filesystem(&ext2_fs_type); destroy_inodecache(); exit_ext2_xattr(); } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the 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 the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
static void __exit exit_ext2_fs(void) { unregister_filesystem(&ext2_fs_type); destroy_inodecache(); }
169,972
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: read_packet(int fd, gss_buffer_t buf, int timeout, int first) { int ret; static uint32_t len = 0; static char len_buf[4]; static int len_buf_pos = 0; static char * tmpbuf = 0; static int tmpbuf_pos = 0; if (first) { len_buf_pos = 0; return -2; } if (len_buf_pos < 4) { ret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { /* EOF */ /* Failure to read ANY length just means we're done */ if (len_buf_pos == 0) return 0; /* * Otherwise, we got EOF mid-length, and that's * a protocol error. */ LOG(LOG_INFO, ("EOF reading packet len")); return -1; } len_buf_pos += ret; } /* Not done reading the length? */ if (len_buf_pos != 4) return -2; /* We have the complete length */ len = ntohl(*(uint32_t *)len_buf); /* * We make sure recvd length is reasonable, allowing for some * slop in enc overhead, beyond the actual maximum number of * bytes of decrypted payload. */ if (len > GSTD_MAXPACKETCONTENTS + 512) { LOG(LOG_ERR, ("ridiculous length, %ld", len)); return -1; } if (!tmpbuf) { if ((tmpbuf = malloc(len)) == NULL) { LOG(LOG_CRIT, ("malloc failure, %ld bytes", len)); return -1; } } ret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); return -1; } if (ret == 0) { LOG(LOG_ERR, ("EOF while reading packet (len=%d)", len)); return -1; } tmpbuf_pos += ret; if (tmpbuf_pos == len) { buf->length = len; buf->value = tmpbuf; len = len_buf_pos = tmpbuf_pos = 0; tmpbuf = NULL; LOG(LOG_DEBUG, ("read packet of length %d", buf->length)); return 1; } return -2; } Commit Message: knc: fix a couple of memory leaks. One of these can be remotely triggered during the authentication phase which leads to a remote DoS possibility. Pointed out by: Imre Rad <[email protected]> CWE ID: CWE-400
read_packet(int fd, gss_buffer_t buf, int timeout, int first) { int ret; static uint32_t len = 0; static char len_buf[4]; static int len_buf_pos = 0; static char * tmpbuf = 0; static int tmpbuf_pos = 0; if (first) { len_buf_pos = 0; return -2; } if (len_buf_pos < 4) { ret = timed_read(fd, &len_buf[len_buf_pos], 4 - len_buf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); goto bail; } if (ret == 0) { /* EOF */ /* Failure to read ANY length just means we're done */ if (len_buf_pos == 0) return 0; /* * Otherwise, we got EOF mid-length, and that's * a protocol error. */ LOG(LOG_INFO, ("EOF reading packet len")); goto bail; } len_buf_pos += ret; } /* Not done reading the length? */ if (len_buf_pos != 4) return -2; /* We have the complete length */ len = ntohl(*(uint32_t *)len_buf); /* * We make sure recvd length is reasonable, allowing for some * slop in enc overhead, beyond the actual maximum number of * bytes of decrypted payload. */ if (len > GSTD_MAXPACKETCONTENTS + 512) { LOG(LOG_ERR, ("ridiculous length, %ld", len)); goto bail; } if (!tmpbuf) { if ((tmpbuf = malloc(len)) == NULL) { LOG(LOG_CRIT, ("malloc failure, %ld bytes", len)); goto bail; } } ret = timed_read(fd, tmpbuf + tmpbuf_pos, len - tmpbuf_pos, timeout); if (ret == -1) { if (errno == EINTR || errno == EAGAIN) return -2; LOG(LOG_ERR, ("%s", strerror(errno))); goto bail; } if (ret == 0) { LOG(LOG_ERR, ("EOF while reading packet (len=%d)", len)); goto bail; } tmpbuf_pos += ret; if (tmpbuf_pos == len) { buf->length = len; buf->value = tmpbuf; len = len_buf_pos = tmpbuf_pos = 0; tmpbuf = NULL; LOG(LOG_DEBUG, ("read packet of length %d", buf->length)); return 1; } return -2; bail: free(tmpbuf); tmpbuf = NULL; return -1; }
169,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MaybeStopInputMethodDaemon(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value) && enable_auto_ime_shutdown_) { StopInputMethodDaemon(); } } 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
void MaybeStopInputMethodDaemon(const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value) && enable_auto_ime_shutdown_) { StopInputMethodDaemon(); } }
170,500
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeFrontendQueryParam( const std::string& key, const std::string& value) { if (key == "can_dock" || key == "debugFrontend" || key == "experiments" || key == "isSharedWorker" || key == "v8only" || key == "remoteFrontend") return "true"; if (key == "ws" || key == "service-backend") return SanitizeEndpoint(value); if (key == "dockSide" && value == "undocked") return value; if (key == "panel" && (value == "elements" || value == "console")) return value; if (key == "remoteBase") return SanitizeRemoteBase(value); if (key == "remoteFrontendUrl") return SanitizeRemoteFrontendURL(value); return std::string(); } 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
std::string SanitizeFrontendQueryParam(
172,459
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[]) { tBTM_SEC_DEV_REC *p_dev_rec; BTM_TRACE_API ("BTM_PINCodeReply(): PairState: %s PairFlags: 0x%02x PinLen:%d Result:%d", btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len, res); /* If timeout already expired or has been canceled, ignore the reply */ if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) { BTM_TRACE_WARNING ("BTM_PINCodeReply() - Wrong State: %d", btm_cb.pairing_state); return; } if (memcmp (bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) { BTM_TRACE_ERROR ("BTM_PINCodeReply() - Wrong BD Addr"); return; } if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL) { BTM_TRACE_ERROR ("BTM_PINCodeReply() - no dev CB"); return; } if ( (pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL) ) res = BTM_ILLEGAL_VALUE; if (res != BTM_SUCCESS) { /* if peer started dd OR we started dd and pre-fetch pin was not used send negative reply */ if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) || ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) ) { /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */ btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_pin_code_neg_reply (bd_addr); } else { p_dev_rec->security_required = BTM_SEC_NONE; btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); } return; } if (trusted_mask) BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask); p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED; if ( (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) && (btm_cb.security_mode_changed == FALSE) ) { /* This is start of the dedicated bonding if local device is 2.0 */ btm_cb.pin_code_len = pin_len; memcpy (btm_cb.pin_code, p_pin, pin_len); btm_cb.security_mode_changed = TRUE; #ifdef APPL_AUTH_WRITE_EXCEPTION if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr)) #endif btsnd_hcic_write_auth_enable (TRUE); btm_cb.acl_disc_reason = 0xff ; /* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */ /* before originating */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { BTM_TRACE_WARNING ("BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected incoming connection"); /* we change state little bit early so btm_sec_connected() will originate connection */ /* when existing ACL link is down completely */ btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ); } /* if we already accepted incoming connection from pairing device */ else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { BTM_TRACE_WARNING ("BTM_PINCodeReply(): link is connecting so wait pin code request from peer"); btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ); } else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) { btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED; if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_AUTH_FAILURE); } return; } btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_SUCCESS; #ifdef PORCHE_PAIRING_CONFLICT BTM_TRACE_EVENT("BTM_PINCodeReply(): Saving pin_len: %d btm_cb.pin_code_len: %d", pin_len, btm_cb.pin_code_len); /* if this was not pre-fetched, save the PIN */ if (btm_cb.pin_code_len == 0) memcpy (btm_cb.pin_code, p_pin, pin_len); btm_cb.pin_code_len_saved = pin_len; #endif btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin); } Commit Message: DO NOT MERGE Remove Porsche car-kit pairing workaround Bug: 26551752 Change-Id: I14c5e3fcda0849874c8a94e48aeb7d09585617e1 CWE ID: CWE-264
void BTM_PINCodeReply (BD_ADDR bd_addr, UINT8 res, UINT8 pin_len, UINT8 *p_pin, UINT32 trusted_mask[]) { tBTM_SEC_DEV_REC *p_dev_rec; BTM_TRACE_API ("BTM_PINCodeReply(): PairState: %s PairFlags: 0x%02x PinLen:%d Result:%d", btm_pair_state_descr(btm_cb.pairing_state), btm_cb.pairing_flags, pin_len, res); /* If timeout already expired or has been canceled, ignore the reply */ if (btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_LOCAL_PIN) { BTM_TRACE_WARNING ("BTM_PINCodeReply() - Wrong State: %d", btm_cb.pairing_state); return; } if (memcmp (bd_addr, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) { BTM_TRACE_ERROR ("BTM_PINCodeReply() - Wrong BD Addr"); return; } if ((p_dev_rec = btm_find_dev (bd_addr)) == NULL) { BTM_TRACE_ERROR ("BTM_PINCodeReply() - no dev CB"); return; } if ( (pin_len > PIN_CODE_LEN) || (pin_len == 0) || (p_pin == NULL) ) res = BTM_ILLEGAL_VALUE; if (res != BTM_SUCCESS) { /* if peer started dd OR we started dd and pre-fetch pin was not used send negative reply */ if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PEER_STARTED_DD) || ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (btm_cb.pairing_flags & BTM_PAIR_FLAGS_DISC_WHEN_DONE)) ) { /* use BTM_PAIR_STATE_WAIT_AUTH_COMPLETE to report authentication failed event */ btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_ERR_HOST_REJECT_SECURITY; btsnd_hcic_pin_code_neg_reply (bd_addr); } else { p_dev_rec->security_required = BTM_SEC_NONE; btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); } return; } if (trusted_mask) BTM_SEC_COPY_TRUSTED_DEVICE(trusted_mask, p_dev_rec->trusted_mask); p_dev_rec->sec_flags |= BTM_SEC_LINK_KEY_AUTHED; if ( (btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) && (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) && (btm_cb.security_mode_changed == FALSE) ) { /* This is start of the dedicated bonding if local device is 2.0 */ btm_cb.pin_code_len = pin_len; memcpy (btm_cb.pin_code, p_pin, pin_len); btm_cb.security_mode_changed = TRUE; #ifdef APPL_AUTH_WRITE_EXCEPTION if(!(APPL_AUTH_WRITE_EXCEPTION)(p_dev_rec->bd_addr)) #endif btsnd_hcic_write_auth_enable (TRUE); btm_cb.acl_disc_reason = 0xff ; /* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */ /* before originating */ if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) { BTM_TRACE_WARNING ("BTM_PINCodeReply(): waiting HCI_Connection_Complete after rejected incoming connection"); /* we change state little bit early so btm_sec_connected() will originate connection */ /* when existing ACL link is down completely */ btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ); } /* if we already accepted incoming connection from pairing device */ else if (p_dev_rec->sm4 & BTM_SM4_CONN_PEND) { BTM_TRACE_WARNING ("BTM_PINCodeReply(): link is connecting so wait pin code request from peer"); btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_PIN_REQ); } else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) { btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); p_dev_rec->sec_flags &= ~BTM_SEC_LINK_KEY_AUTHED; if (btm_cb.api.p_auth_complete_callback) (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_dev_rec->sec_bd_name, HCI_ERR_AUTH_FAILURE); } return; } btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); btm_cb.acl_disc_reason = HCI_SUCCESS; btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin); }
173,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp) { struct compat_timex tx32; if (copy_from_user(&tx32, utp, sizeof(struct compat_timex))) return -EFAULT; txc->modes = tx32.modes; txc->offset = tx32.offset; txc->freq = tx32.freq; txc->maxerror = tx32.maxerror; txc->esterror = tx32.esterror; txc->status = tx32.status; txc->constant = tx32.constant; txc->precision = tx32.precision; txc->tolerance = tx32.tolerance; txc->time.tv_sec = tx32.time.tv_sec; txc->time.tv_usec = tx32.time.tv_usec; txc->tick = tx32.tick; txc->ppsfreq = tx32.ppsfreq; txc->jitter = tx32.jitter; txc->shift = tx32.shift; txc->stabil = tx32.stabil; txc->jitcnt = tx32.jitcnt; txc->calcnt = tx32.calcnt; txc->errcnt = tx32.errcnt; txc->stbcnt = tx32.stbcnt; return 0; } Commit Message: compat: fix 4-byte infoleak via uninitialized struct field Commit 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") removed the memset() in compat_get_timex(). Since then, the compat adjtimex syscall can invoke do_adjtimex() with an uninitialized ->tai. If do_adjtimex() doesn't write to ->tai (e.g. because the arguments are invalid), compat_put_timex() then copies the uninitialized ->tai field to userspace. Fix it by adding the memset() back. Fixes: 3a4d44b61625 ("ntp: Move adjtimex related compat syscalls to native counterparts") Signed-off-by: Jann Horn <[email protected]> Acked-by: Kees Cook <[email protected]> Acked-by: Al Viro <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
int compat_get_timex(struct timex *txc, const struct compat_timex __user *utp) { struct compat_timex tx32; memset(txc, 0, sizeof(struct timex)); if (copy_from_user(&tx32, utp, sizeof(struct compat_timex))) return -EFAULT; txc->modes = tx32.modes; txc->offset = tx32.offset; txc->freq = tx32.freq; txc->maxerror = tx32.maxerror; txc->esterror = tx32.esterror; txc->status = tx32.status; txc->constant = tx32.constant; txc->precision = tx32.precision; txc->tolerance = tx32.tolerance; txc->time.tv_sec = tx32.time.tv_sec; txc->time.tv_usec = tx32.time.tv_usec; txc->tick = tx32.tick; txc->ppsfreq = tx32.ppsfreq; txc->jitter = tx32.jitter; txc->shift = tx32.shift; txc->stabil = tx32.stabil; txc->jitcnt = tx32.jitcnt; txc->calcnt = tx32.calcnt; txc->errcnt = tx32.errcnt; txc->stbcnt = tx32.stbcnt; return 0; }
169,219
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); for(search = fs_searchpaths; search; search = search->next) { len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } } Commit Message: All: Don't load .pk3s as .dlls, and don't load user config files from .pk3s CWE ID: CWE-269
long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueFILE) { searchpath_t *search; long len; qboolean isLocalConfig; if(!fs_searchpaths) Com_Error(ERR_FATAL, "Filesystem call made without initialization"); isLocalConfig = !strcmp(filename, "autoexec.cfg") || !strcmp(filename, Q3CONFIG_CFG); for(search = fs_searchpaths; search; search = search->next) { // autoexec.cfg and wolfconfig.cfg can only be loaded outside of pk3 files. if (isLocalConfig && search->pack) continue; len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); if(file == NULL) { if(len > 0) return len; } else { if(len >= 0 && *file) return len; } } #ifdef FS_MISSING if(missingFiles) fprintf(missingFiles, "%s\n", filename); #endif if(file) { *file = 0; return -1; } else { return 0; } }
170,087
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::string SanitizeEndpoint(const std::string& value) { if (value.find('&') != std::string::npos || value.find('?') != std::string::npos) return std::string(); return value; } 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
std::string SanitizeEndpoint(const std::string& value) {
172,457
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exit_ext2_xattr(void) { mb_cache_destroy(ext2_xattr_cache); } Commit Message: ext2: convert to mbcache2 The conversion is generally straightforward. We convert filesystem from a global cache to per-fs one. Similarly to ext4 the 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 the buffer lock. Signed-off-by: Jan Kara <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> CWE ID: CWE-19
exit_ext2_xattr(void) void ext2_xattr_destroy_cache(struct mb2_cache *cache) { if (cache) mb2_cache_destroy(cache); }
169,976
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool LauncherView::IsShowingMenu() const { #if !defined(OS_MACOSX) return (overflow_menu_runner_.get() && overflow_menu_runner_->IsRunning()) || (launcher_menu_runner_.get() && launcher_menu_runner_->IsRunning()); #endif return false; } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool LauncherView::IsShowingMenu() const { #if !defined(OS_MACOSX) return (launcher_menu_runner_.get() && launcher_menu_runner_->IsRunning()); #endif return false; }
170,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumSamplesOutput = 0; } const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; int32_t numBytesRead; if (mMode == MODE_NARROW) { numBytesRead = AMRDecode(mState, (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), (UWord8 *)&inputPtr[1], reinterpret_cast<int16_t *>(outHeader->pBuffer), MIME_IETF); if (numBytesRead == -1) { ALOGE("PV AMR decoder AMRDecode() call failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } ++numBytesRead; // Include the frame type header byte. if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } else { int16 mode = ((inputPtr[0] >> 3) & 0x0f); if (mode >= 10 && mode <= 13) { ALOGE("encountered illegal frame type %d in AMR WB content.", mode); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } size_t frameSize = getFrameSize(mode); CHECK_GE(inHeader->nFilledLen, frameSize); int16_t *outPtr = (int16_t *)outHeader->pBuffer; if (mode >= 9) { memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); } else if (mode < 9) { int16 frameType; RX_State_wb rx_state; mime_unsorting( const_cast<uint8_t *>(&inputPtr[1]), mInputSampleBuffer, &frameType, &mode, 1, &rx_state); int16_t numSamplesOutput; pvDecoder_AmrWb( mode, mInputSampleBuffer, outPtr, &numSamplesOutput, mDecoderBuf, frameType, mDecoderCookie); CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { /* Delete the 2 LSBs (14-bit output) */ outPtr[i] &= 0xfffC; } } numBytesRead = frameSize; } inHeader->nOffset += numBytesRead; inHeader->nFilledLen -= numBytesRead; outHeader->nFlags = 0; outHeader->nOffset = 0; if (mMode == MODE_NARROW) { outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; mNumSamplesOutput += kNumSamplesPerFrameNB; } else { outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; mNumSamplesOutput += kNumSamplesPerFrameWB; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } } Commit Message: SoftAMR: check output buffer size to avoid overflow. Bug: 27662364 Change-Id: I7b26892c41d6f2e690e77478ab855c2fed1ff6b0 CWE ID: CWE-264
void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); if (mSignalledError || mOutputPortSettingsChange != NONE) { return; } while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nOffset == 0) { mAnchorTimeUs = inHeader->nTimeStamp; mNumSamplesOutput = 0; } const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; int32_t numBytesRead; if (mMode == MODE_NARROW) { if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) { ALOGE("b/27662364: NB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } numBytesRead = AMRDecode(mState, (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), (UWord8 *)&inputPtr[1], reinterpret_cast<int16_t *>(outHeader->pBuffer), MIME_IETF); if (numBytesRead == -1) { ALOGE("PV AMR decoder AMRDecode() call failed"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } ++numBytesRead; // Include the frame type header byte. if (static_cast<size_t>(numBytesRead) > inHeader->nFilledLen) { notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } } else { if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) { ALOGE("b/27662364: WB expected output buffer %zu bytes vs %u", kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27662364"); notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); mSignalledError = true; return; } int16 mode = ((inputPtr[0] >> 3) & 0x0f); if (mode >= 10 && mode <= 13) { ALOGE("encountered illegal frame type %d in AMR WB content.", mode); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } size_t frameSize = getFrameSize(mode); CHECK_GE(inHeader->nFilledLen, frameSize); int16_t *outPtr = (int16_t *)outHeader->pBuffer; if (mode >= 9) { memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); } else if (mode < 9) { int16 frameType; RX_State_wb rx_state; mime_unsorting( const_cast<uint8_t *>(&inputPtr[1]), mInputSampleBuffer, &frameType, &mode, 1, &rx_state); int16_t numSamplesOutput; pvDecoder_AmrWb( mode, mInputSampleBuffer, outPtr, &numSamplesOutput, mDecoderBuf, frameType, mDecoderCookie); CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { /* Delete the 2 LSBs (14-bit output) */ outPtr[i] &= 0xfffC; } } numBytesRead = frameSize; } inHeader->nOffset += numBytesRead; inHeader->nFilledLen -= numBytesRead; outHeader->nFlags = 0; outHeader->nOffset = 0; if (mMode == MODE_NARROW) { outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; mNumSamplesOutput += kNumSamplesPerFrameNB; } else { outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); outHeader->nTimeStamp = mAnchorTimeUs + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; mNumSamplesOutput += kNumSamplesPerFrameWB; } if (inHeader->nFilledLen == 0) { inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; ++mInputBufferCount; } }
173,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } 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 int getnum (lua_State *L, const char **fmt, int df) { static int getnum (const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } }
170,165
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void ResetModel() { last_pts_ = 0; bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz; frame_number_ = 0; first_drop_ = 0; bits_total_ = 0; duration_ = 0.0; } 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 ResetModel() { last_pts_ = 0; bits_in_buffer_model_ = cfg_.rc_target_bitrate * cfg_.rc_buf_initial_sz; frame_number_ = 0; first_drop_ = 0; bits_total_ = 0; duration_ = 0.0; denoiser_offon_test_ = 0; denoiser_offon_period_ = -1; }
174,517
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(locale_get_display_region) { get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_get_display_region) PHP_FUNCTION(locale_get_display_region) { get_icu_disp_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU ); }
167,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -ENOSYS; if (arg != CDSL_CURRENT && arg != CDSL_NONE) { if ((int)arg >= cdi->capacity) return -EINVAL; } /* * ->select_disc is a hook to allow a driver-specific way of * seleting disc. However, since there is no equivalent hook for * cdrom_slot_status this may not actually be useful... */ if (cdi->ops->select_disc) return cdi->ops->select_disc(cdi, arg); cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n"); return cdrom_select_disc(cdi, arg); } Commit Message: cdrom: fix improper type cast, which can leat to information leak. There is another cast from unsigned long to int which causes a bounds check to fail with specially crafted input. The value is then used as an index in the slot array in cdrom_slot_status(). This issue is similar to CVE-2018-16658 and CVE-2018-10940. Signed-off-by: Young_X <[email protected]> Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-200
static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -ENOSYS; if (arg != CDSL_CURRENT && arg != CDSL_NONE) { if (arg >= cdi->capacity) return -EINVAL; } /* * ->select_disc is a hook to allow a driver-specific way of * seleting disc. However, since there is no equivalent hook for * cdrom_slot_status this may not actually be useful... */ if (cdi->ops->select_disc) return cdi->ops->select_disc(cdi, arg); cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n"); return cdrom_select_disc(cdi, arg); }
168,999
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf) { git_pkt *pkt; const char *line, *line_end; size_t line_len; int error; int reading_from_buf = data_pkt_buf->size > 0; if (reading_from_buf) { /* We had an existing partial packet, so add the new * packet to the buffer and parse the whole thing */ git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len); line = data_pkt_buf->ptr; line_len = data_pkt_buf->size; } else { line = data_pkt->data; line_len = data_pkt->len; } while (line_len > 0) { error = git_pkt_parse_line(&pkt, line, &line_end, line_len); if (error == GIT_EBUFS) { /* Buffer the data when the inner packet is split * across multiple sideband packets */ if (!reading_from_buf) git_buf_put(data_pkt_buf, line, line_len); error = 0; goto done; } else if (error < 0) goto done; /* Advance in the buffer */ line_len -= (line_end - line); line = line_end; /* When a valid packet with no content has been * read, git_pkt_parse_line does not report an * error, but the pkt pointer has not been set. * Handle this by skipping over empty packets. */ if (pkt == NULL) continue; error = add_push_report_pkt(push, pkt); git_pkt_free(pkt); if (error < 0 && error != GIT_ITEROVER) goto done; } error = 0; done: if (reading_from_buf) git_buf_consume(data_pkt_buf, line_end); return error; } Commit Message: smart_pkt: treat empty packet lines as error The Git protocol does not specify what should happen in the case of an empty packet line (that is a packet line "0004"). We currently indicate success, but do not return a packet in the case where we hit an empty line. The smart protocol was not prepared to handle such packets in all cases, though, resulting in a `NULL` pointer dereference. Fix the issue by returning an error instead. As such kind of packets is not even specified by upstream, this is the right thing to do. CWE ID: CWE-476
static int add_push_report_sideband_pkt(git_push *push, git_pkt_data *data_pkt, git_buf *data_pkt_buf) { git_pkt *pkt; const char *line, *line_end; size_t line_len; int error; int reading_from_buf = data_pkt_buf->size > 0; if (reading_from_buf) { /* We had an existing partial packet, so add the new * packet to the buffer and parse the whole thing */ git_buf_put(data_pkt_buf, data_pkt->data, data_pkt->len); line = data_pkt_buf->ptr; line_len = data_pkt_buf->size; } else { line = data_pkt->data; line_len = data_pkt->len; } while (line_len > 0) { error = git_pkt_parse_line(&pkt, line, &line_end, line_len); if (error == GIT_EBUFS) { /* Buffer the data when the inner packet is split * across multiple sideband packets */ if (!reading_from_buf) git_buf_put(data_pkt_buf, line, line_len); error = 0; goto done; } else if (error < 0) goto done; /* Advance in the buffer */ line_len -= (line_end - line); line = line_end; error = add_push_report_pkt(push, pkt); git_pkt_free(pkt); if (error < 0 && error != GIT_ITEROVER) goto done; } error = 0; done: if (reading_from_buf) git_buf_consume(data_pkt_buf, line_end); return error; }
170,110
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } { zend_object_iterator *iterator; iterator = (zend_object_iterator*) spl_filesystem_object_to_iterator(intern); if (iterator->data != NULL) { iterator->data = NULL; iterator->funcs->dtor(iterator TSRMLS_CC); } } efree(object); } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } { zend_object_iterator *iterator; iterator = (zend_object_iterator*) spl_filesystem_object_to_iterator(intern); if (iterator->data != NULL) { iterator->data = NULL; iterator->funcs->dtor(iterator TSRMLS_CC); } } efree(object); } /* }}} */
167,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option) { ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option); Mutex::Autolock lock(mLock); Mutex::Autolock glock(sLock); mThumbnail.clear(); if (mRetriever == NULL) { ALOGE("retriever is not initialized"); return NULL; } VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option); if (frame == NULL) { ALOGE("failed to capture a video frame"); return NULL; } size_t size = sizeof(VideoFrame) + frame->mSize; sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient"); if (heap == NULL) { ALOGE("failed to create MemoryDealer"); delete frame; return NULL; } mThumbnail = new MemoryBase(heap, 0, size); if (mThumbnail == NULL) { ALOGE("not enough memory for VideoFrame size=%u", size); delete frame; return NULL; } VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer()); frameCopy->mWidth = frame->mWidth; frameCopy->mHeight = frame->mHeight; frameCopy->mDisplayWidth = frame->mDisplayWidth; frameCopy->mDisplayHeight = frame->mDisplayHeight; frameCopy->mSize = frame->mSize; frameCopy->mRotationAngle = frame->mRotationAngle; ALOGV("rotation: %d", frameCopy->mRotationAngle); frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame); memcpy(frameCopy->mData, frame->mData, frame->mSize); delete frame; // Fix memory leakage return mThumbnail; } Commit Message: Clear unused pointer field when sending across binder Bug: 28377502 Change-Id: Iad5ebfb0a9ef89f09755bb332579dbd3534f9c98 CWE ID: CWE-20
sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option) { ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option); Mutex::Autolock lock(mLock); Mutex::Autolock glock(sLock); mThumbnail.clear(); if (mRetriever == NULL) { ALOGE("retriever is not initialized"); return NULL; } VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option); if (frame == NULL) { ALOGE("failed to capture a video frame"); return NULL; } size_t size = sizeof(VideoFrame) + frame->mSize; sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient"); if (heap == NULL) { ALOGE("failed to create MemoryDealer"); delete frame; return NULL; } mThumbnail = new MemoryBase(heap, 0, size); if (mThumbnail == NULL) { ALOGE("not enough memory for VideoFrame size=%u", size); delete frame; return NULL; } VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer()); frameCopy->mWidth = frame->mWidth; frameCopy->mHeight = frame->mHeight; frameCopy->mDisplayWidth = frame->mDisplayWidth; frameCopy->mDisplayHeight = frame->mDisplayHeight; frameCopy->mSize = frame->mSize; frameCopy->mRotationAngle = frame->mRotationAngle; ALOGV("rotation: %d", frameCopy->mRotationAngle); frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame); memcpy(frameCopy->mData, frame->mData, frame->mSize); frameCopy->mData = 0; delete frame; // Fix memory leakage return mThumbnail; }
173,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int svc_rdma_bc_sendto(struct svcxprt_rdma *rdma, struct rpc_rqst *rqst) { struct xdr_buf *sndbuf = &rqst->rq_snd_buf; struct svc_rdma_op_ctxt *ctxt; struct svc_rdma_req_map *vec; struct ib_send_wr send_wr; int ret; vec = svc_rdma_get_req_map(rdma); ret = svc_rdma_map_xdr(rdma, sndbuf, vec, false); if (ret) goto out_err; ret = svc_rdma_repost_recv(rdma, GFP_NOIO); if (ret) goto out_err; ctxt = svc_rdma_get_context(rdma); ctxt->pages[0] = virt_to_page(rqst->rq_buffer); ctxt->count = 1; ctxt->direction = DMA_TO_DEVICE; ctxt->sge[0].lkey = rdma->sc_pd->local_dma_lkey; ctxt->sge[0].length = sndbuf->len; ctxt->sge[0].addr = ib_dma_map_page(rdma->sc_cm_id->device, ctxt->pages[0], 0, sndbuf->len, DMA_TO_DEVICE); if (ib_dma_mapping_error(rdma->sc_cm_id->device, ctxt->sge[0].addr)) { ret = -EIO; goto out_unmap; } svc_rdma_count_mappings(rdma, ctxt); memset(&send_wr, 0, sizeof(send_wr)); ctxt->cqe.done = svc_rdma_wc_send; send_wr.wr_cqe = &ctxt->cqe; send_wr.sg_list = ctxt->sge; send_wr.num_sge = 1; send_wr.opcode = IB_WR_SEND; send_wr.send_flags = IB_SEND_SIGNALED; ret = svc_rdma_send(rdma, &send_wr); if (ret) { ret = -EIO; goto out_unmap; } out_err: svc_rdma_put_req_map(rdma, vec); dprintk("svcrdma: %s returns %d\n", __func__, ret); return ret; out_unmap: svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 1); goto out_err; } 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
static int svc_rdma_bc_sendto(struct svcxprt_rdma *rdma, struct rpc_rqst *rqst) { struct svc_rdma_op_ctxt *ctxt; int ret; ctxt = svc_rdma_get_context(rdma); /* rpcrdma_bc_send_request builds the transport header and * the backchannel RPC message in the same buffer. Thus only * one SGE is needed to send both. */ ret = svc_rdma_map_reply_hdr(rdma, ctxt, rqst->rq_buffer, rqst->rq_snd_buf.len); if (ret < 0) goto out_err; ret = svc_rdma_repost_recv(rdma, GFP_NOIO); if (ret) goto out_err; ret = svc_rdma_post_send_wr(rdma, ctxt, 1, 0); if (ret) goto out_unmap; out_err: dprintk("svcrdma: %s returns %d\n", __func__, ret); return ret; out_unmap: svc_rdma_unmap_dma(ctxt); svc_rdma_put_context(ctxt, 1); ret = -EIO; goto out_err; }
168,157
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, priv->cac_id_len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); } Commit Message: fixed out of bounds writes Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting the problems. CWE ID: CWE-415
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial) { cac_private_data_t * priv = CAC_DATA(card); SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL); if (card->serialnr.len) { *serial = card->serialnr; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } if (priv->cac_id_len) { serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR); memcpy(serial->value, priv->cac_id, serial->len); SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_SUCCESS); } SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, SC_ERROR_FILE_NOT_FOUND); }
169,071
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void scsi_read_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->sector_count == (uint32_t)-1) { DPRINTF("Read buf_len=%zd\n", r->iov.iov_len); r->sector_count = 0; scsi_req_data(&r->req, r->iov.iov_len); return; } DPRINTF("Read sector_count=%d\n", r->sector_count); if (r->sector_count == 0) { /* This also clears the sense buffer for REQUEST SENSE. */ scsi_req_complete(&r->req, GOOD); return; } /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_read_complete(r, -EINVAL); return; } n = r->sector_count; if (n > SCSI_DMA_BUF_SIZE / 512) n = SCSI_DMA_BUF_SIZE / 512; if (s->tray_open) { scsi_read_complete(r, -ENOMEDIUM); } r->iov.iov_len = n * 512; qemu_iovec_init_external(&r->qiov, &r->iov, 1); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n, scsi_read_complete, r); if (r->req.aiocb == NULL) { scsi_read_complete(r, -EIO); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static void scsi_read_data(SCSIRequest *req) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->sector_count == (uint32_t)-1) { DPRINTF("Read buf_len=%zd\n", r->iov.iov_len); r->sector_count = 0; scsi_req_data(&r->req, r->iov.iov_len); return; } DPRINTF("Read sector_count=%d\n", r->sector_count); if (r->sector_count == 0) { /* This also clears the sense buffer for REQUEST SENSE. */ scsi_req_complete(&r->req, GOOD); return; } /* No data transfer may already be in progress */ assert(r->req.aiocb == NULL); if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { DPRINTF("Data transfer direction invalid\n"); scsi_read_complete(r, -EINVAL); return; } if (s->tray_open) { scsi_read_complete(r, -ENOMEDIUM); } n = scsi_init_iovec(r); bdrv_acct_start(s->bs, &r->acct, n * BDRV_SECTOR_SIZE, BDRV_ACCT_READ); r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n, scsi_read_complete, r); if (r->req.aiocb == NULL) { scsi_read_complete(r, -EIO); } }
169,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame), logging_state_active_(false), was_username_autofilled_(false), was_password_autofilled_(false), weak_ptr_factory_(this) { Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id())); } Commit Message: Remove WeakPtrFactory from PasswordAutofillAgent Unlike in AutofillAgent, the factory is no longer used in PAA. [email protected] BUG=609010,609007,608100,608101,433486 Review-Url: https://codereview.chromium.org/1945723003 Cr-Commit-Position: refs/heads/master@{#391475} CWE ID:
PasswordAutofillAgent::PasswordAutofillAgent(content::RenderFrame* render_frame) : content::RenderFrameObserver(render_frame), logging_state_active_(false), was_username_autofilled_(false), was_password_autofilled_(false) { Send(new AutofillHostMsg_PasswordAutofillAgentConstructed(routing_id())); }
173,334
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeOSCancelHandwriting(InputMethodStatusConnection* connection, int n_strokes) { g_return_if_fail(connection); connection->CancelHandwriting(n_strokes); } 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
void ChromeOSCancelHandwriting(InputMethodStatusConnection* connection, IBusController::~IBusController() { }
170,520
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GDataFileSystem::OnCopyDocumentCompleted( const FilePath& dir_path, const FileOperationCallback& callback, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); GDataFileError error = util::GDataToGDataFileError(status); if (error != GDATA_FILE_OK) { callback.Run(error); return; } scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (!doc_entry.get()) { callback.Run(GDATA_FILE_ERROR_FAILED); return; } GDataEntry* entry = GDataEntry::FromDocumentEntry( NULL, doc_entry.get(), directory_service_.get()); if (!entry) { callback.Run(GDATA_FILE_ERROR_FAILED); return; } directory_service_->root()->AddEntry(entry); MoveEntryFromRootDirectory(dir_path, callback, GDATA_FILE_OK, entry->GetFilePath()); } Commit Message: Remove parent* arg from GDataEntry ctor. * Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry. * Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry. * Add GDataDirectoryService::FromDocumentEntry and use this everywhere. * Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and CreateGDataDirectory. Make GDataEntry ctor protected. BUG=141494 TEST=unit tests. Review URL: https://chromiumcodereview.appspot.com/10854083 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GDataFileSystem::OnCopyDocumentCompleted( const FilePath& dir_path, const FileOperationCallback& callback, GDataErrorCode status, scoped_ptr<base::Value> data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(!callback.is_null()); GDataFileError error = util::GDataToGDataFileError(status); if (error != GDATA_FILE_OK) { callback.Run(error); return; } scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data)); if (!doc_entry.get()) { callback.Run(GDATA_FILE_ERROR_FAILED); return; } GDataEntry* entry = directory_service_->FromDocumentEntry(doc_entry.get()); if (!entry) { callback.Run(GDATA_FILE_ERROR_FAILED); return; } directory_service_->root()->AddEntry(entry); MoveEntryFromRootDirectory(dir_path, callback, GDATA_FILE_OK, entry->GetFilePath()); }
171,481
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; scale_factor = 1.0f; rasterize_pdf = false; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = blink::kWebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; title = base::string16(); url = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; } Commit Message: DevTools: allow styling the page number element when printing over the protocol. Bug: none Change-Id: I13e6afbd86a7c6bcdedbf0645183194b9de7cfb4 Reviewed-on: https://chromium-review.googlesource.com/809759 Commit-Queue: Pavel Feldman <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: Tom Sepez <[email protected]> Reviewed-by: Jianzhou Feng <[email protected]> Cr-Commit-Position: refs/heads/master@{#523966} CWE ID: CWE-20
void PrintMsg_Print_Params::Reset() { page_size = gfx::Size(); content_size = gfx::Size(); printable_area = gfx::Rect(); margin_top = 0; margin_left = 0; dpi = 0; scale_factor = 1.0f; rasterize_pdf = false; document_cookie = 0; selection_only = false; supports_alpha_blend = false; preview_ui_id = -1; preview_request_id = 0; is_first_request = false; print_scaling_option = blink::kWebPrintScalingOptionSourceSize; print_to_pdf = false; display_header_footer = false; title = base::string16(); url = base::string16(); header_template = base::string16(); footer_template = base::string16(); should_print_backgrounds = false; printed_doc_type = printing::SkiaDocumentType::PDF; }
172,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); } Commit Message: CWE ID: CWE-189
create_bits (pixman_format_code_t format, int width, int height, int * rowstride_bytes, pixman_bool_t clear) { int stride; size_t buf_size; int bpp; /* what follows is a long-winded way, avoiding any possibility of integer * overflows, of saying: * stride = ((width * bpp + 0x1f) >> 5) * sizeof (uint32_t); */ bpp = PIXMAN_FORMAT_BPP (format); if (_pixman_multiply_overflows_int (width, bpp)) return NULL; stride = width * bpp; if (_pixman_addition_overflows_int (stride, 0x1f)) return NULL; stride += 0x1f; stride >>= 5; stride *= sizeof (uint32_t); if (_pixman_multiply_overflows_size (height, stride)) return NULL; buf_size = (size_t)height * stride; if (rowstride_bytes) *rowstride_bytes = stride; if (clear) return calloc (buf_size, 1); else return malloc (buf_size); }
165,337
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lrmd_remote_client_msg(gpointer data) { int id = 0; int rc = 0; int disconnected = 0; xmlNode *request = NULL; crm_client_t *client = data; if (client->remote->tls_handshake_complete == FALSE) { int rc = 0; /* Muliple calls to handshake will be required, this callback * will be invoked once the client sends more handshake data. */ do { rc = gnutls_handshake(*client->remote->tls_session); if (rc < 0 && rc != GNUTLS_E_AGAIN) { crm_err("Remote lrmd tls handshake failed"); return -1; } } while (rc == GNUTLS_E_INTERRUPTED); if (rc == 0) { crm_debug("Remote lrmd tls handshake completed"); client->remote->tls_handshake_complete = TRUE; if (client->remote->auth_timeout) { g_source_remove(client->remote->auth_timeout); } client->remote->auth_timeout = 0; } return 0; } rc = crm_remote_ready(client->remote, 0); if (rc == 0) { /* no msg to read */ return 0; } else if (rc < 0) { crm_info("Client disconnected during remote client read"); return -1; } crm_remote_recv(client->remote, -1, &disconnected); request = crm_remote_parse_buffer(client->remote); while (request) { crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id); crm_trace("processing request from remote client with remote msg id %d", id); if (!client->name) { const char *value = crm_element_value(request, F_LRMD_CLIENTNAME); if (value) { client->name = strdup(value); } } lrmd_call_id++; if (lrmd_call_id < 1) { lrmd_call_id = 1; } crm_xml_add(request, F_LRMD_CLIENTID, client->id); crm_xml_add(request, F_LRMD_CLIENTNAME, client->name); crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id); process_lrmd_message(client, id, request); free_xml(request); /* process all the messages in the current buffer */ request = crm_remote_parse_buffer(client->remote); } if (disconnected) { crm_info("Client disconnect detected in tls msg dispatcher."); return -1; } return 0; } Commit Message: Fix: remote: cl#5269 - Notify other clients of a new connection only if the handshake has completed (bsc#967388) CWE ID: CWE-254
lrmd_remote_client_msg(gpointer data) { int id = 0; int rc = 0; int disconnected = 0; xmlNode *request = NULL; crm_client_t *client = data; if (client->remote->tls_handshake_complete == FALSE) { int rc = 0; /* Muliple calls to handshake will be required, this callback * will be invoked once the client sends more handshake data. */ do { rc = gnutls_handshake(*client->remote->tls_session); if (rc < 0 && rc != GNUTLS_E_AGAIN) { crm_err("Remote lrmd tls handshake failed"); return -1; } } while (rc == GNUTLS_E_INTERRUPTED); if (rc == 0) { crm_debug("Remote lrmd tls handshake completed"); client->remote->tls_handshake_complete = TRUE; if (client->remote->auth_timeout) { g_source_remove(client->remote->auth_timeout); } client->remote->auth_timeout = 0; /* Alert other clients of the new connection */ notify_of_new_client(client); } return 0; } rc = crm_remote_ready(client->remote, 0); if (rc == 0) { /* no msg to read */ return 0; } else if (rc < 0) { crm_info("Client disconnected during remote client read"); return -1; } crm_remote_recv(client->remote, -1, &disconnected); request = crm_remote_parse_buffer(client->remote); while (request) { crm_element_value_int(request, F_LRMD_REMOTE_MSG_ID, &id); crm_trace("processing request from remote client with remote msg id %d", id); if (!client->name) { const char *value = crm_element_value(request, F_LRMD_CLIENTNAME); if (value) { client->name = strdup(value); } } lrmd_call_id++; if (lrmd_call_id < 1) { lrmd_call_id = 1; } crm_xml_add(request, F_LRMD_CLIENTID, client->id); crm_xml_add(request, F_LRMD_CLIENTNAME, client->name); crm_xml_add_int(request, F_LRMD_CALLID, lrmd_call_id); process_lrmd_message(client, id, request); free_xml(request); /* process all the messages in the current buffer */ request = crm_remote_parse_buffer(client->remote); } if (disconnected) { crm_info("Client disconnect detected in tls msg dispatcher."); return -1; } return 0; }
168,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } Commit Message: sg_start_req(): make sure that there's not too many elements in iovec unfortunately, allowing an arbitrary 16bit value means a possibility of overflow in the calculation of total number of pages in bio_map_user_iov() - we rely on there being no more than PAGE_SIZE members of sum in the first loop there. If that sum wraps around, we end up allocating too small array of pointers to pages and it's easy to overflow it in the second loop. X-Coverup: TINC (and there's no lumber cartel either) Cc: [email protected] # way, way back Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-189
sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; unsigned char *long_cmdp = NULL; SCSI_LOG_TIMEOUT(4, sg_printk(KERN_INFO, sfp->parentdp, "sg_start_req: dxfer_len=%d\n", dxfer_len)); if (hp->cmd_len > BLK_MAX_CDB) { long_cmdp = kzalloc(hp->cmd_len, GFP_KERNEL); if (!long_cmdp) return -ENOMEM; } /* * NOTE * * With scsi-mq enabled, there are a fixed number of preallocated * requests equal in number to shost->can_queue. If all of the * preallocated requests are already in use, then using GFP_ATOMIC with * blk_get_request() will return -EWOULDBLOCK, whereas using GFP_KERNEL * will cause blk_get_request() to sleep until an active command * completes, freeing up a request. Neither option is ideal, but * GFP_KERNEL is the better choice to prevent userspace from getting an * unexpected EWOULDBLOCK. * * With scsi-mq disabled, blk_get_request() with GFP_KERNEL usually * does not sleep except under memory pressure. */ rq = blk_get_request(q, rw, GFP_KERNEL); if (IS_ERR(rq)) { kfree(long_cmdp); return PTR_ERR(rq); } blk_rq_set_block_pc(rq); if (hp->cmd_len > BLK_MAX_CDB) rq->cmd = long_cmdp; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (unlikely(iov_count > MAX_UIOVEC)) return -EINVAL; if (iov_count) { int size = sizeof(struct iovec) * iov_count; struct iovec *iov; struct iov_iter i; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); iov_iter_init(&i, rw, iov, iov_count, min_t(size_t, hp->dxfer_len, iov_length(iov, iov_count))); res = blk_rq_map_user_iov(q, rq, md, &i, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; }
166,593
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfs3svc_decode_readdirplusargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { int len; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ntohl(*p++); args->count = ntohl(*p++); len = args->count = min(args->count, max_blocksize); while (len > 0) { struct page *p = *(rqstp->rq_next_page++); if (!args->buffer) args->buffer = page_address(p); len -= PAGE_SIZE; } 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_readdirplusargs(struct svc_rqst *rqstp, __be32 *p, struct nfsd3_readdirargs *args) { int len; u32 max_blocksize = svc_max_payload(rqstp); p = decode_fh(p, &args->fh); if (!p) return 0; p = xdr_decode_hyper(p, &args->cookie); args->verf = p; p += 2; args->dircount = ntohl(*p++); args->count = ntohl(*p++); if (!xdr_argsize_check(rqstp, p)) return 0; len = args->count = min(args->count, max_blocksize); while (len > 0) { struct page *p = *(rqstp->rq_next_page++); if (!args->buffer) args->buffer = page_address(p); len -= PAGE_SIZE; } return 1; }
168,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AddInitialUrlToPreconnectPrediction(const GURL& initial_url, PreconnectPrediction* prediction) { GURL initial_origin = initial_url.GetOrigin(); static const int kMinSockets = 2; if (!prediction->requests.empty() && prediction->requests.front().origin == initial_origin) { prediction->requests.front().num_sockets = std::max(prediction->requests.front().num_sockets, kMinSockets); } else if (initial_origin.is_valid() && initial_origin.SchemeIsHTTPOrHTTPS()) { url::Origin origin = url::Origin::Create(initial_origin); prediction->requests.emplace(prediction->requests.begin(), initial_origin, kMinSockets, net::NetworkIsolationKey(origin, origin)); } return !prediction->requests.empty(); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <[email protected]> Reviewed-by: Alex Ilin <[email protected]> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
bool AddInitialUrlToPreconnectPrediction(const GURL& initial_url, PreconnectPrediction* prediction) { url::Origin initial_origin = url::Origin::Create(initial_url); static const int kMinSockets = 2; if (!prediction->requests.empty() && prediction->requests.front().origin == initial_origin) { prediction->requests.front().num_sockets = std::max(prediction->requests.front().num_sockets, kMinSockets); } else if (!initial_origin.opaque() && (initial_origin.scheme() == url::kHttpScheme || initial_origin.scheme() == url::kHttpsScheme)) { prediction->requests.emplace( prediction->requests.begin(), initial_origin, kMinSockets, net::NetworkIsolationKey(initial_origin, initial_origin)); } return !prediction->requests.empty(); }
172,369
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserPolicyConnector::DeviceStopAutoRetry() { #if defined(OS_CHROMEOS) if (device_cloud_policy_subsystem_.get()) device_cloud_policy_subsystem_->StopAutoRetry(); #endif } Commit Message: Reset the device policy machinery upon retrying enrollment. BUG=chromium-os:18208 TEST=See bug description Review URL: http://codereview.chromium.org/7676005 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void BrowserPolicyConnector::DeviceStopAutoRetry() { void BrowserPolicyConnector::ResetDevicePolicy() { #if defined(OS_CHROMEOS) if (device_cloud_policy_subsystem_.get()) device_cloud_policy_subsystem_->Reset(); #endif }
170,279
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Chapters::Atom::Init() { m_string_uid = NULL; m_uid = 0; m_start_timecode = -1; m_stop_timecode = -1; m_displays = NULL; m_displays_size = 0; m_displays_count = 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Atom::Init()
174,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } Commit Message: iFixed bug #72446 - Integer Overflow in gdImagePaletteToTrueColor() resulting in heap overflow CWE ID: CWE-190
void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } }
167,125