instruction
stringclasses
1 value
input
stringlengths
90
139k
output
stringlengths
16
138k
__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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateIntArray( int64_t *numbers, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateInt( numbers[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateIntArray( int64_t *numbers, int count )
167,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } if (cmdCode == EFFECT_CMD_GET_PARAM && (*replySize < sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) { android_errorWriteLog(0x534e4554, "29251553"); return -EINVAL; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; } Commit Message: Add EFFECT_CMD_SET_PARAM parameter checking Bug: 30204301 Change-Id: Ib9c3ee1c2f23c96f8f7092dd9e146bc453d7a290 (cherry picked from commit e4a1d91501d47931dbae19c47815952378787ab6) CWE ID: CWE-200
status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, uint32_t cmdSize, void *pCmdData, uint32_t *replySize, void *pReplyData) { Mutex::Autolock _l(mLock); ALOGVV("command(), cmdCode: %d, mEffectInterface: %p", cmdCode, mEffectInterface); if (mState == DESTROYED || mEffectInterface == NULL) { return NO_INIT; } if (mStatus != NO_ERROR) { return mStatus; } if (cmdCode == EFFECT_CMD_GET_PARAM && (*replySize < sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->psize > *replySize - sizeof(effect_param_t))) { android_errorWriteLog(0x534e4554, "29251553"); return -EINVAL; } if ((cmdCode == EFFECT_CMD_SET_PARAM || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) && // DEFERRED not generally used (sizeof(effect_param_t) > cmdSize || ((effect_param_t *)pCmdData)->psize > cmdSize - sizeof(effect_param_t) || ((effect_param_t *)pCmdData)->vsize > cmdSize - sizeof(effect_param_t) - ((effect_param_t *)pCmdData)->psize || roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) > cmdSize - sizeof(effect_param_t) - ((effect_param_t *)pCmdData)->psize - ((effect_param_t *)pCmdData)->vsize)) { android_errorWriteLog(0x534e4554, "30204301"); return -EINVAL; } status_t status = (*mEffectInterface)->command(mEffectInterface, cmdCode, cmdSize, pCmdData, replySize, pReplyData); if (cmdCode != EFFECT_CMD_GET_PARAM && status == NO_ERROR) { uint32_t size = (replySize == NULL) ? 0 : *replySize; for (size_t i = 1; i < mHandles.size(); i++) { EffectHandle *h = mHandles[i]; if (h != NULL && !h->destroyed_l()) { h->commandExecuted(cmdCode, cmdSize, pCmdData, size, pReplyData); } } } return status; }
173,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *check_secret(int module, const char *user, const char *group, const char *challenge, const char *pass) { char line[1024]; char pass2[MAX_DIGEST_LEN*2]; const char *fname = lp_secrets_file(module); STRUCT_STAT st; int fd, ok = 1; int user_len = strlen(user); int group_len = group ? strlen(group) : 0; char *err; if (!fname || !*fname || (fd = open(fname, O_RDONLY)) < 0) return "no secrets file"; if (do_fstat(fd, &st) == -1) { rsyserr(FLOG, errno, "fstat(%s)", fname); ok = 0; } else if (lp_strict_modes(module)) { rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n"); ok = 0; } else if (MY_UID() == 0 && st.st_uid != 0) { rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n"); ok = 0; } } Commit Message: CWE ID: CWE-20
static const char *check_secret(int module, const char *user, const char *group, const char *challenge, const char *pass) { char line[1024]; char pass2[MAX_DIGEST_LEN*2]; const char *fname = lp_secrets_file(module); STRUCT_STAT st; int ok = 1; int user_len = strlen(user); int group_len = group ? strlen(group) : 0; char *err; FILE *fh; if (!fname || !*fname || (fh = fopen(fname, "r")) == NULL) return "no secrets file"; if (do_fstat(fileno(fh), &st) == -1) { rsyserr(FLOG, errno, "fstat(%s)", fname); ok = 0; } else if (lp_strict_modes(module)) { rprintf(FLOG, "secrets file must not be other-accessible (see strict modes option)\n"); ok = 0; } else if (MY_UID() == 0 && st.st_uid != 0) { rprintf(FLOG, "secrets file must be owned by root when running as root (see strict modes)\n"); ok = 0; } }
165,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } Commit Message: Slightly different fix for #714 CWE ID: CWE-834
static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); }
170,016
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: init_global_keywords(bool global_active) { /* global definitions mapping */ install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active); #if HAVE_DECL_CLONE_NEWNET install_keyword_root("net_namespace", &net_namespace_handler, global_active); install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active); #endif install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active); install_keyword_root("instance", &instance_handler, global_active); install_keyword_root("child_wait_time", &child_wait_handler, global_active); install_keyword_root("global_defs", NULL, global_active); install_keyword("router_id", &routerid_handler); install_keyword("notification_email_from", &emailfrom_handler); install_keyword("smtp_server", &smtpserver_handler); install_keyword("smtp_helo_name", &smtphelo_handler); install_keyword("smtp_connect_timeout", &smtpto_handler); install_keyword("notification_email", &email_handler); install_keyword("smtp_alert", &smtp_alert_handler); #ifdef _WITH_VRRP_ install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler); #endif #ifdef _WITH_LVS_ install_keyword("smtp_alert_checker", &smtp_alert_checker_handler); #endif #ifdef _WITH_VRRP_ install_keyword("dynamic_interfaces", &dynamic_interfaces_handler); install_keyword("no_email_faults", &no_email_faults_handler); install_keyword("default_interface", &default_interface_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_timeouts", &lvs_timeouts); install_keyword("lvs_flush", &lvs_flush_handler); #ifdef _WITH_VRRP_ install_keyword("lvs_sync_daemon", &lvs_syncd_handler); #endif #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler); install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler); install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler); install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler); install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler); install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler); install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler); install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler); install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler); install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler); install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler); install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler); install_keyword("vrrp_version", &vrrp_version_handler); install_keyword("vrrp_iptables", &vrrp_iptables_handler); #ifdef _HAVE_LIBIPSET_ install_keyword("vrrp_ipsets", &vrrp_ipsets_handler); #endif install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler); install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler); install_keyword("vrrp_strict", &vrrp_strict_handler); install_keyword("vrrp_priority", &vrrp_prio_handler); install_keyword("vrrp_no_swap", &vrrp_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler); #endif #endif #endif install_keyword("notify_fifo", &global_notify_fifo); install_keyword("notify_fifo_script", &global_notify_fifo_script); #ifdef _WITH_VRRP_ install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo); install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script); #endif #ifdef _WITH_LVS_ install_keyword("lvs_notify_fifo", &lvs_notify_fifo); install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script); install_keyword("checker_priority", &checker_prio_handler); install_keyword("checker_no_swap", &checker_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("checker_rt_priority", &checker_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_BFD_ install_keyword("bfd_priority", &bfd_prio_handler); install_keyword("bfd_no_swap", &bfd_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("bfd_rt_priority", &bfd_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_SNMP_ install_keyword("snmp_socket", &snmp_socket_handler); install_keyword("enable_traps", &trap_handler); #ifdef _WITH_SNMP_VRRP_ install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler); install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */ #endif #ifdef _WITH_SNMP_RFC_ install_keyword("enable_snmp_rfc", &snmp_rfc_handler); #endif #ifdef _WITH_SNMP_RFCV2_ install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler); #endif #ifdef _WITH_SNMP_RFCV3_ install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler); #endif #ifdef _WITH_SNMP_CHECKER_ install_keyword("enable_snmp_checker", &snmp_checker_handler); #endif #endif #ifdef _WITH_DBUS_ install_keyword("enable_dbus", &enable_dbus_handler); install_keyword("dbus_service_name", &dbus_service_name_handler); #endif install_keyword("script_user", &script_user_handler); install_keyword("enable_script_security", &script_security_handler); #ifdef _WITH_VRRP_ install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler); install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler); install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler); install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler); install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("rs_init_notifies", &rs_init_notifies_handler); install_keyword("no_checker_emails", &no_checker_emails_handler); #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler); install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler); #endif } Commit Message: Add command line and configuration option to set umask Issue #1048 identified that files created by keepalived are created with mode 0666. This commit changes the default to 0644, and also allows the umask to be specified in the configuration or as a command line option. Signed-off-by: Quentin Armitage <[email protected]> CWE ID: CWE-200
init_global_keywords(bool global_active) { /* global definitions mapping */ install_keyword_root("linkbeat_use_polling", use_polling_handler, global_active); #if HAVE_DECL_CLONE_NEWNET install_keyword_root("net_namespace", &net_namespace_handler, global_active); install_keyword_root("namespace_with_ipsets", &namespace_ipsets_handler, global_active); #endif install_keyword_root("use_pid_dir", &use_pid_dir_handler, global_active); install_keyword_root("instance", &instance_handler, global_active); install_keyword_root("child_wait_time", &child_wait_handler, global_active); install_keyword_root("global_defs", NULL, global_active); install_keyword("router_id", &routerid_handler); install_keyword("notification_email_from", &emailfrom_handler); install_keyword("smtp_server", &smtpserver_handler); install_keyword("smtp_helo_name", &smtphelo_handler); install_keyword("smtp_connect_timeout", &smtpto_handler); install_keyword("notification_email", &email_handler); install_keyword("smtp_alert", &smtp_alert_handler); #ifdef _WITH_VRRP_ install_keyword("smtp_alert_vrrp", &smtp_alert_vrrp_handler); #endif #ifdef _WITH_LVS_ install_keyword("smtp_alert_checker", &smtp_alert_checker_handler); #endif #ifdef _WITH_VRRP_ install_keyword("dynamic_interfaces", &dynamic_interfaces_handler); install_keyword("no_email_faults", &no_email_faults_handler); install_keyword("default_interface", &default_interface_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_timeouts", &lvs_timeouts); install_keyword("lvs_flush", &lvs_flush_handler); #ifdef _WITH_VRRP_ install_keyword("lvs_sync_daemon", &lvs_syncd_handler); #endif #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_mcast_group4", &vrrp_mcast_group4_handler); install_keyword("vrrp_mcast_group6", &vrrp_mcast_group6_handler); install_keyword("vrrp_garp_master_delay", &vrrp_garp_delay_handler); install_keyword("vrrp_garp_master_repeat", &vrrp_garp_rep_handler); install_keyword("vrrp_garp_master_refresh", &vrrp_garp_refresh_handler); install_keyword("vrrp_garp_master_refresh_repeat", &vrrp_garp_refresh_rep_handler); install_keyword("vrrp_garp_lower_prio_delay", &vrrp_garp_lower_prio_delay_handler); install_keyword("vrrp_garp_lower_prio_repeat", &vrrp_garp_lower_prio_rep_handler); install_keyword("vrrp_garp_interval", &vrrp_garp_interval_handler); install_keyword("vrrp_gna_interval", &vrrp_gna_interval_handler); install_keyword("vrrp_lower_prio_no_advert", &vrrp_lower_prio_no_advert_handler); install_keyword("vrrp_higher_prio_send_advert", &vrrp_higher_prio_send_advert_handler); install_keyword("vrrp_version", &vrrp_version_handler); install_keyword("vrrp_iptables", &vrrp_iptables_handler); #ifdef _HAVE_LIBIPSET_ install_keyword("vrrp_ipsets", &vrrp_ipsets_handler); #endif install_keyword("vrrp_check_unicast_src", &vrrp_check_unicast_src_handler); install_keyword("vrrp_skip_check_adv_addr", &vrrp_check_adv_addr_handler); install_keyword("vrrp_strict", &vrrp_strict_handler); install_keyword("vrrp_priority", &vrrp_prio_handler); install_keyword("vrrp_no_swap", &vrrp_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("vrrp_rt_priority", &vrrp_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("vrrp_rlimit_rtime", &vrrp_rt_rlimit_handler); #endif #endif #endif install_keyword("notify_fifo", &global_notify_fifo); install_keyword("notify_fifo_script", &global_notify_fifo_script); #ifdef _WITH_VRRP_ install_keyword("vrrp_notify_fifo", &vrrp_notify_fifo); install_keyword("vrrp_notify_fifo_script", &vrrp_notify_fifo_script); #endif #ifdef _WITH_LVS_ install_keyword("lvs_notify_fifo", &lvs_notify_fifo); install_keyword("lvs_notify_fifo_script", &lvs_notify_fifo_script); install_keyword("checker_priority", &checker_prio_handler); install_keyword("checker_no_swap", &checker_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("checker_rt_priority", &checker_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("checker_rlimit_rtime", &checker_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_BFD_ install_keyword("bfd_priority", &bfd_prio_handler); install_keyword("bfd_no_swap", &bfd_no_swap_handler); #ifdef _HAVE_SCHED_RT_ install_keyword("bfd_rt_priority", &bfd_rt_priority_handler); #if HAVE_DECL_RLIMIT_RTTIME == 1 install_keyword("bfd_rlimit_rtime", &bfd_rt_rlimit_handler); #endif #endif #endif #ifdef _WITH_SNMP_ install_keyword("snmp_socket", &snmp_socket_handler); install_keyword("enable_traps", &trap_handler); #ifdef _WITH_SNMP_VRRP_ install_keyword("enable_snmp_vrrp", &snmp_vrrp_handler); install_keyword("enable_snmp_keepalived", &snmp_vrrp_handler); /* Deprecated v2.0.0 */ #endif #ifdef _WITH_SNMP_RFC_ install_keyword("enable_snmp_rfc", &snmp_rfc_handler); #endif #ifdef _WITH_SNMP_RFCV2_ install_keyword("enable_snmp_rfcv2", &snmp_rfcv2_handler); #endif #ifdef _WITH_SNMP_RFCV3_ install_keyword("enable_snmp_rfcv3", &snmp_rfcv3_handler); #endif #ifdef _WITH_SNMP_CHECKER_ install_keyword("enable_snmp_checker", &snmp_checker_handler); #endif #endif #ifdef _WITH_DBUS_ install_keyword("enable_dbus", &enable_dbus_handler); install_keyword("dbus_service_name", &dbus_service_name_handler); #endif install_keyword("script_user", &script_user_handler); install_keyword("enable_script_security", &script_security_handler); #ifdef _WITH_VRRP_ install_keyword("vrrp_netlink_cmd_rcv_bufs", &vrrp_netlink_cmd_rcv_bufs_handler); install_keyword("vrrp_netlink_cmd_rcv_bufs_force", &vrrp_netlink_cmd_rcv_bufs_force_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs", &vrrp_netlink_monitor_rcv_bufs_handler); install_keyword("vrrp_netlink_monitor_rcv_bufs_force", &vrrp_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("lvs_netlink_cmd_rcv_bufs", &lvs_netlink_cmd_rcv_bufs_handler); install_keyword("lvs_netlink_cmd_rcv_bufs_force", &lvs_netlink_cmd_rcv_bufs_force_handler); install_keyword("lvs_netlink_monitor_rcv_bufs", &lvs_netlink_monitor_rcv_bufs_handler); install_keyword("lvs_netlink_monitor_rcv_bufs_force", &lvs_netlink_monitor_rcv_bufs_force_handler); #endif #ifdef _WITH_LVS_ install_keyword("rs_init_notifies", &rs_init_notifies_handler); install_keyword("no_checker_emails", &no_checker_emails_handler); #endif #ifdef _WITH_VRRP_ install_keyword("vrrp_rx_bufs_policy", &vrrp_rx_bufs_policy_handler); install_keyword("vrrp_rx_bufs_multiplier", &vrrp_rx_bufs_multiplier_handler); #endif install_keyword("umask", &umask_handler); }
168,981
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static unsigned int khugepaged_scan_mm_slot(unsigned int pages, struct page **hpage) { struct mm_slot *mm_slot; struct mm_struct *mm; struct vm_area_struct *vma; int progress = 0; VM_BUG_ON(!pages); VM_BUG_ON(!spin_is_locked(&khugepaged_mm_lock)); if (khugepaged_scan.mm_slot) mm_slot = khugepaged_scan.mm_slot; else { mm_slot = list_entry(khugepaged_scan.mm_head.next, struct mm_slot, mm_node); khugepaged_scan.address = 0; khugepaged_scan.mm_slot = mm_slot; } spin_unlock(&khugepaged_mm_lock); mm = mm_slot->mm; down_read(&mm->mmap_sem); if (unlikely(khugepaged_test_exit(mm))) vma = NULL; else vma = find_vma(mm, khugepaged_scan.address); progress++; for (; vma; vma = vma->vm_next) { unsigned long hstart, hend; cond_resched(); if (unlikely(khugepaged_test_exit(mm))) { progress++; break; } if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) || (vma->vm_flags & VM_NOHUGEPAGE)) { skip: progress++; continue; } /* VM_PFNMAP vmas may have vm_ops null but vm_file set */ if (!vma->anon_vma || vma->vm_ops || vma->vm_file) goto skip; if (is_vma_temporary_stack(vma)) goto skip; VM_BUG_ON(is_linear_pfn_mapping(vma) || is_pfn_mapping(vma)); hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; hend = vma->vm_end & HPAGE_PMD_MASK; if (hstart >= hend) goto skip; if (khugepaged_scan.address > hend) goto skip; if (khugepaged_scan.address < hstart) khugepaged_scan.address = hstart; VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK); while (khugepaged_scan.address < hend) { int ret; cond_resched(); if (unlikely(khugepaged_test_exit(mm))) goto breakouterloop; VM_BUG_ON(khugepaged_scan.address < hstart || khugepaged_scan.address + HPAGE_PMD_SIZE > hend); ret = khugepaged_scan_pmd(mm, vma, khugepaged_scan.address, hpage); /* move to next address */ khugepaged_scan.address += HPAGE_PMD_SIZE; progress += HPAGE_PMD_NR; if (ret) /* we released mmap_sem so break loop */ goto breakouterloop_mmap_sem; if (progress >= pages) goto breakouterloop; } } breakouterloop: up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */ breakouterloop_mmap_sem: spin_lock(&khugepaged_mm_lock); VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot); /* * Release the current mm_slot if this mm is about to die, or * if we scanned all vmas of this mm. */ if (khugepaged_test_exit(mm) || !vma) { /* * Make sure that if mm_users is reaching zero while * khugepaged runs here, khugepaged_exit will find * mm_slot not pointing to the exiting mm. */ if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) { khugepaged_scan.mm_slot = list_entry( mm_slot->mm_node.next, struct mm_slot, mm_node); khugepaged_scan.address = 0; } else { khugepaged_scan.mm_slot = NULL; khugepaged_full_scans++; } collect_mm_slot(mm_slot); } return progress; } Commit Message: mm: thp: fix /dev/zero MAP_PRIVATE and vm_flags cleanups The huge_memory.c THP page fault was allowed to run if vm_ops was null (which would succeed for /dev/zero MAP_PRIVATE, as the f_op->mmap wouldn't setup a special vma->vm_ops and it would fallback to regular anonymous memory) but other THP logics weren't fully activated for vmas with vm_file not NULL (/dev/zero has a not NULL vma->vm_file). So this removes the vm_file checks so that /dev/zero also can safely use THP (the other albeit safer approach to fix this bug would have been to prevent the THP initial page fault to run if vm_file was set). After removing the vm_file checks, this also makes huge_memory.c stricter in khugepaged for the DEBUG_VM=y case. It doesn't replace the vm_file check with a is_pfn_mapping check (but it keeps checking for VM_PFNMAP under VM_BUG_ON) because for a is_cow_mapping() mapping VM_PFNMAP should only be allowed to exist before the first page fault, and in turn when vma->anon_vma is null (so preventing khugepaged registration). So I tend to think the previous comment saying if vm_file was set, VM_PFNMAP might have been set and we could still be registered in khugepaged (despite anon_vma was not NULL to be registered in khugepaged) was too paranoid. The is_linear_pfn_mapping check is also I think superfluous (as described by comment) but under DEBUG_VM it is safe to stay. Addresses https://bugzilla.kernel.org/show_bug.cgi?id=33682 Signed-off-by: Andrea Arcangeli <[email protected]> Reported-by: Caspar Zhang <[email protected]> Acked-by: Mel Gorman <[email protected]> Acked-by: Rik van Riel <[email protected]> Cc: <[email protected]> [2.6.38.x] Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
static unsigned int khugepaged_scan_mm_slot(unsigned int pages, struct page **hpage) { struct mm_slot *mm_slot; struct mm_struct *mm; struct vm_area_struct *vma; int progress = 0; VM_BUG_ON(!pages); VM_BUG_ON(!spin_is_locked(&khugepaged_mm_lock)); if (khugepaged_scan.mm_slot) mm_slot = khugepaged_scan.mm_slot; else { mm_slot = list_entry(khugepaged_scan.mm_head.next, struct mm_slot, mm_node); khugepaged_scan.address = 0; khugepaged_scan.mm_slot = mm_slot; } spin_unlock(&khugepaged_mm_lock); mm = mm_slot->mm; down_read(&mm->mmap_sem); if (unlikely(khugepaged_test_exit(mm))) vma = NULL; else vma = find_vma(mm, khugepaged_scan.address); progress++; for (; vma; vma = vma->vm_next) { unsigned long hstart, hend; cond_resched(); if (unlikely(khugepaged_test_exit(mm))) { progress++; break; } if ((!(vma->vm_flags & VM_HUGEPAGE) && !khugepaged_always()) || (vma->vm_flags & VM_NOHUGEPAGE)) { skip: progress++; continue; } if (!vma->anon_vma || vma->vm_ops) goto skip; if (is_vma_temporary_stack(vma)) goto skip; /* * If is_pfn_mapping() is true is_learn_pfn_mapping() * must be true too, verify it here. */ VM_BUG_ON(is_linear_pfn_mapping(vma) || vma->vm_flags & VM_NO_THP); hstart = (vma->vm_start + ~HPAGE_PMD_MASK) & HPAGE_PMD_MASK; hend = vma->vm_end & HPAGE_PMD_MASK; if (hstart >= hend) goto skip; if (khugepaged_scan.address > hend) goto skip; if (khugepaged_scan.address < hstart) khugepaged_scan.address = hstart; VM_BUG_ON(khugepaged_scan.address & ~HPAGE_PMD_MASK); while (khugepaged_scan.address < hend) { int ret; cond_resched(); if (unlikely(khugepaged_test_exit(mm))) goto breakouterloop; VM_BUG_ON(khugepaged_scan.address < hstart || khugepaged_scan.address + HPAGE_PMD_SIZE > hend); ret = khugepaged_scan_pmd(mm, vma, khugepaged_scan.address, hpage); /* move to next address */ khugepaged_scan.address += HPAGE_PMD_SIZE; progress += HPAGE_PMD_NR; if (ret) /* we released mmap_sem so break loop */ goto breakouterloop_mmap_sem; if (progress >= pages) goto breakouterloop; } } breakouterloop: up_read(&mm->mmap_sem); /* exit_mmap will destroy ptes after this */ breakouterloop_mmap_sem: spin_lock(&khugepaged_mm_lock); VM_BUG_ON(khugepaged_scan.mm_slot != mm_slot); /* * Release the current mm_slot if this mm is about to die, or * if we scanned all vmas of this mm. */ if (khugepaged_test_exit(mm) || !vma) { /* * Make sure that if mm_users is reaching zero while * khugepaged runs here, khugepaged_exit will find * mm_slot not pointing to the exiting mm. */ if (mm_slot->mm_node.next != &khugepaged_scan.mm_head) { khugepaged_scan.mm_slot = list_entry( mm_slot->mm_node.next, struct mm_slot, mm_node); khugepaged_scan.address = 0; } else { khugepaged_scan.mm_slot = NULL; khugepaged_full_scans++; } collect_mm_slot(mm_slot); } return progress; }
166,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int regset_tls_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct user_desc infobuf[GDT_ENTRY_TLS_ENTRIES]; const struct user_desc *info; if (pos >= GDT_ENTRY_TLS_ENTRIES * sizeof(struct user_desc) || (pos % sizeof(struct user_desc)) != 0 || (count % sizeof(struct user_desc)) != 0) return -EINVAL; if (kbuf) info = kbuf; else if (__copy_from_user(infobuf, ubuf, count)) return -EFAULT; else info = infobuf; set_tls_desc(target, GDT_ENTRY_TLS_MIN + (pos / sizeof(struct user_desc)), info, count / sizeof(struct user_desc)); return 0; } Commit Message: x86/tls: Validate TLS entries to protect espfix Installing a 16-bit RW data segment into the GDT defeats espfix. AFAICT this will not affect glibc, Wine, or dosemu at all. Signed-off-by: Andy Lutomirski <[email protected]> Acked-by: H. Peter Anvin <[email protected]> Cc: [email protected] Cc: Konrad Rzeszutek Wilk <[email protected]> Cc: Linus Torvalds <[email protected]> Cc: [email protected] <[email protected]> Cc: Willy Tarreau <[email protected]> Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
int regset_tls_set(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, const void *kbuf, const void __user *ubuf) { struct user_desc infobuf[GDT_ENTRY_TLS_ENTRIES]; const struct user_desc *info; int i; if (pos >= GDT_ENTRY_TLS_ENTRIES * sizeof(struct user_desc) || (pos % sizeof(struct user_desc)) != 0 || (count % sizeof(struct user_desc)) != 0) return -EINVAL; if (kbuf) info = kbuf; else if (__copy_from_user(infobuf, ubuf, count)) return -EFAULT; else info = infobuf; for (i = 0; i < count / sizeof(struct user_desc); i++) if (!tls_desc_okay(info + i)) return -EINVAL; set_tls_desc(target, GDT_ENTRY_TLS_MIN + (pos / sizeof(struct user_desc)), info, count / sizeof(struct user_desc)); return 0; }
166,247
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int __videobuf_mmap_mapper(struct videobuf_queue *q, struct vm_area_struct *vma) { struct videbuf_vmalloc_memory *mem; struct videobuf_mapping *map; unsigned int first; int retval; unsigned long offset = vma->vm_pgoff << PAGE_SHIFT; if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED)) return -EINVAL; /* look for first buffer to map */ for (first = 0; first < VIDEO_MAX_FRAME; first++) { if (NULL == q->bufs[first]) continue; if (V4L2_MEMORY_MMAP != q->bufs[first]->memory) continue; if (q->bufs[first]->boff == offset) break; } if (VIDEO_MAX_FRAME == first) { dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n", (vma->vm_pgoff << PAGE_SHIFT)); return -EINVAL; } /* create mapping + update buffer list */ map = q->bufs[first]->map = kmalloc(sizeof(struct videobuf_mapping),GFP_KERNEL); if (NULL == map) return -ENOMEM; map->start = vma->vm_start; map->end = vma->vm_end; map->q = q; q->bufs[first]->baddr = vma->vm_start; vma->vm_ops = &videobuf_vm_ops; vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED; vma->vm_private_data = map; mem=q->bufs[first]->priv; BUG_ON (!mem); MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM); /* Try to remap memory */ retval=remap_vmalloc_range(vma, mem->vmalloc,0); if (retval<0) { dprintk(1,"mmap: postponing remap_vmalloc_range\n"); mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL); if (!mem->vma) { kfree(map); q->bufs[first]->map=NULL; return -ENOMEM; } memcpy(mem->vma,vma,sizeof(*vma)); } dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n", map,q,vma->vm_start,vma->vm_end, (long int) q->bufs[first]->bsize, vma->vm_pgoff,first); videobuf_vm_open(vma); return (0); } Commit Message: V4L/DVB (6751): V4L: Memory leak! Fix count in videobuf-vmalloc mmap This is pretty serious bug. map->count is never initialized after the call to kmalloc making the count start at some random trash value. The end result is leaking videobufs. Also, fix up the debug statements to print unsigned values. Pushed to http://ifup.org/hg/v4l-dvb too Signed-off-by: Brandon Philips <[email protected]> Signed-off-by: Mauro Carvalho Chehab <[email protected]> CWE ID: CWE-119
static int __videobuf_mmap_mapper(struct videobuf_queue *q, struct vm_area_struct *vma) { struct videbuf_vmalloc_memory *mem; struct videobuf_mapping *map; unsigned int first; int retval; unsigned long offset = vma->vm_pgoff << PAGE_SHIFT; if (! (vma->vm_flags & VM_WRITE) || ! (vma->vm_flags & VM_SHARED)) return -EINVAL; /* look for first buffer to map */ for (first = 0; first < VIDEO_MAX_FRAME; first++) { if (NULL == q->bufs[first]) continue; if (V4L2_MEMORY_MMAP != q->bufs[first]->memory) continue; if (q->bufs[first]->boff == offset) break; } if (VIDEO_MAX_FRAME == first) { dprintk(1,"mmap app bug: offset invalid [offset=0x%lx]\n", (vma->vm_pgoff << PAGE_SHIFT)); return -EINVAL; } /* create mapping + update buffer list */ map = q->bufs[first]->map = kzalloc(sizeof(struct videobuf_mapping),GFP_KERNEL); if (NULL == map) return -ENOMEM; map->start = vma->vm_start; map->end = vma->vm_end; map->q = q; q->bufs[first]->baddr = vma->vm_start; vma->vm_ops = &videobuf_vm_ops; vma->vm_flags |= VM_DONTEXPAND | VM_RESERVED; vma->vm_private_data = map; mem=q->bufs[first]->priv; BUG_ON (!mem); MAGIC_CHECK(mem->magic,MAGIC_VMAL_MEM); /* Try to remap memory */ retval=remap_vmalloc_range(vma, mem->vmalloc,0); if (retval<0) { dprintk(1,"mmap: postponing remap_vmalloc_range\n"); mem->vma=kmalloc(sizeof(*vma),GFP_KERNEL); if (!mem->vma) { kfree(map); q->bufs[first]->map=NULL; return -ENOMEM; } memcpy(mem->vma,vma,sizeof(*vma)); } dprintk(1,"mmap %p: q=%p %08lx-%08lx (%lx) pgoff %08lx buf %d\n", map,q,vma->vm_start,vma->vm_end, (long int) q->bufs[first]->bsize, vma->vm_pgoff,first); videobuf_vm_open(vma); return (0); }
168,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: gss_krb5int_export_lucid_sec_context( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_error_code kret = 0; OM_uint32 retval; krb5_gss_ctx_id_t ctx = (krb5_gss_ctx_id_t)context_handle; void *lctx = NULL; int version = 0; gss_buffer_desc rep; /* Assume failure */ retval = GSS_S_FAILURE; *minor_status = 0; *data_set = GSS_C_NO_BUFFER_SET; retval = generic_gss_oid_decompose(minor_status, GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID, GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH, desired_object, &version); if (GSS_ERROR(retval)) return retval; /* Externalize a structure of the right version */ switch (version) { case 1: kret = make_external_lucid_ctx_v1((krb5_pointer)ctx, version, &lctx); break; default: kret = (OM_uint32) KG_LUCID_VERSION; break; } if (kret) goto error_out; rep.value = &lctx; rep.length = sizeof(lctx); retval = generic_gss_add_buffer_set_member(minor_status, &rep, data_set); if (GSS_ERROR(retval)) goto error_out; error_out: if (*minor_status == 0) *minor_status = (OM_uint32) kret; return(retval); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
gss_krb5int_export_lucid_sec_context( OM_uint32 *minor_status, const gss_ctx_id_t context_handle, const gss_OID desired_object, gss_buffer_set_t *data_set) { krb5_error_code kret = 0; OM_uint32 retval; krb5_gss_ctx_id_t ctx = (krb5_gss_ctx_id_t)context_handle; void *lctx = NULL; int version = 0; gss_buffer_desc rep; /* Assume failure */ retval = GSS_S_FAILURE; *minor_status = 0; *data_set = GSS_C_NO_BUFFER_SET; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return GSS_S_NO_CONTEXT; } retval = generic_gss_oid_decompose(minor_status, GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID, GSS_KRB5_EXPORT_LUCID_SEC_CONTEXT_OID_LENGTH, desired_object, &version); if (GSS_ERROR(retval)) return retval; /* Externalize a structure of the right version */ switch (version) { case 1: kret = make_external_lucid_ctx_v1((krb5_pointer)ctx, version, &lctx); break; default: kret = (OM_uint32) KG_LUCID_VERSION; break; } if (kret) goto error_out; rep.value = &lctx; rep.length = sizeof(lctx); retval = generic_gss_add_buffer_set_member(minor_status, &rep, data_set); if (GSS_ERROR(retval)) goto error_out; error_out: if (*minor_status == 0) *minor_status = (OM_uint32) kret; return(retval); }
166,821
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, const FrameLoadRequest& r, const WebWindowFeatures& features, NavigationPolicy navigation_policy, SandboxFlags sandbox_flags) { if (!web_view_->Client()) return nullptr; if (!frame->GetPage() || frame->GetPage()->Paused()) return nullptr; DCHECK(frame->GetDocument()); Fullscreen::FullyExitFullscreen(*frame->GetDocument()); const AtomicString& frame_name = !EqualIgnoringASCIICase(r.FrameName(), "_blank") ? r.FrameName() : g_empty_atom; WebViewImpl* new_view = static_cast<WebViewImpl*>(web_view_->Client()->CreateView( WebLocalFrameImpl::FromFrame(frame), WrappedResourceRequest(r.GetResourceRequest()), features, frame_name, static_cast<WebNavigationPolicy>(navigation_policy), r.GetShouldSetOpener() == kNeverSetOpener, static_cast<WebSandboxFlags>(sandbox_flags))); if (!new_view) return nullptr; return new_view->GetPage(); } Commit Message: If a page shows a popup, end fullscreen. This was implemented in Blink r159834, but it is susceptible to a popup/fullscreen race. This CL reverts that implementation and re-implements it in WebContents. BUG=752003 TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f Reviewed-on: https://chromium-review.googlesource.com/606987 Commit-Queue: Avi Drissman <[email protected]> Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Philip Jägenstedt <[email protected]> Cr-Commit-Position: refs/heads/master@{#498171} CWE ID: CWE-20
Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, const FrameLoadRequest& r, const WebWindowFeatures& features, NavigationPolicy navigation_policy, SandboxFlags sandbox_flags) { if (!web_view_->Client()) return nullptr; if (!frame->GetPage() || frame->GetPage()->Paused()) return nullptr; const AtomicString& frame_name = !EqualIgnoringASCIICase(r.FrameName(), "_blank") ? r.FrameName() : g_empty_atom; WebViewImpl* new_view = static_cast<WebViewImpl*>(web_view_->Client()->CreateView( WebLocalFrameImpl::FromFrame(frame), WrappedResourceRequest(r.GetResourceRequest()), features, frame_name, static_cast<WebNavigationPolicy>(navigation_policy), r.GetShouldSetOpener() == kNeverSetOpener, static_cast<WebSandboxFlags>(sandbox_flags))); if (!new_view) return nullptr; return new_view->GetPage(); }
172,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: main(void) { fprintf(stderr, "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n", PNG_ZLIB_VERNUM); return 77; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
main(void) { fprintf(stderr, "pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n", ZLIB_VERNUM); return 77; }
173,734
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_vdec::get_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_INOUT OMX_PTR configData) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Config in Invalid State"); return OMX_ErrorInvalidState; } switch ((unsigned long)configIndex) { case OMX_QcomIndexConfigInterlaced: { OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; if (configFmt->nPortIndex == 1) { if (configFmt->nIndex == 0) { configFmt->eInterlaceType = OMX_QCOM_InterlaceFrameProgressive; } else if (configFmt->nIndex == 1) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst; } else if (configFmt->nIndex == 2) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst; } else { DEBUG_PRINT_ERROR("get_config: OMX_QcomIndexConfigInterlaced:" " NoMore Interlaced formats"); eRet = OMX_ErrorNoMore; } } else { DEBUG_PRINT_ERROR("get_config: Bad port index %d queried on only o/p port", (int)configFmt->nPortIndex); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexQueryNumberOfVideoDecInstance: { QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; decoderinstances->nNumOfInstances = 16; /*TODO: How to handle this case */ break; } case OMX_QcomIndexConfigVideoFramePackingArrangement: { if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; memcpy(configFmt, &m_frame_pack_arrangement, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); } else { DEBUG_PRINT_ERROR("get_config: Framepack data not supported for non H264 codecs"); } break; } case OMX_IndexConfigCommonOutputCrop: { OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); DEBUG_PRINT_HIGH("get_config: crop info: L: %u, T: %u, R: %u, B: %u", rectangle.nLeft, rectangle.nTop, rectangle.nWidth, rectangle.nHeight); break; } case OMX_QcomIndexConfigPerfLevel: { struct v4l2_control control; OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting performance level: %d", errno); eRet = OMX_ErrorHardware; } if (eRet == OMX_ErrorNone) { switch (control.value) { case V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO: perf->ePerfLevel = OMX_QCOM_PerfLevelTurbo; break; default: DEBUG_PRINT_HIGH("Unknown perf level %d, reporting Nominal instead", control.value); /* Fall through */ case V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL: perf->ePerfLevel = OMX_QCOM_PerfLevelNominal; break; } } break; } default: { DEBUG_PRINT_ERROR("get_config: unknown param %d",configIndex); eRet = OMX_ErrorBadParameter; } } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: vidc: validate omx param/config data Check the sanity of config/param strcuture objects passed to get/set _ config()/parameter() methods. Bug: 27533317 Security Vulnerability in MediaServer omx_vdec::get_config() Can lead to arbitrary write Change-Id: I6c3243afe12055ab94f1a1ecf758c10e88231809 Conflicts: mm-core/inc/OMX_QCOMExtns.h mm-video-v4l2/vidc/vdec/src/omx_vdec_msm8974.cpp mm-video-v4l2/vidc/venc/src/omx_video_base.cpp mm-video-v4l2/vidc/venc/src/omx_video_encoder.cpp CWE ID: CWE-20
OMX_ERRORTYPE omx_vdec::get_config(OMX_IN OMX_HANDLETYPE hComp, OMX_IN OMX_INDEXTYPE configIndex, OMX_INOUT OMX_PTR configData) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; if (m_state == OMX_StateInvalid) { DEBUG_PRINT_ERROR("Get Config in Invalid State"); return OMX_ErrorInvalidState; } switch ((unsigned long)configIndex) { case OMX_QcomIndexConfigInterlaced: { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_CONFIG_INTERLACETYPE); OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; if (configFmt->nPortIndex == 1) { if (configFmt->nIndex == 0) { configFmt->eInterlaceType = OMX_QCOM_InterlaceFrameProgressive; } else if (configFmt->nIndex == 1) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst; } else if (configFmt->nIndex == 2) { configFmt->eInterlaceType = OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst; } else { DEBUG_PRINT_ERROR("get_config: OMX_QcomIndexConfigInterlaced:" " NoMore Interlaced formats"); eRet = OMX_ErrorNoMore; } } else { DEBUG_PRINT_ERROR("get_config: Bad port index %d queried on only o/p port", (int)configFmt->nPortIndex); eRet = OMX_ErrorBadPortIndex; } break; } case OMX_QcomIndexQueryNumberOfVideoDecInstance: { VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_QUERY_DECODER_INSTANCES); QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; decoderinstances->nNumOfInstances = 16; /*TODO: How to handle this case */ break; } case OMX_QcomIndexConfigVideoFramePackingArrangement: { if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_FRAME_PACK_ARRANGEMENT); OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; memcpy(configFmt, &m_frame_pack_arrangement, sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); } else { DEBUG_PRINT_ERROR("get_config: Framepack data not supported for non H264 codecs"); } break; } case OMX_IndexConfigCommonOutputCrop: { VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_RECTTYPE); OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); DEBUG_PRINT_HIGH("get_config: crop info: L: %u, T: %u, R: %u, B: %u", rectangle.nLeft, rectangle.nTop, rectangle.nWidth, rectangle.nHeight); break; } case OMX_QcomIndexConfigPerfLevel: { VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL); struct v4l2_control control; OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { DEBUG_PRINT_ERROR("Failed getting performance level: %d", errno); eRet = OMX_ErrorHardware; } if (eRet == OMX_ErrorNone) { switch (control.value) { case V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO: perf->ePerfLevel = OMX_QCOM_PerfLevelTurbo; break; default: DEBUG_PRINT_HIGH("Unknown perf level %d, reporting Nominal instead", control.value); /* Fall through */ case V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL: perf->ePerfLevel = OMX_QCOM_PerfLevelNominal; break; } } break; } default: { DEBUG_PRINT_ERROR("get_config: unknown param %d",configIndex); eRet = OMX_ErrorBadParameter; } } return eRet; }
173,788
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ShellMainDelegate::ShellMainDelegate() { } Commit Message: Fix content_shell with network service enabled not loading pages. This regressed in my earlier cl r528763. This is a reland of r547221. Bug: 833612 Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b Reviewed-on: https://chromium-review.googlesource.com/1064702 Reviewed-by: Jay Civelli <[email protected]> Commit-Queue: John Abd-El-Malek <[email protected]> Cr-Commit-Position: refs/heads/master@{#560011} CWE ID: CWE-264
ShellMainDelegate::ShellMainDelegate() {
172,121
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_increment_retval (MyObject *obj, gint32 x) { return x + 1; } Commit Message: CWE ID: CWE-264
my_object_increment_retval (MyObject *obj, gint32 x)
165,106
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } }
167,103
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void prefetch_enc(void) { prefetch_table((const void *)encT, sizeof(encT)); } Commit Message: AES: move look-up tables to .data section and unshare between processes * cipher/rijndael-internal.h (ATTR_ALIGNED_64): New. * cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure. (enc_tables): New structure for encryption table with counters before and after. (encT): New macro. (dec_tables): Add counters before and after encryption table; Move from .rodata to .data section. (do_encrypt): Change 'encT' to 'enc_tables.T'. (do_decrypt): Change '&dec_tables' to 'dec_tables.T'. * cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input with length not multiple of 256. (prefetch_enc, prefetch_dec): Modify pre- and post-table counters to unshare look-up table pages between processes. -- GnuPG-bug-id: 4541 Signed-off-by: Jussi Kivilinna <[email protected]> CWE ID: CWE-310
static void prefetch_enc(void) { /* Modify counters to trigger copy-on-write and unsharing if physical pages * of look-up table are shared between processes. Modifying counters also * causes checksums for pages to change and hint same-page merging algorithm * that these pages are frequently changing. */ enc_tables.counter_head++; enc_tables.counter_tail++; /* Prefetch look-up tables to cache. */ prefetch_table((const void *)&enc_tables, sizeof(enc_tables)); }
170,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mpeg4video_probe(AVProbeData *probe_packet) { uint32_t temp_buffer = -1; int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0; int i; for (i = 0; i < probe_packet->buf_size; i++) { temp_buffer = (temp_buffer << 8) + probe_packet->buf[i]; if ((temp_buffer & 0xffffff00) != 0x100) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer < 0x120) VO++; else if (temp_buffer < 0x130) VOL++; else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++; } if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0) return AVPROBE_SCORE_EXTENSION; return 0; } Commit Message: m4vdec: Check for non-startcode 00 00 00 sequences in probe This makes the m4v detection less trigger-happy. Bug-Id: 949 Signed-off-by: Diego Biurrun <[email protected]> CWE ID: CWE-476
static int mpeg4video_probe(AVProbeData *probe_packet) { uint32_t temp_buffer = -1; int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0; int i; for (i = 0; i < probe_packet->buf_size; i++) { temp_buffer = (temp_buffer << 8) + probe_packet->buf[i]; if (temp_buffer & 0xfffffe00) continue; if (temp_buffer < 2) continue; if (temp_buffer == VOP_START_CODE) VOP++; else if (temp_buffer == VISUAL_OBJECT_START_CODE) VISO++; else if (temp_buffer >= 0x100 && temp_buffer < 0x120) VO++; else if (temp_buffer >= 0x120 && temp_buffer < 0x130) VOL++; else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) && !(0x1B9 < temp_buffer && temp_buffer < 0x1C4)) res++; } if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0) return AVPROBE_SCORE_EXTENSION; return 0; }
168,768
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); const struct uac_to_guid { uint32_t uac; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; const char *error_string; } map[] = { { }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } }; Commit Message: CWE ID: CWE-264
static int samldb_check_user_account_control_acl(struct samldb_ctx *ac, struct dom_sid *sid, uint32_t user_account_control, uint32_t user_account_control_old) { int i, ret = 0; bool need_acl_check = false; struct ldb_result *res; const char * const sd_attrs[] = {"ntSecurityDescriptor", NULL}; struct security_token *user_token; struct security_descriptor *domain_sd; struct ldb_dn *domain_dn = ldb_get_default_basedn(ldb_module_get_ctx(ac->module)); struct ldb_context *ldb = ldb_module_get_ctx(ac->module); const struct uac_to_guid { uint32_t uac; uint32_t priv_to_change_from; const char *oid; const char *guid; enum sec_privilege privilege; bool delete_is_privileged; bool admin_required; const char *error_string; } map[] = { { }, { .uac = UF_DONT_EXPIRE_PASSWD, .guid = GUID_DRS_UNEXPIRE_PASSWORD, .error_string = "Adding the UF_DONT_EXPIRE_PASSWD bit in userAccountControl requires the Unexpire-Password right that was not given on the Domain object" }, { .uac = UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED, .guid = GUID_DRS_ENABLE_PER_USER_REVERSIBLY_ENCRYPTED_PASSWORD, .error_string = "Adding the UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED bit in userAccountControl requires the Enable-Per-User-Reversibly-Encrypted-Password right that was not given on the Domain object" }, { .uac = UF_SERVER_TRUST_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_SERVER_TRUST_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_PARTIAL_SECRETS_ACCOUNT, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, .guid = GUID_DRS_DS_INSTALL_REPLICA, .error_string = "Adding the UF_PARTIAL_SECRETS_ACCOUNT bit in userAccountControl requires the DS-Install-Replica right that was not given on the Domain object" }, { .uac = UF_WORKSTATION_TRUST_ACCOUNT, .priv_to_change_from = UF_NORMAL_ACCOUNT, .error_string = "Swapping UF_NORMAL_ACCOUNT to UF_WORKSTATION_TRUST_ACCOUNT requires the user to be a member of the domain admins group" }, { .uac = UF_NORMAL_ACCOUNT, .priv_to_change_from = UF_WORKSTATION_TRUST_ACCOUNT, .error_string = "Swapping UF_WORKSTATION_TRUST_ACCOUNT to UF_NORMAL_ACCOUNT requires the user to be a member of the domain admins group" }, { .uac = UF_INTERDOMAIN_TRUST_ACCOUNT, .oid = DSDB_CONTROL_PERMIT_INTERDOMAIN_TRUST_UAC_OID, .error_string = "Updating the UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION bit in userAccountControl is not permitted without the SeEnableDelegationPrivilege" } };
164,564
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest() : event(false, false), gpu_process_handle(base::kNullProcessHandle) { } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
BrowserGpuChannelHostFactory::EstablishRequest::EstablishRequest() : event(false, false) { }
170,918
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: z2grestore(i_ctx_t *i_ctx_p) { if (!restore_page_device(igs, gs_gstate_saved(igs))) return gs_grestore(igs); return push_callout(i_ctx_p, "%grestorepagedevice"); } Commit Message: CWE ID:
z2grestore(i_ctx_t *i_ctx_p) { int code = restore_page_device(i_ctx_p, igs, gs_gstate_saved(igs)); if (code < 0) return code; if (code == 0) return gs_grestore(igs); return push_callout(i_ctx_p, "%grestorepagedevice"); }
164,691
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResetState() { nav_handle1_.reset(); nav_handle2_.reset(); nav_handle3_.reset(); throttle1_.reset(); throttle2_.reset(); throttle3_.reset(); contents1_.reset(); contents2_.reset(); contents3_.reset(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <[email protected]> Reviewed-by: François Doray <[email protected]> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
void ResetState() { nav_handle1_.reset(); nav_handle2_.reset(); nav_handle3_.reset(); throttle1_.reset(); throttle2_.reset(); throttle3_.reset(); // ChromeTestHarnessWithLocalDB::TearDown() deletes the contents1_.reset(); contents2_.reset(); contents3_.reset(); }
172,231
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->pos + count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; } Commit Message: CWE ID: CWE-20
FT_Stream_EnterFrame( FT_Stream stream, FT_ULong count ) { FT_Error error = FT_Err_Ok; FT_ULong read_bytes; /* check for nested frame access */ FT_ASSERT( stream && stream->cursor == 0 ); if ( stream->read ) { /* allocate the frame in memory */ FT_Memory memory = stream->memory; /* simple sanity check */ if ( count > stream->size ) { FT_ERROR(( "FT_Stream_EnterFrame:" " frame size (%lu) larger than stream size (%lu)\n", count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } #ifdef FT_DEBUG_MEMORY /* assume _ft_debug_file and _ft_debug_lineno are already set */ stream->base = (unsigned char*)ft_mem_qalloc( memory, count, &error ); if ( error ) goto Exit; #else if ( FT_QALLOC( stream->base, count ) ) goto Exit; #endif /* read it */ read_bytes = stream->read( stream, stream->pos, stream->base, count ); if ( read_bytes < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid read; expected %lu bytes, got %lu\n", count, read_bytes )); FT_FREE( stream->base ); error = FT_Err_Invalid_Stream_Operation; } stream->cursor = stream->base; stream->limit = stream->cursor + count; stream->pos += read_bytes; } else { /* check current and new position */ if ( stream->pos >= stream->size || stream->size - stream->pos < count ) { FT_ERROR(( "FT_Stream_EnterFrame:" " invalid i/o; pos = 0x%lx, count = %lu, size = 0x%lx\n", stream->pos, count, stream->size )); error = FT_Err_Invalid_Stream_Operation; goto Exit; } /* set cursor */ stream->cursor = stream->base + stream->pos; stream->limit = stream->cursor + count; stream->pos += count; } Exit: return error; }
164,986
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mb_ereg_search_init) { size_t argc = ZEND_NUM_ARGS(); zval *arg_str; char *arg_pattern = NULL, *arg_options = NULL; int arg_pattern_len = 0, arg_options_len = 0; OnigSyntaxType *syntax = NULL; OnigOptionType option; if (zend_parse_parameters(argc TSRMLS_CC, "z|ss", &arg_str, &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) { return; } if (argc > 1 && arg_pattern_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty pattern"); RETURN_FALSE; } option = MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); if (argc == 3) { option = 0; _php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL); } if (argc > 1) { /* create regex pattern buffer */ if ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), syntax TSRMLS_CC)) == NULL) { RETURN_FALSE; } } if (MBREX(search_str) != NULL) { zval_ptr_dtor(&MBREX(search_str)); MBREX(search_str) = (zval *)NULL; } MBREX(search_str) = arg_str; Z_ADDREF_P(MBREX(search_str)); SEPARATE_ZVAL_IF_NOT_REF(&MBREX(search_str)); MBREX(search_pos) = 0; if (MBREX(search_regs) != NULL) { onig_region_free(MBREX(search_regs), 1); MBREX(search_regs) = (OnigRegion *) NULL; } RETURN_TRUE; } Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free CWE ID: CWE-415
PHP_FUNCTION(mb_ereg_search_init) { size_t argc = ZEND_NUM_ARGS(); zval *arg_str; char *arg_pattern = NULL, *arg_options = NULL; int arg_pattern_len = 0, arg_options_len = 0; OnigSyntaxType *syntax = NULL; OnigOptionType option; if (zend_parse_parameters(argc TSRMLS_CC, "z|ss", &arg_str, &arg_pattern, &arg_pattern_len, &arg_options, &arg_options_len) == FAILURE) { return; } if (argc > 1 && arg_pattern_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty pattern"); RETURN_FALSE; } option = MBREX(regex_default_options); syntax = MBREX(regex_default_syntax); if (argc == 3) { option = 0; _php_mb_regex_init_options(arg_options, arg_options_len, &option, &syntax, NULL); } if (argc > 1) { /* create regex pattern buffer */ if ((MBREX(search_re) = php_mbregex_compile_pattern(arg_pattern, arg_pattern_len, option, MBREX(current_mbctype), syntax TSRMLS_CC)) == NULL) { RETURN_FALSE; } } if (MBREX(search_str) != NULL) { zval_ptr_dtor(&MBREX(search_str)); MBREX(search_str) = (zval *)NULL; } MBREX(search_str) = arg_str; Z_ADDREF_P(MBREX(search_str)); SEPARATE_ZVAL_IF_NOT_REF(&MBREX(search_str)); MBREX(search_pos) = 0; if (MBREX(search_regs) != NULL) { onig_region_free(MBREX(search_regs), 1); MBREX(search_regs) = (OnigRegion *) NULL; } RETURN_TRUE; }
167,116
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SimulateOnBufferCreated(int buffer_id, const base::SharedMemory& shm) { auto handle = base::SharedMemory::DuplicateHandle(shm.handle()); video_capture_impl_->OnBufferCreated( buffer_id, mojo::WrapSharedMemoryHandle(handle, shm.mapped_size(), true /* read_only */)); } Commit Message: Correct mojo::WrapSharedMemoryHandle usage Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which were assuming that the call actually has any control over the memory protection applied to a handle when mapped. Where fixing usage is infeasible for this CL, TODOs are added to annotate follow-up work. Also updates the API and documentation to (hopefully) improve clarity and avoid similar mistakes from being made in the future. BUG=792900 Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477 Reviewed-on: https://chromium-review.googlesource.com/818282 Reviewed-by: Wei Li <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Reviewed-by: John Abd-El-Malek <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Sadrul Chowdhury <[email protected]> Reviewed-by: Yuzhu Shen <[email protected]> Reviewed-by: Robert Sesek <[email protected]> Commit-Queue: Ken Rockot <[email protected]> Cr-Commit-Position: refs/heads/master@{#530268} CWE ID: CWE-787
void SimulateOnBufferCreated(int buffer_id, const base::SharedMemory& shm) { video_capture_impl_->OnBufferCreated( buffer_id, mojo::WrapSharedMemoryHandle( shm.GetReadOnlyHandle(), shm.mapped_size(), mojo::UnwrappedSharedMemoryHandleProtection::kReadOnly)); }
172,866
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { SEPARATE_ZVAL(var2); convert_to_double(*var2); matrix[i][j] = (float)Z_DVAL_PP(var2); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } } Commit Message: Fixed bug #66356 (Heap Overflow Vulnerability in imagecrop()) And also fixed the bug: arguments are altered after some calls CWE ID: CWE-189
PHP_FUNCTION(imageconvolution) { zval *SIM, *hash_matrix; zval **var = NULL, **var2 = NULL; gdImagePtr im_src = NULL; double div, offset; int nelem, i, j, res; float matrix[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "radd", &SIM, &hash_matrix, &div, &offset) == FAILURE) { RETURN_FALSE; } ZEND_FETCH_RESOURCE(im_src, gdImagePtr, &SIM, -1, "Image", le_gd); nelem = zend_hash_num_elements(Z_ARRVAL_P(hash_matrix)); if (nelem != 3) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (i=0; i<3; i++) { if (zend_hash_index_find(Z_ARRVAL_P(hash_matrix), (i), (void **) &var) == SUCCESS && Z_TYPE_PP(var) == IS_ARRAY) { if (Z_TYPE_PP(var) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_PP(var)) != 3 ) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have 3x3 array"); RETURN_FALSE; } for (j=0; j<3; j++) { if (zend_hash_index_find(Z_ARRVAL_PP(var), (j), (void **) &var2) == SUCCESS) { if (Z_TYPE_PP(var2) != IS_DOUBLE) { zval dval; dval = **var; zval_copy_ctor(&dval); convert_to_double(&dval); matrix[i][j] = (float)Z_DVAL(dval); } else { matrix[i][j] = (float)Z_DVAL_PP(var2); } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "You must have a 3x3 matrix"); RETURN_FALSE; } } } } res = gdImageConvolution(im_src, matrix, (float)div, (float)offset); if (res) { RETURN_TRUE; } else { RETURN_FALSE; } }
166,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct task_struct *copy_process(unsigned long clone_flags, unsigned long stack_start, unsigned long stack_size, int __user *child_tidptr, struct pid *pid, int trace) { int retval; struct task_struct *p; if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. */ if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) return ERR_PTR(-EINVAL); /* * Shared signal handlers imply shared VM. By way of the above, * thread groups also imply shared VM. Blocking this case allows * for various simplifications in other code. */ if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) return ERR_PTR(-EINVAL); /* * Siblings of global init remain as zombies on exit since they are * not reaped by their parent (swapper). To solve this and to avoid * multi-rooted process trees, prevent global and container-inits * from creating siblings. */ if ((clone_flags & CLONE_PARENT) && current->signal->flags & SIGNAL_UNKILLABLE) return ERR_PTR(-EINVAL); /* * If the new process will be in a different pid namespace * don't allow the creation of threads. */ if ((clone_flags & (CLONE_VM|CLONE_NEWPID)) && (task_active_pid_ns(current) != current->nsproxy->pid_ns)) return ERR_PTR(-EINVAL); retval = security_task_create(clone_flags); if (retval) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current); if (!p) goto fork_out; ftrace_graph_init_task(p); get_seccomp_filter(p); rt_mutex_init_task(p); #ifdef CONFIG_PROVE_LOCKING DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled); DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif retval = -EAGAIN; if (atomic_read(&p->real_cred->user->processes) >= task_rlimit(p, RLIMIT_NPROC)) { if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) && p->real_cred->user != INIT_USER) goto bad_fork_free; } current->flags &= ~PF_NPROC_EXCEEDED; retval = copy_creds(p, clone_flags); if (retval < 0) goto bad_fork_free; /* * If multiple threads are within copy_process(), then this check * triggers too late. This doesn't hurt, the check is only there * to stop root fork bombs. */ retval = -EAGAIN; if (nr_threads >= max_threads) goto bad_fork_cleanup_count; if (!try_module_get(task_thread_info(p)->exec_domain->module)) goto bad_fork_cleanup_count; p->did_exec = 0; delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ copy_flags(clone_flags, p); INIT_LIST_HEAD(&p->children); INIT_LIST_HEAD(&p->sibling); rcu_copy_process(p); p->vfork_done = NULL; spin_lock_init(&p->alloc_lock); init_sigpending(&p->pending); p->utime = p->stime = p->gtime = 0; p->utimescaled = p->stimescaled = 0; #ifndef CONFIG_VIRT_CPU_ACCOUNTING p->prev_cputime.utime = p->prev_cputime.stime = 0; #endif #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN seqlock_init(&p->vtime_seqlock); p->vtime_snap = 0; p->vtime_snap_whence = VTIME_SLEEPING; #endif #if defined(SPLIT_RSS_COUNTING) memset(&p->rss_stat, 0, sizeof(p->rss_stat)); #endif p->default_timer_slack_ns = current->timer_slack_ns; task_io_accounting_init(&p->ioac); acct_clear_integrals(p); posix_cpu_timers_init(p); do_posix_clock_monotonic_gettime(&p->start_time); p->real_start_time = p->start_time; monotonic_to_bootbased(&p->real_start_time); p->io_context = NULL; p->audit_context = NULL; if (clone_flags & CLONE_THREAD) threadgroup_change_begin(current); cgroup_fork(p); #ifdef CONFIG_NUMA p->mempolicy = mpol_dup(p->mempolicy); if (IS_ERR(p->mempolicy)) { retval = PTR_ERR(p->mempolicy); p->mempolicy = NULL; goto bad_fork_cleanup_cgroup; } mpol_fix_fork_child_flag(p); #endif #ifdef CONFIG_CPUSETS p->cpuset_mem_spread_rotor = NUMA_NO_NODE; p->cpuset_slab_spread_rotor = NUMA_NO_NODE; seqcount_init(&p->mems_allowed_seq); #endif #ifdef CONFIG_TRACE_IRQFLAGS p->irq_events = 0; p->hardirqs_enabled = 0; p->hardirq_enable_ip = 0; p->hardirq_enable_event = 0; p->hardirq_disable_ip = _THIS_IP_; p->hardirq_disable_event = 0; p->softirqs_enabled = 1; p->softirq_enable_ip = _THIS_IP_; p->softirq_enable_event = 0; p->softirq_disable_ip = 0; p->softirq_disable_event = 0; p->hardirq_context = 0; p->softirq_context = 0; #endif #ifdef CONFIG_LOCKDEP p->lockdep_depth = 0; /* no locks held yet */ p->curr_chain_key = 0; p->lockdep_recursion = 0; #endif #ifdef CONFIG_DEBUG_MUTEXES p->blocked_on = NULL; /* not blocked yet */ #endif #ifdef CONFIG_MEMCG p->memcg_batch.do_batch = 0; p->memcg_batch.memcg = NULL; #endif /* Perform scheduler related setup. Assign this task to a CPU. */ sched_fork(p); retval = perf_event_init_task(p); if (retval) goto bad_fork_cleanup_policy; retval = audit_alloc(p); if (retval) goto bad_fork_cleanup_policy; /* copy all the process information */ retval = copy_semundo(clone_flags, p); if (retval) goto bad_fork_cleanup_audit; retval = copy_files(clone_flags, p); if (retval) goto bad_fork_cleanup_semundo; retval = copy_fs(clone_flags, p); if (retval) goto bad_fork_cleanup_files; retval = copy_sighand(clone_flags, p); if (retval) goto bad_fork_cleanup_fs; retval = copy_signal(clone_flags, p); if (retval) goto bad_fork_cleanup_sighand; retval = copy_mm(clone_flags, p); if (retval) goto bad_fork_cleanup_signal; retval = copy_namespaces(clone_flags, p); if (retval) goto bad_fork_cleanup_mm; retval = copy_io(clone_flags, p); if (retval) goto bad_fork_cleanup_namespaces; retval = copy_thread(clone_flags, stack_start, stack_size, p); if (retval) goto bad_fork_cleanup_io; if (pid != &init_struct_pid) { retval = -ENOMEM; pid = alloc_pid(p->nsproxy->pid_ns); if (!pid) goto bad_fork_cleanup_io; } p->pid = pid_nr(pid); p->tgid = p->pid; if (clone_flags & CLONE_THREAD) p->tgid = current->tgid; p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL; /* * Clear TID on mm_release()? */ p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL; #ifdef CONFIG_BLOCK p->plug = NULL; #endif #ifdef CONFIG_FUTEX p->robust_list = NULL; #ifdef CONFIG_COMPAT p->compat_robust_list = NULL; #endif INIT_LIST_HEAD(&p->pi_state_list); p->pi_state_cache = NULL; #endif uprobe_copy_process(p); /* * sigaltstack should be cleared when sharing the same VM */ if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) p->sas_ss_sp = p->sas_ss_size = 0; /* * Syscall tracing and stepping should be turned off in the * child regardless of CLONE_PTRACE. */ user_disable_single_step(p); clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE); #ifdef TIF_SYSCALL_EMU clear_tsk_thread_flag(p, TIF_SYSCALL_EMU); #endif clear_all_latency_tracing(p); /* ok, now we should be set up.. */ if (clone_flags & CLONE_THREAD) p->exit_signal = -1; else if (clone_flags & CLONE_PARENT) p->exit_signal = current->group_leader->exit_signal; else p->exit_signal = (clone_flags & CSIGNAL); p->pdeath_signal = 0; p->exit_state = 0; p->nr_dirtied = 0; p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10); p->dirty_paused_when = 0; /* * Ok, make it visible to the rest of the system. * We dont wake it up yet. */ p->group_leader = p; INIT_LIST_HEAD(&p->thread_group); p->task_works = NULL; /* Need tasklist lock for parent etc handling! */ write_lock_irq(&tasklist_lock); /* CLONE_PARENT re-uses the old parent */ if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) { p->real_parent = current->real_parent; p->parent_exec_id = current->parent_exec_id; } else { p->real_parent = current; p->parent_exec_id = current->self_exec_id; } spin_lock(&current->sighand->siglock); /* * Process group and session signals need to be delivered to just the * parent before the fork or both the parent and the child after the * fork. Restart if a signal comes in before we add the new process to * it's process group. * A fatal signal pending means that current will exit, so the new * thread can't slip out of an OOM kill (or normal SIGKILL). */ recalc_sigpending(); if (signal_pending(current)) { spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); retval = -ERESTARTNOINTR; goto bad_fork_free_pid; } if (clone_flags & CLONE_THREAD) { current->signal->nr_threads++; atomic_inc(&current->signal->live); atomic_inc(&current->signal->sigcnt); p->group_leader = current->group_leader; list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group); } if (likely(p->pid)) { ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace); if (thread_group_leader(p)) { if (is_child_reaper(pid)) { ns_of_pid(pid)->child_reaper = p; p->signal->flags |= SIGNAL_UNKILLABLE; } p->signal->leader_pid = pid; p->signal->tty = tty_kref_get(current->signal->tty); attach_pid(p, PIDTYPE_PGID, task_pgrp(current)); attach_pid(p, PIDTYPE_SID, task_session(current)); list_add_tail(&p->sibling, &p->real_parent->children); list_add_tail_rcu(&p->tasks, &init_task.tasks); __this_cpu_inc(process_counts); } attach_pid(p, PIDTYPE_PID, pid); nr_threads++; } total_forks++; spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); proc_fork_connector(p); cgroup_post_fork(p); if (clone_flags & CLONE_THREAD) threadgroup_change_end(current); perf_event_fork(p); trace_task_newtask(p, clone_flags); return p; bad_fork_free_pid: if (pid != &init_struct_pid) free_pid(pid); bad_fork_cleanup_io: if (p->io_context) exit_io_context(p); bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: if (!(clone_flags & CLONE_THREAD)) free_signal_struct(p->signal); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* blocking */ bad_fork_cleanup_files: exit_files(p); /* blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_audit: audit_free(p); bad_fork_cleanup_policy: perf_event_free_task(p); #ifdef CONFIG_NUMA mpol_put(p->mempolicy); bad_fork_cleanup_cgroup: #endif if (clone_flags & CLONE_THREAD) threadgroup_change_end(current); cgroup_exit(p, 0); delayacct_tsk_free(p); module_put(task_thread_info(p)->exec_domain->module); bad_fork_cleanup_count: atomic_dec(&p->cred->user->processes); exit_creds(p); bad_fork_free: free_task(p); fork_out: return ERR_PTR(retval); } Commit Message: userns: Don't allow CLONE_NEWUSER | CLONE_FS Don't allowing sharing the root directory with processes in a different user namespace. There doesn't seem to be any point, and to allow it would require the overhead of putting a user namespace reference in fs_struct (for permission checks) and incrementing that reference count on practically every call to fork. So just perform the inexpensive test of forbidding sharing fs_struct acrosss processes in different user namespaces. We already disallow other forms of threading when unsharing a user namespace so this should be no real burden in practice. This updates setns, clone, and unshare to disallow multiple user namespaces sharing an fs_struct. Cc: [email protected] Signed-off-by: "Eric W. Biederman" <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
static struct task_struct *copy_process(unsigned long clone_flags, unsigned long stack_start, unsigned long stack_size, int __user *child_tidptr, struct pid *pid, int trace) { int retval; struct task_struct *p; if ((clone_flags & (CLONE_NEWNS|CLONE_FS)) == (CLONE_NEWNS|CLONE_FS)) return ERR_PTR(-EINVAL); if ((clone_flags & (CLONE_NEWUSER|CLONE_FS)) == (CLONE_NEWUSER|CLONE_FS)) return ERR_PTR(-EINVAL); /* * Thread groups must share signals as well, and detached threads * can only be started up within the thread group. */ if ((clone_flags & CLONE_THREAD) && !(clone_flags & CLONE_SIGHAND)) return ERR_PTR(-EINVAL); /* * Shared signal handlers imply shared VM. By way of the above, * thread groups also imply shared VM. Blocking this case allows * for various simplifications in other code. */ if ((clone_flags & CLONE_SIGHAND) && !(clone_flags & CLONE_VM)) return ERR_PTR(-EINVAL); /* * Siblings of global init remain as zombies on exit since they are * not reaped by their parent (swapper). To solve this and to avoid * multi-rooted process trees, prevent global and container-inits * from creating siblings. */ if ((clone_flags & CLONE_PARENT) && current->signal->flags & SIGNAL_UNKILLABLE) return ERR_PTR(-EINVAL); /* * If the new process will be in a different pid namespace * don't allow the creation of threads. */ if ((clone_flags & (CLONE_VM|CLONE_NEWPID)) && (task_active_pid_ns(current) != current->nsproxy->pid_ns)) return ERR_PTR(-EINVAL); retval = security_task_create(clone_flags); if (retval) goto fork_out; retval = -ENOMEM; p = dup_task_struct(current); if (!p) goto fork_out; ftrace_graph_init_task(p); get_seccomp_filter(p); rt_mutex_init_task(p); #ifdef CONFIG_PROVE_LOCKING DEBUG_LOCKS_WARN_ON(!p->hardirqs_enabled); DEBUG_LOCKS_WARN_ON(!p->softirqs_enabled); #endif retval = -EAGAIN; if (atomic_read(&p->real_cred->user->processes) >= task_rlimit(p, RLIMIT_NPROC)) { if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RESOURCE) && p->real_cred->user != INIT_USER) goto bad_fork_free; } current->flags &= ~PF_NPROC_EXCEEDED; retval = copy_creds(p, clone_flags); if (retval < 0) goto bad_fork_free; /* * If multiple threads are within copy_process(), then this check * triggers too late. This doesn't hurt, the check is only there * to stop root fork bombs. */ retval = -EAGAIN; if (nr_threads >= max_threads) goto bad_fork_cleanup_count; if (!try_module_get(task_thread_info(p)->exec_domain->module)) goto bad_fork_cleanup_count; p->did_exec = 0; delayacct_tsk_init(p); /* Must remain after dup_task_struct() */ copy_flags(clone_flags, p); INIT_LIST_HEAD(&p->children); INIT_LIST_HEAD(&p->sibling); rcu_copy_process(p); p->vfork_done = NULL; spin_lock_init(&p->alloc_lock); init_sigpending(&p->pending); p->utime = p->stime = p->gtime = 0; p->utimescaled = p->stimescaled = 0; #ifndef CONFIG_VIRT_CPU_ACCOUNTING p->prev_cputime.utime = p->prev_cputime.stime = 0; #endif #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN seqlock_init(&p->vtime_seqlock); p->vtime_snap = 0; p->vtime_snap_whence = VTIME_SLEEPING; #endif #if defined(SPLIT_RSS_COUNTING) memset(&p->rss_stat, 0, sizeof(p->rss_stat)); #endif p->default_timer_slack_ns = current->timer_slack_ns; task_io_accounting_init(&p->ioac); acct_clear_integrals(p); posix_cpu_timers_init(p); do_posix_clock_monotonic_gettime(&p->start_time); p->real_start_time = p->start_time; monotonic_to_bootbased(&p->real_start_time); p->io_context = NULL; p->audit_context = NULL; if (clone_flags & CLONE_THREAD) threadgroup_change_begin(current); cgroup_fork(p); #ifdef CONFIG_NUMA p->mempolicy = mpol_dup(p->mempolicy); if (IS_ERR(p->mempolicy)) { retval = PTR_ERR(p->mempolicy); p->mempolicy = NULL; goto bad_fork_cleanup_cgroup; } mpol_fix_fork_child_flag(p); #endif #ifdef CONFIG_CPUSETS p->cpuset_mem_spread_rotor = NUMA_NO_NODE; p->cpuset_slab_spread_rotor = NUMA_NO_NODE; seqcount_init(&p->mems_allowed_seq); #endif #ifdef CONFIG_TRACE_IRQFLAGS p->irq_events = 0; p->hardirqs_enabled = 0; p->hardirq_enable_ip = 0; p->hardirq_enable_event = 0; p->hardirq_disable_ip = _THIS_IP_; p->hardirq_disable_event = 0; p->softirqs_enabled = 1; p->softirq_enable_ip = _THIS_IP_; p->softirq_enable_event = 0; p->softirq_disable_ip = 0; p->softirq_disable_event = 0; p->hardirq_context = 0; p->softirq_context = 0; #endif #ifdef CONFIG_LOCKDEP p->lockdep_depth = 0; /* no locks held yet */ p->curr_chain_key = 0; p->lockdep_recursion = 0; #endif #ifdef CONFIG_DEBUG_MUTEXES p->blocked_on = NULL; /* not blocked yet */ #endif #ifdef CONFIG_MEMCG p->memcg_batch.do_batch = 0; p->memcg_batch.memcg = NULL; #endif /* Perform scheduler related setup. Assign this task to a CPU. */ sched_fork(p); retval = perf_event_init_task(p); if (retval) goto bad_fork_cleanup_policy; retval = audit_alloc(p); if (retval) goto bad_fork_cleanup_policy; /* copy all the process information */ retval = copy_semundo(clone_flags, p); if (retval) goto bad_fork_cleanup_audit; retval = copy_files(clone_flags, p); if (retval) goto bad_fork_cleanup_semundo; retval = copy_fs(clone_flags, p); if (retval) goto bad_fork_cleanup_files; retval = copy_sighand(clone_flags, p); if (retval) goto bad_fork_cleanup_fs; retval = copy_signal(clone_flags, p); if (retval) goto bad_fork_cleanup_sighand; retval = copy_mm(clone_flags, p); if (retval) goto bad_fork_cleanup_signal; retval = copy_namespaces(clone_flags, p); if (retval) goto bad_fork_cleanup_mm; retval = copy_io(clone_flags, p); if (retval) goto bad_fork_cleanup_namespaces; retval = copy_thread(clone_flags, stack_start, stack_size, p); if (retval) goto bad_fork_cleanup_io; if (pid != &init_struct_pid) { retval = -ENOMEM; pid = alloc_pid(p->nsproxy->pid_ns); if (!pid) goto bad_fork_cleanup_io; } p->pid = pid_nr(pid); p->tgid = p->pid; if (clone_flags & CLONE_THREAD) p->tgid = current->tgid; p->set_child_tid = (clone_flags & CLONE_CHILD_SETTID) ? child_tidptr : NULL; /* * Clear TID on mm_release()? */ p->clear_child_tid = (clone_flags & CLONE_CHILD_CLEARTID) ? child_tidptr : NULL; #ifdef CONFIG_BLOCK p->plug = NULL; #endif #ifdef CONFIG_FUTEX p->robust_list = NULL; #ifdef CONFIG_COMPAT p->compat_robust_list = NULL; #endif INIT_LIST_HEAD(&p->pi_state_list); p->pi_state_cache = NULL; #endif uprobe_copy_process(p); /* * sigaltstack should be cleared when sharing the same VM */ if ((clone_flags & (CLONE_VM|CLONE_VFORK)) == CLONE_VM) p->sas_ss_sp = p->sas_ss_size = 0; /* * Syscall tracing and stepping should be turned off in the * child regardless of CLONE_PTRACE. */ user_disable_single_step(p); clear_tsk_thread_flag(p, TIF_SYSCALL_TRACE); #ifdef TIF_SYSCALL_EMU clear_tsk_thread_flag(p, TIF_SYSCALL_EMU); #endif clear_all_latency_tracing(p); /* ok, now we should be set up.. */ if (clone_flags & CLONE_THREAD) p->exit_signal = -1; else if (clone_flags & CLONE_PARENT) p->exit_signal = current->group_leader->exit_signal; else p->exit_signal = (clone_flags & CSIGNAL); p->pdeath_signal = 0; p->exit_state = 0; p->nr_dirtied = 0; p->nr_dirtied_pause = 128 >> (PAGE_SHIFT - 10); p->dirty_paused_when = 0; /* * Ok, make it visible to the rest of the system. * We dont wake it up yet. */ p->group_leader = p; INIT_LIST_HEAD(&p->thread_group); p->task_works = NULL; /* Need tasklist lock for parent etc handling! */ write_lock_irq(&tasklist_lock); /* CLONE_PARENT re-uses the old parent */ if (clone_flags & (CLONE_PARENT|CLONE_THREAD)) { p->real_parent = current->real_parent; p->parent_exec_id = current->parent_exec_id; } else { p->real_parent = current; p->parent_exec_id = current->self_exec_id; } spin_lock(&current->sighand->siglock); /* * Process group and session signals need to be delivered to just the * parent before the fork or both the parent and the child after the * fork. Restart if a signal comes in before we add the new process to * it's process group. * A fatal signal pending means that current will exit, so the new * thread can't slip out of an OOM kill (or normal SIGKILL). */ recalc_sigpending(); if (signal_pending(current)) { spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); retval = -ERESTARTNOINTR; goto bad_fork_free_pid; } if (clone_flags & CLONE_THREAD) { current->signal->nr_threads++; atomic_inc(&current->signal->live); atomic_inc(&current->signal->sigcnt); p->group_leader = current->group_leader; list_add_tail_rcu(&p->thread_group, &p->group_leader->thread_group); } if (likely(p->pid)) { ptrace_init_task(p, (clone_flags & CLONE_PTRACE) || trace); if (thread_group_leader(p)) { if (is_child_reaper(pid)) { ns_of_pid(pid)->child_reaper = p; p->signal->flags |= SIGNAL_UNKILLABLE; } p->signal->leader_pid = pid; p->signal->tty = tty_kref_get(current->signal->tty); attach_pid(p, PIDTYPE_PGID, task_pgrp(current)); attach_pid(p, PIDTYPE_SID, task_session(current)); list_add_tail(&p->sibling, &p->real_parent->children); list_add_tail_rcu(&p->tasks, &init_task.tasks); __this_cpu_inc(process_counts); } attach_pid(p, PIDTYPE_PID, pid); nr_threads++; } total_forks++; spin_unlock(&current->sighand->siglock); write_unlock_irq(&tasklist_lock); proc_fork_connector(p); cgroup_post_fork(p); if (clone_flags & CLONE_THREAD) threadgroup_change_end(current); perf_event_fork(p); trace_task_newtask(p, clone_flags); return p; bad_fork_free_pid: if (pid != &init_struct_pid) free_pid(pid); bad_fork_cleanup_io: if (p->io_context) exit_io_context(p); bad_fork_cleanup_namespaces: exit_task_namespaces(p); bad_fork_cleanup_mm: if (p->mm) mmput(p->mm); bad_fork_cleanup_signal: if (!(clone_flags & CLONE_THREAD)) free_signal_struct(p->signal); bad_fork_cleanup_sighand: __cleanup_sighand(p->sighand); bad_fork_cleanup_fs: exit_fs(p); /* blocking */ bad_fork_cleanup_files: exit_files(p); /* blocking */ bad_fork_cleanup_semundo: exit_sem(p); bad_fork_cleanup_audit: audit_free(p); bad_fork_cleanup_policy: perf_event_free_task(p); #ifdef CONFIG_NUMA mpol_put(p->mempolicy); bad_fork_cleanup_cgroup: #endif if (clone_flags & CLONE_THREAD) threadgroup_change_end(current); cgroup_exit(p, 0); delayacct_tsk_free(p); module_put(task_thread_info(p)->exec_domain->module); bad_fork_cleanup_count: atomic_dec(&p->cred->user->processes); exit_creds(p); bad_fork_free: free_task(p); fork_out: return ERR_PTR(retval); }
166,107
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int try_smi_init(struct smi_info *new_smi) { int rv = 0; int i; char *init_name = NULL; pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type], addr_space_to_str[new_smi->io.addr_type], new_smi->io.addr_data, new_smi->io.slave_addr, new_smi->io.irq); switch (new_smi->io.si_type) { case SI_KCS: new_smi->handlers = &kcs_smi_handlers; break; case SI_SMIC: new_smi->handlers = &smic_smi_handlers; break; case SI_BT: new_smi->handlers = &bt_smi_handlers; break; default: /* No support for anything else yet. */ rv = -EIO; goto out_err; } new_smi->si_num = smi_num; /* Do this early so it's available for logs. */ if (!new_smi->io.dev) { init_name = kasprintf(GFP_KERNEL, "ipmi_si.%d", new_smi->si_num); /* * If we don't already have a device from something * else (like PCI), then register a new one. */ new_smi->pdev = platform_device_alloc("ipmi_si", new_smi->si_num); if (!new_smi->pdev) { pr_err("Unable to allocate platform device\n"); rv = -ENOMEM; goto out_err; } new_smi->io.dev = &new_smi->pdev->dev; new_smi->io.dev->driver = &ipmi_platform_driver.driver; /* Nulled by device_add() */ new_smi->io.dev->init_name = init_name; } /* Allocate the state machine's data and initialize it. */ new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL); if (!new_smi->si_sm) { rv = -ENOMEM; goto out_err; } new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm, &new_smi->io); /* Now that we know the I/O size, we can set up the I/O. */ rv = new_smi->io.io_setup(&new_smi->io); if (rv) { dev_err(new_smi->io.dev, "Could not set up I/O space\n"); goto out_err; } /* Do low-level detection first. */ if (new_smi->handlers->detect(new_smi->si_sm)) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "Interface detection failed\n"); rv = -ENODEV; goto out_err; } /* * Attempt a get device id command. If it fails, we probably * don't have a BMC here. */ rv = try_get_dev_id(new_smi); if (rv) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "There appears to be no BMC at this location\n"); goto out_err; } setup_oem_data_handler(new_smi); setup_xaction_handlers(new_smi); check_for_broken_irqs(new_smi); new_smi->waiting_msg = NULL; new_smi->curr_msg = NULL; atomic_set(&new_smi->req_events, 0); new_smi->run_to_completion = false; for (i = 0; i < SI_NUM_STATS; i++) atomic_set(&new_smi->stats[i], 0); new_smi->interrupt_disabled = true; atomic_set(&new_smi->need_watch, 0); rv = try_enable_event_buffer(new_smi); if (rv == 0) new_smi->has_event_buffer = true; /* * Start clearing the flags before we enable interrupts or the * timer to avoid racing with the timer. */ start_clear_flags(new_smi); /* * IRQ is defined to be set when non-zero. req_events will * cause a global flags check that will enable interrupts. */ if (new_smi->io.irq) { new_smi->interrupt_disabled = false; atomic_set(&new_smi->req_events, 1); } if (new_smi->pdev && !new_smi->pdev_registered) { rv = platform_device_add(new_smi->pdev); if (rv) { dev_err(new_smi->io.dev, "Unable to register system interface device: %d\n", rv); goto out_err; } new_smi->pdev_registered = true; } dev_set_drvdata(new_smi->io.dev, new_smi); rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group); if (rv) { dev_err(new_smi->io.dev, "Unable to add device attributes: error %d\n", rv); goto out_err; } new_smi->dev_group_added = true; rv = ipmi_register_smi(&handlers, new_smi, new_smi->io.dev, new_smi->io.slave_addr); if (rv) { dev_err(new_smi->io.dev, "Unable to register device: error %d\n", rv); goto out_err; } /* Don't increment till we know we have succeeded. */ smi_num++; dev_info(new_smi->io.dev, "IPMI %s interface initialized\n", si_to_str[new_smi->io.si_type]); WARN_ON(new_smi->io.dev->init_name != NULL); out_err: kfree(init_name); return rv; } Commit Message: ipmi_si: fix use-after-free of resource->name When we excute the following commands, we got oops rmmod ipmi_si cat /proc/ioports [ 1623.482380] Unable to handle kernel paging request at virtual address ffff00000901d478 [ 1623.482382] Mem abort info: [ 1623.482383] ESR = 0x96000007 [ 1623.482385] Exception class = DABT (current EL), IL = 32 bits [ 1623.482386] SET = 0, FnV = 0 [ 1623.482387] EA = 0, S1PTW = 0 [ 1623.482388] Data abort info: [ 1623.482389] ISV = 0, ISS = 0x00000007 [ 1623.482390] CM = 0, WnR = 0 [ 1623.482393] swapper pgtable: 4k pages, 48-bit VAs, pgdp = 00000000d7d94a66 [ 1623.482395] [ffff00000901d478] pgd=000000dffbfff003, pud=000000dffbffe003, pmd=0000003f5d06e003, pte=0000000000000000 [ 1623.482399] Internal error: Oops: 96000007 [#1] SMP [ 1623.487407] Modules linked in: ipmi_si(E) nls_utf8 isofs rpcrdma ib_iser ib_srpt target_core_mod ib_srp scsi_transport_srp ib_ipoib rdma_ucm ib_umad rdma_cm ib_cm dm_mirror dm_region_hash dm_log iw_cm dm_mod aes_ce_blk crypto_simd cryptd aes_ce_cipher ses ghash_ce sha2_ce enclosure sha256_arm64 sg sha1_ce hisi_sas_v2_hw hibmc_drm sbsa_gwdt hisi_sas_main ip_tables mlx5_ib ib_uverbs marvell ib_core mlx5_core ixgbe mdio hns_dsaf ipmi_devintf hns_enet_drv ipmi_msghandler hns_mdio [last unloaded: ipmi_si] [ 1623.532410] CPU: 30 PID: 11438 Comm: cat Kdump: loaded Tainted: G E 5.0.0-rc3+ #168 [ 1623.541498] Hardware name: Huawei TaiShan 2280 /BC11SPCD, BIOS 1.37 11/21/2017 [ 1623.548822] pstate: a0000005 (NzCv daif -PAN -UAO) [ 1623.553684] pc : string+0x28/0x98 [ 1623.557040] lr : vsnprintf+0x368/0x5e8 [ 1623.560837] sp : ffff000013213a80 [ 1623.564191] x29: ffff000013213a80 x28: ffff00001138abb5 [ 1623.569577] x27: ffff000013213c18 x26: ffff805f67d06049 [ 1623.574963] x25: 0000000000000000 x24: ffff00001138abb5 [ 1623.580349] x23: 0000000000000fb7 x22: ffff0000117ed000 [ 1623.585734] x21: ffff000011188fd8 x20: ffff805f67d07000 [ 1623.591119] x19: ffff805f67d06061 x18: ffffffffffffffff [ 1623.596505] x17: 0000000000000200 x16: 0000000000000000 [ 1623.601890] x15: ffff0000117ed748 x14: ffff805f67d07000 [ 1623.607276] x13: ffff805f67d0605e x12: 0000000000000000 [ 1623.612661] x11: 0000000000000000 x10: 0000000000000000 [ 1623.618046] x9 : 0000000000000000 x8 : 000000000000000f [ 1623.623432] x7 : ffff805f67d06061 x6 : fffffffffffffffe [ 1623.628817] x5 : 0000000000000012 x4 : ffff00000901d478 [ 1623.634203] x3 : ffff0a00ffffff04 x2 : ffff805f67d07000 [ 1623.639588] x1 : ffff805f67d07000 x0 : ffffffffffffffff [ 1623.644974] Process cat (pid: 11438, stack limit = 0x000000008d4cbc10) [ 1623.651592] Call trace: [ 1623.654068] string+0x28/0x98 [ 1623.657071] vsnprintf+0x368/0x5e8 [ 1623.660517] seq_vprintf+0x70/0x98 [ 1623.668009] seq_printf+0x7c/0xa0 [ 1623.675530] r_show+0xc8/0xf8 [ 1623.682558] seq_read+0x330/0x440 [ 1623.689877] proc_reg_read+0x78/0xd0 [ 1623.697346] __vfs_read+0x60/0x1a0 [ 1623.704564] vfs_read+0x94/0x150 [ 1623.711339] ksys_read+0x6c/0xd8 [ 1623.717939] __arm64_sys_read+0x24/0x30 [ 1623.725077] el0_svc_common+0x120/0x148 [ 1623.732035] el0_svc_handler+0x30/0x40 [ 1623.738757] el0_svc+0x8/0xc [ 1623.744520] Code: d1000406 aa0103e2 54000149 b4000080 (39400085) [ 1623.753441] ---[ end trace f91b6a4937de9835 ]--- [ 1623.760871] Kernel panic - not syncing: Fatal exception [ 1623.768935] SMP: stopping secondary CPUs [ 1623.775718] Kernel Offset: disabled [ 1623.781998] CPU features: 0x002,21006008 [ 1623.788777] Memory Limit: none [ 1623.798329] Starting crashdump kernel... [ 1623.805202] Bye! If io_setup is called successful in try_smi_init() but try_smi_init() goes out_err before calling ipmi_register_smi(), so ipmi_unregister_smi() will not be called while removing module. It leads to the resource that allocated in io_setup() can not be freed, but the name(DEVICE_NAME) of resource is freed while removing the module. It causes use-after-free when cat /proc/ioports. Fix this by calling io_cleanup() while try_smi_init() goes to out_err. and don't call io_cleanup() until io_setup() returns successful to avoid warning prints. Fixes: 93c303d2045b ("ipmi_si: Clean up shutdown a bit") Cc: [email protected] Reported-by: NuoHan Qiao <[email protected]> Suggested-by: Corey Minyard <[email protected]> Signed-off-by: Yang Yingliang <[email protected]> Signed-off-by: Corey Minyard <[email protected]> CWE ID: CWE-416
static int try_smi_init(struct smi_info *new_smi) { int rv = 0; int i; char *init_name = NULL; pr_info("Trying %s-specified %s state machine at %s address 0x%lx, slave address 0x%x, irq %d\n", ipmi_addr_src_to_str(new_smi->io.addr_source), si_to_str[new_smi->io.si_type], addr_space_to_str[new_smi->io.addr_type], new_smi->io.addr_data, new_smi->io.slave_addr, new_smi->io.irq); switch (new_smi->io.si_type) { case SI_KCS: new_smi->handlers = &kcs_smi_handlers; break; case SI_SMIC: new_smi->handlers = &smic_smi_handlers; break; case SI_BT: new_smi->handlers = &bt_smi_handlers; break; default: /* No support for anything else yet. */ rv = -EIO; goto out_err; } new_smi->si_num = smi_num; /* Do this early so it's available for logs. */ if (!new_smi->io.dev) { init_name = kasprintf(GFP_KERNEL, "ipmi_si.%d", new_smi->si_num); /* * If we don't already have a device from something * else (like PCI), then register a new one. */ new_smi->pdev = platform_device_alloc("ipmi_si", new_smi->si_num); if (!new_smi->pdev) { pr_err("Unable to allocate platform device\n"); rv = -ENOMEM; goto out_err; } new_smi->io.dev = &new_smi->pdev->dev; new_smi->io.dev->driver = &ipmi_platform_driver.driver; /* Nulled by device_add() */ new_smi->io.dev->init_name = init_name; } /* Allocate the state machine's data and initialize it. */ new_smi->si_sm = kmalloc(new_smi->handlers->size(), GFP_KERNEL); if (!new_smi->si_sm) { rv = -ENOMEM; goto out_err; } new_smi->io.io_size = new_smi->handlers->init_data(new_smi->si_sm, &new_smi->io); /* Now that we know the I/O size, we can set up the I/O. */ rv = new_smi->io.io_setup(&new_smi->io); if (rv) { dev_err(new_smi->io.dev, "Could not set up I/O space\n"); goto out_err; } /* Do low-level detection first. */ if (new_smi->handlers->detect(new_smi->si_sm)) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "Interface detection failed\n"); rv = -ENODEV; goto out_err; } /* * Attempt a get device id command. If it fails, we probably * don't have a BMC here. */ rv = try_get_dev_id(new_smi); if (rv) { if (new_smi->io.addr_source) dev_err(new_smi->io.dev, "There appears to be no BMC at this location\n"); goto out_err; } setup_oem_data_handler(new_smi); setup_xaction_handlers(new_smi); check_for_broken_irqs(new_smi); new_smi->waiting_msg = NULL; new_smi->curr_msg = NULL; atomic_set(&new_smi->req_events, 0); new_smi->run_to_completion = false; for (i = 0; i < SI_NUM_STATS; i++) atomic_set(&new_smi->stats[i], 0); new_smi->interrupt_disabled = true; atomic_set(&new_smi->need_watch, 0); rv = try_enable_event_buffer(new_smi); if (rv == 0) new_smi->has_event_buffer = true; /* * Start clearing the flags before we enable interrupts or the * timer to avoid racing with the timer. */ start_clear_flags(new_smi); /* * IRQ is defined to be set when non-zero. req_events will * cause a global flags check that will enable interrupts. */ if (new_smi->io.irq) { new_smi->interrupt_disabled = false; atomic_set(&new_smi->req_events, 1); } if (new_smi->pdev && !new_smi->pdev_registered) { rv = platform_device_add(new_smi->pdev); if (rv) { dev_err(new_smi->io.dev, "Unable to register system interface device: %d\n", rv); goto out_err; } new_smi->pdev_registered = true; } dev_set_drvdata(new_smi->io.dev, new_smi); rv = device_add_group(new_smi->io.dev, &ipmi_si_dev_attr_group); if (rv) { dev_err(new_smi->io.dev, "Unable to add device attributes: error %d\n", rv); goto out_err; } new_smi->dev_group_added = true; rv = ipmi_register_smi(&handlers, new_smi, new_smi->io.dev, new_smi->io.slave_addr); if (rv) { dev_err(new_smi->io.dev, "Unable to register device: error %d\n", rv); goto out_err; } /* Don't increment till we know we have succeeded. */ smi_num++; dev_info(new_smi->io.dev, "IPMI %s interface initialized\n", si_to_str[new_smi->io.si_type]); WARN_ON(new_smi->io.dev->init_name != NULL); out_err: if (rv && new_smi->io.io_cleanup) { new_smi->io.io_cleanup(&new_smi->io); new_smi->io.io_cleanup = NULL; } kfree(init_name); return rv; }
169,680
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LauncherView::ShowOverflowMenu() { #if !defined(OS_MACOSX) if (!delegate_) return; std::vector<LauncherItem> items; GetOverflowItems(&items); if (items.empty()) return; MenuDelegateImpl menu_delegate; ui::SimpleMenuModel menu_model(&menu_delegate); for (size_t i = 0; i < items.size(); ++i) menu_model.AddItem(static_cast<int>(i), delegate_->GetTitle(items[i])); views::MenuModelAdapter menu_adapter(&menu_model); overflow_menu_runner_.reset(new views::MenuRunner(menu_adapter.CreateMenu())); gfx::Rect bounds(overflow_button_->size()); gfx::Point origin; ConvertPointToScreen(overflow_button_, &origin); if (overflow_menu_runner_->RunMenuAt(GetWidget(), NULL, gfx::Rect(origin, size()), views::MenuItemView::TOPLEFT, 0) == views::MenuRunner::MENU_DELETED) return; Shell::GetInstance()->UpdateShelfVisibility(); if (menu_delegate.activated_command_id() == -1) return; LauncherID activated_id = items[menu_delegate.activated_command_id()].id; LauncherItems::const_iterator window_iter = model_->ItemByID(activated_id); if (window_iter == model_->items().end()) return; // Window was deleted while menu was up. delegate_->ItemClicked(*window_iter, ui::EF_NONE); #endif // !defined(OS_MACOSX) } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::ShowOverflowMenu() { void LauncherView::ShowOverflowBubble() { int first_overflow_index = last_visible_index_ + 1; DCHECK_LT(first_overflow_index, view_model_->view_size() - 1); if (!overflow_bubble_.get()) overflow_bubble_.reset(new OverflowBubble()); overflow_bubble_->Show(delegate_, model_, overflow_button_, alignment_, first_overflow_index); Shell::GetInstance()->UpdateShelfVisibility(); }
170,896
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function) { int scriptId = function->ScriptId(); if (scriptId == v8::UnboundScript::kNoScriptId) return v8::Null(m_isolate); int lineNumber = function->GetScriptLineNumber(); int columnNumber = function->GetScriptColumnNumber(); if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound) return v8::Null(m_isolate); v8::Local<v8::Object> location = v8::Object::New(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!markAsInternal(context, location, V8InternalValueType::kLocation)) return v8::Null(m_isolate); return location; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::Local<v8::Value> V8Debugger::functionLocation(v8::Local<v8::Context> context, v8::Local<v8::Function> function) { int scriptId = function->ScriptId(); if (scriptId == v8::UnboundScript::kNoScriptId) return v8::Null(m_isolate); int lineNumber = function->GetScriptLineNumber(); int columnNumber = function->GetScriptColumnNumber(); if (lineNumber == v8::Function::kLineOffsetNotFound || columnNumber == v8::Function::kLineOffsetNotFound) return v8::Null(m_isolate); v8::Local<v8::Object> location = v8::Object::New(m_isolate); if (!location->SetPrototype(context, v8::Null(m_isolate)).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "scriptId"), toV8String(m_isolate, String16::fromInteger(scriptId))).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "lineNumber"), v8::Integer::New(m_isolate, lineNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!location->Set(context, toV8StringInternalized(m_isolate, "columnNumber"), v8::Integer::New(m_isolate, columnNumber)).FromMaybe(false)) return v8::Null(m_isolate); if (!markAsInternal(context, location, V8InternalValueType::kLocation)) return v8::Null(m_isolate); return location; }
172,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long Chapters::Atom::GetTime( const Chapters* pChapters, long long timecode) { if (pChapters == NULL) return -1; Segment* const pSegment = pChapters->m_pSegment; if (pSegment == NULL) // weird return -1; const SegmentInfo* const pInfo = pSegment->GetInfo(); if (pInfo == NULL) return -1; const long long timecode_scale = pInfo->GetTimeCodeScale(); if (timecode_scale < 1) // weird return -1; if (timecode < 0) return -1; const long long result = timecode_scale * timecode; return result; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long Chapters::Atom::GetTime(
174,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cmd_handle_untagged(struct ImapData *idata) { unsigned int count = 0; char *s = imap_next_word(idata->buf); char *pn = imap_next_word(s); if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) { pn = s; s = imap_next_word(s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (mutt_str_strncasecmp("EXISTS", s, 6) == 0) { mutt_debug(2, "Handling EXISTS\n"); /* new mail arrived */ if (mutt_str_atoui(pn, &count) < 0) { mutt_debug(1, "Malformed EXISTS: '%s'\n", pn); } if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ mutt_debug(1, "Message count is out of sync\n"); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) mutt_debug(3, "superfluous EXISTS message.\n"); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->new_mail_count = count; } } /* pn vs. s: need initial seqno */ else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0) cmd_parse_expunge(idata, pn); else if (mutt_str_strncasecmp("FETCH", s, 5) == 0) cmd_parse_fetch(idata, pn); } else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0) cmd_parse_capability(idata, s); else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0) cmd_parse_capability(idata, pn); else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0) cmd_parse_capability(idata, imap_next_word(pn)); else if (mutt_str_strncasecmp("LIST", s, 4) == 0) cmd_parse_list(idata, s); else if (mutt_str_strncasecmp("LSUB", s, 4) == 0) cmd_parse_lsub(idata, s); else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0) cmd_parse_myrights(idata, s); else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0) cmd_parse_search(idata, s); else if (mutt_str_strncasecmp("STATUS", s, 6) == 0) cmd_parse_status(idata, s); else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0) cmd_parse_enabled(idata, s); else if (mutt_str_strncasecmp("BYE", s, 3) == 0) { mutt_debug(2, "Handling BYE\n"); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS(s); mutt_error("%s", s); cmd_handle_fatal(idata); return -1; } else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0)) { mutt_debug(2, "Handling untagged NO\n"); /* Display the warning message from the server */ mutt_error("%s", s + 3); } return 0; } Commit Message: Handle NO response without message properly CWE ID: CWE-20
static int cmd_handle_untagged(struct ImapData *idata) { unsigned int count = 0; char *s = imap_next_word(idata->buf); char *pn = imap_next_word(s); if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) { pn = s; s = imap_next_word(s); /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the * connection, so update that one. */ if (mutt_str_strncasecmp("EXISTS", s, 6) == 0) { mutt_debug(2, "Handling EXISTS\n"); /* new mail arrived */ if (mutt_str_atoui(pn, &count) < 0) { mutt_debug(1, "Malformed EXISTS: '%s'\n", pn); } if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) { /* Notes 6.0.3 has a tendency to report fewer messages exist than * it should. */ mutt_debug(1, "Message count is out of sync\n"); return 0; } /* at least the InterChange server sends EXISTS messages freely, * even when there is no new mail */ else if (count == idata->max_msn) mutt_debug(3, "superfluous EXISTS message.\n"); else { if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) { mutt_debug(2, "New mail in %s - %d messages total.\n", idata->mailbox, count); idata->reopen |= IMAP_NEWMAIL_PENDING; } idata->new_mail_count = count; } } /* pn vs. s: need initial seqno */ else if (mutt_str_strncasecmp("EXPUNGE", s, 7) == 0) cmd_parse_expunge(idata, pn); else if (mutt_str_strncasecmp("FETCH", s, 5) == 0) cmd_parse_fetch(idata, pn); } else if (mutt_str_strncasecmp("CAPABILITY", s, 10) == 0) cmd_parse_capability(idata, s); else if (mutt_str_strncasecmp("OK [CAPABILITY", s, 14) == 0) cmd_parse_capability(idata, pn); else if (mutt_str_strncasecmp("OK [CAPABILITY", pn, 14) == 0) cmd_parse_capability(idata, imap_next_word(pn)); else if (mutt_str_strncasecmp("LIST", s, 4) == 0) cmd_parse_list(idata, s); else if (mutt_str_strncasecmp("LSUB", s, 4) == 0) cmd_parse_lsub(idata, s); else if (mutt_str_strncasecmp("MYRIGHTS", s, 8) == 0) cmd_parse_myrights(idata, s); else if (mutt_str_strncasecmp("SEARCH", s, 6) == 0) cmd_parse_search(idata, s); else if (mutt_str_strncasecmp("STATUS", s, 6) == 0) cmd_parse_status(idata, s); else if (mutt_str_strncasecmp("ENABLED", s, 7) == 0) cmd_parse_enabled(idata, s); else if (mutt_str_strncasecmp("BYE", s, 3) == 0) { mutt_debug(2, "Handling BYE\n"); /* check if we're logging out */ if (idata->status == IMAP_BYE) return 0; /* server shut down our connection */ s += 3; SKIPWS(s); mutt_error("%s", s); cmd_handle_fatal(idata); return -1; } else if (ImapServernoise && (mutt_str_strncasecmp("NO", s, 2) == 0)) { mutt_debug(2, "Handling untagged NO\n"); /* Display the warning message from the server */ mutt_error("%s", s + 2); } return 0; }
169,139
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHYSICALPATH_FUNC(mod_alias_physical_handler) { plugin_data *p = p_d; int uri_len, basedir_len; char *uri_ptr; size_t k; if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON; mod_alias_patch_connection(srv, con, p); /* not to include the tailing slash */ basedir_len = buffer_string_length(con->physical.basedir); if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len; uri_len = buffer_string_length(con->physical.path) - basedir_len; uri_ptr = con->physical.path->ptr + basedir_len; for (k = 0; k < p->conf.alias->used; k++) { data_string *ds = (data_string *)p->conf.alias->data[k]; int alias_len = buffer_string_length(ds->key); if (alias_len > uri_len) continue; if (buffer_is_empty(ds->key)) continue; if (0 == (con->conf.force_lowercase_filenames ? strncasecmp(uri_ptr, ds->key->ptr, alias_len) : strncmp(uri_ptr, ds->key->ptr, alias_len))) { /* matched */ buffer_copy_buffer(con->physical.basedir, ds->value); buffer_copy_buffer(srv->tmp_buf, ds->value); buffer_append_string(srv->tmp_buf, uri_ptr + alias_len); buffer_copy_buffer(con->physical.path, srv->tmp_buf); return HANDLER_GO_ON; } } /* not found */ return HANDLER_GO_ON; } Commit Message: [mod_alias] security: potential path traversal with specific configs Security: potential path traversal of a single directory above the alias target with a specific mod_alias config where the alias which is matched does not end in '/', but alias target filesystem path does end in '/'. e.g. server.docroot = "/srv/www/host/HOSTNAME/docroot" alias.url = ( "/img" => "/srv/www/hosts/HOSTNAME/images/" ) If a malicious URL "/img../" were passed, the request would be for directory "/srv/www/hosts/HOSTNAME/images/../" which would resolve to "/srv/www/hosts/HOSTNAME/". If mod_dirlisting were enabled, which is not the default, this would result in listing the contents of the directory above the alias. An attacker might also try to directly access files anywhere under that path, which is one level above the intended aliased path. credit: Orange Tsai(@orange_8361) from DEVCORE CWE ID:
PHYSICALPATH_FUNC(mod_alias_physical_handler) { plugin_data *p = p_d; int uri_len, basedir_len; char *uri_ptr; size_t k; if (buffer_is_empty(con->physical.path)) return HANDLER_GO_ON; mod_alias_patch_connection(srv, con, p); /* not to include the tailing slash */ basedir_len = buffer_string_length(con->physical.basedir); if ('/' == con->physical.basedir->ptr[basedir_len-1]) --basedir_len; uri_len = buffer_string_length(con->physical.path) - basedir_len; uri_ptr = con->physical.path->ptr + basedir_len; for (k = 0; k < p->conf.alias->used; k++) { data_string *ds = (data_string *)p->conf.alias->data[k]; int alias_len = buffer_string_length(ds->key); if (alias_len > uri_len) continue; if (buffer_is_empty(ds->key)) continue; if (0 == (con->conf.force_lowercase_filenames ? strncasecmp(uri_ptr, ds->key->ptr, alias_len) : strncmp(uri_ptr, ds->key->ptr, alias_len))) { /* matched */ /* check for path traversal in url-path following alias if key * does not end in slash, but replacement value ends in slash */ if (uri_ptr[alias_len] == '.') { char *s = uri_ptr + alias_len + 1; if (*s == '.') ++s; if (*s == '/' || *s == '\0') { size_t vlen = buffer_string_length(ds->value); if (0 != alias_len && ds->key->ptr[alias_len-1] != '/' && 0 != vlen && ds->value->ptr[vlen-1] == '/') { con->http_status = 403; return HANDLER_FINISHED; } } } buffer_copy_buffer(con->physical.basedir, ds->value); buffer_copy_buffer(srv->tmp_buf, ds->value); buffer_append_string(srv->tmp_buf, uri_ptr + alias_len); buffer_copy_buffer(con->physical.path, srv->tmp_buf); return HANDLER_GO_ON; } } /* not found */ return HANDLER_GO_ON; }
168,979
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SimpleSoftOMXComponent::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *defParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (defParams->nPortIndex >= mPorts.size()) { return OMX_ErrorBadPortIndex; } if (defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) { return OMX_ErrorUnsupportedSetting; } PortInfo *port = &mPorts.editItemAt(defParams->nPortIndex); if (defParams->nBufferSize > port->mDef.nBufferSize) { port->mDef.nBufferSize = defParams->nBufferSize; } if (defParams->nBufferCountActual < port->mDef.nBufferCountMin) { ALOGW("component requires at least %u buffers (%u requested)", port->mDef.nBufferCountMin, defParams->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } port->mDef.nBufferCountActual = defParams->nBufferCountActual; return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SimpleSoftOMXComponent::internalSetParameter( OMX_INDEXTYPE index, const OMX_PTR params) { switch (index) { case OMX_IndexParamPortDefinition: { OMX_PARAM_PORTDEFINITIONTYPE *defParams = (OMX_PARAM_PORTDEFINITIONTYPE *)params; if (!isValidOMXParam(defParams)) { return OMX_ErrorBadParameter; } if (defParams->nPortIndex >= mPorts.size()) { return OMX_ErrorBadPortIndex; } if (defParams->nSize != sizeof(OMX_PARAM_PORTDEFINITIONTYPE)) { return OMX_ErrorUnsupportedSetting; } PortInfo *port = &mPorts.editItemAt(defParams->nPortIndex); if (defParams->nBufferSize > port->mDef.nBufferSize) { port->mDef.nBufferSize = defParams->nBufferSize; } if (defParams->nBufferCountActual < port->mDef.nBufferCountMin) { ALOGW("component requires at least %u buffers (%u requested)", port->mDef.nBufferCountMin, defParams->nBufferCountActual); return OMX_ErrorUnsupportedSetting; } port->mDef.nBufferCountActual = defParams->nBufferCountActual; return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } }
174,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: UserSelectionScreen::UpdateAndReturnUserListForWebUI() { std::unique_ptr<base::ListValue> users_list = std::make_unique<base::ListValue>(); const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (user_manager::UserList::const_iterator it = users_to_send_.begin(); it != users_to_send_.end(); ++it) { const AccountId& account_id = (*it)->GetAccountId(); bool is_owner = (account_id == owner); const bool is_public_account = ((*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(*it) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; auto user_dict = std::make_unique<base::DictionaryValue>(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; FillUserDictionary(*it, is_owner, is_signin_to_add, initial_auth_type, public_session_recommended_locales, user_dict.get()); user_dict->SetBoolean(kKeyCanRemove, CanRemoveUser(*it)); users_list->Append(std::move(user_dict)); } return users_list; } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <[email protected]> Commit-Queue: Jacob Dufault <[email protected]> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
UserSelectionScreen::UpdateAndReturnUserListForWebUI() { std::unique_ptr<base::ListValue> users_list = std::make_unique<base::ListValue>(); const AccountId owner = GetOwnerAccountId(); const bool is_signin_to_add = IsSigninToAdd(); users_to_send_ = PrepareUserListForSending(users_, owner, is_signin_to_add); user_auth_type_map_.clear(); for (const user_manager::User* user : users_to_send_) { const AccountId& account_id = user->GetAccountId(); bool is_owner = (account_id == owner); const bool is_public_account = user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; const proximity_auth::mojom::AuthType initial_auth_type = is_public_account ? proximity_auth::mojom::AuthType::EXPAND_THEN_USER_CLICK : (ShouldForceOnlineSignIn(user) ? proximity_auth::mojom::AuthType::ONLINE_SIGN_IN : proximity_auth::mojom::AuthType::OFFLINE_PASSWORD); user_auth_type_map_[account_id] = initial_auth_type; auto user_dict = std::make_unique<base::DictionaryValue>(); const std::vector<std::string>* public_session_recommended_locales = public_session_recommended_locales_.find(account_id) == public_session_recommended_locales_.end() ? nullptr : &public_session_recommended_locales_[account_id]; FillUserDictionary(user, is_owner, is_signin_to_add, initial_auth_type, public_session_recommended_locales, user_dict.get()); user_dict->SetBoolean(kKeyCanRemove, CanRemoveUser(user)); users_list->Append(std::move(user_dict)); } return users_list; }
172,205
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltDocumentElem(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemDocumentPtr comp = (xsltStyleItemDocumentPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xsltStylesheetPtr style = NULL; int ret; xmlChar *filename = NULL, *prop, *elements; xmlChar *element, *end; xmlDocPtr res = NULL; xmlDocPtr oldOutput; xmlNodePtr oldInsert, root; const char *oldOutputFile; xsltOutputType oldType; xmlChar *URL = NULL; const xmlChar *method; const xmlChar *doctypePublic; const xmlChar *doctypeSystem; const xmlChar *version; const xmlChar *encoding; int redirect_write_append = 0; if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; if (comp->filename == NULL) { if (xmlStrEqual(inst->name, (const xmlChar *) "output")) { /* * The element "output" is in the namespace XSLT_SAXON_NAMESPACE * (http://icl.com/saxon) * The @file is in no namespace. */ #ifdef WITH_XSLT_DEBUG_EXTRA xsltGenericDebug(xsltGenericDebugContext, "Found saxon:output extension\n"); #endif URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "file", XSLT_SAXON_NAMESPACE); if (URL == NULL) URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "href", XSLT_SAXON_NAMESPACE); } else if (xmlStrEqual(inst->name, (const xmlChar *) "write")) { #ifdef WITH_XSLT_DEBUG_EXTRA xsltGenericDebug(xsltGenericDebugContext, "Found xalan:write extension\n"); #endif URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "select", XSLT_XALAN_NAMESPACE); if (URL != NULL) { xmlXPathCompExprPtr cmp; xmlChar *val; /* * Trying to handle bug #59212 * The value of the "select" attribute is an * XPath expression. * (see http://xml.apache.org/xalan-j/extensionslib.html#redirect) */ cmp = xmlXPathCompile(URL); val = xsltEvalXPathString(ctxt, cmp); xmlXPathFreeCompExpr(cmp); xmlFree(URL); URL = val; } if (URL == NULL) URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "file", XSLT_XALAN_NAMESPACE); if (URL == NULL) URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "href", XSLT_XALAN_NAMESPACE); } else if (xmlStrEqual(inst->name, (const xmlChar *) "document")) { URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "href", NULL); } } else { URL = xmlStrdup(comp->filename); } if (URL == NULL) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: href/URI-Reference not found\n"); return; } /* * If the computation failed, it's likely that the URL wasn't escaped */ filename = xmlBuildURI(URL, (const xmlChar *) ctxt->outputFile); if (filename == NULL) { xmlChar *escURL; escURL=xmlURIEscapeStr(URL, BAD_CAST ":/.?,"); if (escURL != NULL) { filename = xmlBuildURI(escURL, (const xmlChar *) ctxt->outputFile); xmlFree(escURL); } } if (filename == NULL) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: URL computation failed for %s\n", URL); xmlFree(URL); return; } /* * Security checking: can we write to this resource */ if (ctxt->sec != NULL) { ret = xsltCheckWrite(ctxt->sec, ctxt, filename); if (ret == 0) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: write rights for %s denied\n", filename); xmlFree(URL); xmlFree(filename); return; } } oldOutputFile = ctxt->outputFile; oldOutput = ctxt->output; oldInsert = ctxt->insert; oldType = ctxt->type; ctxt->outputFile = (const char *) filename; style = xsltNewStylesheet(); if (style == NULL) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: out of memory\n"); goto error; } /* * Version described in 1.1 draft allows full parameterization * of the output. */ prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "version", NULL); if (prop != NULL) { if (style->version != NULL) xmlFree(style->version); style->version = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "encoding", NULL); if (prop != NULL) { if (style->encoding != NULL) xmlFree(style->encoding); style->encoding = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "method", NULL); if (prop != NULL) { const xmlChar *URI; if (style->method != NULL) xmlFree(style->method); style->method = NULL; if (style->methodURI != NULL) xmlFree(style->methodURI); style->methodURI = NULL; URI = xsltGetQNameURI(inst, &prop); if (prop == NULL) { if (style != NULL) style->errors++; } else if (URI == NULL) { if ((xmlStrEqual(prop, (const xmlChar *) "xml")) || (xmlStrEqual(prop, (const xmlChar *) "html")) || (xmlStrEqual(prop, (const xmlChar *) "text"))) { style->method = prop; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for method: %s\n", prop); if (style != NULL) style->warnings++; } } else { style->method = prop; style->methodURI = xmlStrdup(URI); } } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "doctype-system", NULL); if (prop != NULL) { if (style->doctypeSystem != NULL) xmlFree(style->doctypeSystem); style->doctypeSystem = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "doctype-public", NULL); if (prop != NULL) { if (style->doctypePublic != NULL) xmlFree(style->doctypePublic); style->doctypePublic = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "standalone", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "yes")) { style->standalone = 1; } else if (xmlStrEqual(prop, (const xmlChar *) "no")) { style->standalone = 0; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for standalone: %s\n", prop); if (style != NULL) style->warnings++; } xmlFree(prop); } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "indent", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "yes")) { style->indent = 1; } else if (xmlStrEqual(prop, (const xmlChar *) "no")) { style->indent = 0; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for indent: %s\n", prop); if (style != NULL) style->warnings++; } xmlFree(prop); } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "omit-xml-declaration", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "yes")) { style->omitXmlDeclaration = 1; } else if (xmlStrEqual(prop, (const xmlChar *) "no")) { style->omitXmlDeclaration = 0; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for omit-xml-declaration: %s\n", prop); if (style != NULL) style->warnings++; } xmlFree(prop); } elements = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "cdata-section-elements", NULL); if (elements != NULL) { if (style->stripSpaces == NULL) style->stripSpaces = xmlHashCreate(10); if (style->stripSpaces == NULL) return; element = elements; while (*element != 0) { while (IS_BLANK_CH(*element)) element++; if (*element == 0) break; end = element; while ((*end != 0) && (!IS_BLANK_CH(*end))) end++; element = xmlStrndup(element, end - element); if (element) { const xmlChar *URI; #ifdef WITH_XSLT_DEBUG_PARSING xsltGenericDebug(xsltGenericDebugContext, "add cdata section output element %s\n", element); #endif URI = xsltGetQNameURI(inst, &element); xmlHashAddEntry2(style->stripSpaces, element, URI, (xmlChar *) "cdata"); xmlFree(element); } element = end; } xmlFree(elements); } /* * Create a new document tree and process the element template */ XSLT_GET_IMPORT_PTR(method, style, method) XSLT_GET_IMPORT_PTR(doctypePublic, style, doctypePublic) XSLT_GET_IMPORT_PTR(doctypeSystem, style, doctypeSystem) XSLT_GET_IMPORT_PTR(version, style, version) XSLT_GET_IMPORT_PTR(encoding, style, encoding) if ((method != NULL) && (!xmlStrEqual(method, (const xmlChar *) "xml"))) { if (xmlStrEqual(method, (const xmlChar *) "html")) { ctxt->type = XSLT_OUTPUT_HTML; if (((doctypePublic != NULL) || (doctypeSystem != NULL))) res = htmlNewDoc(doctypeSystem, doctypePublic); else { if (version != NULL) { #ifdef XSLT_GENERATE_HTML_DOCTYPE xsltGetHTMLIDs(version, &doctypePublic, &doctypeSystem); #endif } res = htmlNewDocNoDtD(doctypeSystem, doctypePublic); } if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); } else if (xmlStrEqual(method, (const xmlChar *) "xhtml")) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: unsupported method xhtml\n", style->method); ctxt->type = XSLT_OUTPUT_HTML; res = htmlNewDocNoDtD(doctypeSystem, doctypePublic); if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); } else if (xmlStrEqual(method, (const xmlChar *) "text")) { ctxt->type = XSLT_OUTPUT_TEXT; res = xmlNewDoc(style->version); if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); #ifdef WITH_XSLT_DEBUG xsltGenericDebug(xsltGenericDebugContext, "reusing transformation dict for output\n"); #endif } else { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: unsupported method %s\n", style->method); goto error; } } else { ctxt->type = XSLT_OUTPUT_XML; res = xmlNewDoc(style->version); if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); #ifdef WITH_XSLT_DEBUG xsltGenericDebug(xsltGenericDebugContext, "reusing transformation dict for output\n"); #endif } res->charset = XML_CHAR_ENCODING_UTF8; if (encoding != NULL) res->encoding = xmlStrdup(encoding); ctxt->output = res; ctxt->insert = (xmlNodePtr) res; xsltApplySequenceConstructor(ctxt, node, inst->children, NULL); /* * Do some post processing work depending on the generated output */ root = xmlDocGetRootElement(res); if (root != NULL) { const xmlChar *doctype = NULL; if ((root->ns != NULL) && (root->ns->prefix != NULL)) doctype = xmlDictQLookup(ctxt->dict, root->ns->prefix, root->name); if (doctype == NULL) doctype = root->name; /* * Apply the default selection of the method */ if ((method == NULL) && (root->ns == NULL) && (!xmlStrcasecmp(root->name, (const xmlChar *) "html"))) { xmlNodePtr tmp; tmp = res->children; while ((tmp != NULL) && (tmp != root)) { if (tmp->type == XML_ELEMENT_NODE) break; if ((tmp->type == XML_TEXT_NODE) && (!xmlIsBlankNode(tmp))) break; tmp = tmp->next; } if (tmp == root) { ctxt->type = XSLT_OUTPUT_HTML; res->type = XML_HTML_DOCUMENT_NODE; if (((doctypePublic != NULL) || (doctypeSystem != NULL))) { res->intSubset = xmlCreateIntSubset(res, doctype, doctypePublic, doctypeSystem); #ifdef XSLT_GENERATE_HTML_DOCTYPE } else if (version != NULL) { xsltGetHTMLIDs(version, &doctypePublic, &doctypeSystem); if (((doctypePublic != NULL) || (doctypeSystem != NULL))) res->intSubset = xmlCreateIntSubset(res, doctype, doctypePublic, doctypeSystem); #endif } } } if (ctxt->type == XSLT_OUTPUT_XML) { XSLT_GET_IMPORT_PTR(doctypePublic, style, doctypePublic) XSLT_GET_IMPORT_PTR(doctypeSystem, style, doctypeSystem) if (((doctypePublic != NULL) || (doctypeSystem != NULL))) res->intSubset = xmlCreateIntSubset(res, doctype, doctypePublic, doctypeSystem); } } /* * Calls to redirect:write also take an optional attribute append. * Attribute append="true|yes" which will attempt to simply append * to an existing file instead of always opening a new file. The * default behavior of always overwriting the file still happens * if we do not specify append. * Note that append use will forbid use of remote URI target. */ prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *)"append", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "true") || xmlStrEqual(prop, (const xmlChar *) "yes")) { style->omitXmlDeclaration = 1; redirect_write_append = 1; } else style->omitXmlDeclaration = 0; xmlFree(prop); } if (redirect_write_append) { FILE *f; f = fopen((const char *) filename, "ab"); if (f == NULL) { ret = -1; } else { ret = xsltSaveResultToFile(f, res, style); fclose(f); } } else { ret = xsltSaveResultToFilename((const char *) filename, res, style, 0); } if (ret < 0) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: unable to save to %s\n", filename); ctxt->state = XSLT_STATE_ERROR; #ifdef WITH_XSLT_DEBUG_EXTRA } else { xsltGenericDebug(xsltGenericDebugContext, "Wrote %d bytes to %s\n", ret, filename); #endif } error: ctxt->output = oldOutput; ctxt->insert = oldInsert; ctxt->type = oldType; ctxt->outputFile = oldOutputFile; if (URL != NULL) xmlFree(URL); if (filename != NULL) xmlFree(filename); if (style != NULL) xsltFreeStylesheet(style); if (res != NULL) xmlFreeDoc(res); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
xsltDocumentElem(xsltTransformContextPtr ctxt, xmlNodePtr node, xmlNodePtr inst, xsltStylePreCompPtr castedComp) { #ifdef XSLT_REFACTORED xsltStyleItemDocumentPtr comp = (xsltStyleItemDocumentPtr) castedComp; #else xsltStylePreCompPtr comp = castedComp; #endif xsltStylesheetPtr style = NULL; int ret; xmlChar *filename = NULL, *prop, *elements; xmlChar *element, *end; xmlDocPtr res = NULL; xmlDocPtr oldOutput; xmlNodePtr oldInsert, root; const char *oldOutputFile; xsltOutputType oldType; xmlChar *URL = NULL; const xmlChar *method; const xmlChar *doctypePublic; const xmlChar *doctypeSystem; const xmlChar *version; const xmlChar *encoding; int redirect_write_append = 0; if ((ctxt == NULL) || (node == NULL) || (inst == NULL) || (comp == NULL)) return; if (comp->filename == NULL) { if (xmlStrEqual(inst->name, (const xmlChar *) "output")) { /* * The element "output" is in the namespace XSLT_SAXON_NAMESPACE * (http://icl.com/saxon) * The @file is in no namespace. */ #ifdef WITH_XSLT_DEBUG_EXTRA xsltGenericDebug(xsltGenericDebugContext, "Found saxon:output extension\n"); #endif URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "file", XSLT_SAXON_NAMESPACE); if (URL == NULL) URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "href", XSLT_SAXON_NAMESPACE); } else if (xmlStrEqual(inst->name, (const xmlChar *) "write")) { #ifdef WITH_XSLT_DEBUG_EXTRA xsltGenericDebug(xsltGenericDebugContext, "Found xalan:write extension\n"); #endif URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "select", XSLT_XALAN_NAMESPACE); if (URL != NULL) { xmlXPathCompExprPtr cmp; xmlChar *val; /* * Trying to handle bug #59212 * The value of the "select" attribute is an * XPath expression. * (see http://xml.apache.org/xalan-j/extensionslib.html#redirect) */ cmp = xmlXPathCompile(URL); val = xsltEvalXPathString(ctxt, cmp); xmlXPathFreeCompExpr(cmp); xmlFree(URL); URL = val; } if (URL == NULL) URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "file", XSLT_XALAN_NAMESPACE); if (URL == NULL) URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "href", XSLT_XALAN_NAMESPACE); } else if (xmlStrEqual(inst->name, (const xmlChar *) "document")) { URL = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "href", NULL); } } else { URL = xmlStrdup(comp->filename); } if (URL == NULL) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: href/URI-Reference not found\n"); return; } /* * If the computation failed, it's likely that the URL wasn't escaped */ filename = xmlBuildURI(URL, (const xmlChar *) ctxt->outputFile); if (filename == NULL) { xmlChar *escURL; escURL=xmlURIEscapeStr(URL, BAD_CAST ":/.?,"); if (escURL != NULL) { filename = xmlBuildURI(escURL, (const xmlChar *) ctxt->outputFile); xmlFree(escURL); } } if (filename == NULL) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: URL computation failed for %s\n", URL); xmlFree(URL); return; } /* * Security checking: can we write to this resource */ if (ctxt->sec != NULL) { ret = xsltCheckWrite(ctxt->sec, ctxt, filename); if (ret == 0) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: write rights for %s denied\n", filename); xmlFree(URL); xmlFree(filename); return; } } oldOutputFile = ctxt->outputFile; oldOutput = ctxt->output; oldInsert = ctxt->insert; oldType = ctxt->type; ctxt->outputFile = (const char *) filename; style = xsltNewStylesheet(); if (style == NULL) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: out of memory\n"); goto error; } /* * Version described in 1.1 draft allows full parameterization * of the output. */ prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "version", NULL); if (prop != NULL) { if (style->version != NULL) xmlFree(style->version); style->version = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "encoding", NULL); if (prop != NULL) { if (style->encoding != NULL) xmlFree(style->encoding); style->encoding = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "method", NULL); if (prop != NULL) { const xmlChar *URI; if (style->method != NULL) xmlFree(style->method); style->method = NULL; if (style->methodURI != NULL) xmlFree(style->methodURI); style->methodURI = NULL; URI = xsltGetQNameURI(inst, &prop); if (prop == NULL) { if (style != NULL) style->errors++; } else if (URI == NULL) { if ((xmlStrEqual(prop, (const xmlChar *) "xml")) || (xmlStrEqual(prop, (const xmlChar *) "html")) || (xmlStrEqual(prop, (const xmlChar *) "text"))) { style->method = prop; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for method: %s\n", prop); if (style != NULL) style->warnings++; } } else { style->method = prop; style->methodURI = xmlStrdup(URI); } } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "doctype-system", NULL); if (prop != NULL) { if (style->doctypeSystem != NULL) xmlFree(style->doctypeSystem); style->doctypeSystem = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "doctype-public", NULL); if (prop != NULL) { if (style->doctypePublic != NULL) xmlFree(style->doctypePublic); style->doctypePublic = prop; } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "standalone", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "yes")) { style->standalone = 1; } else if (xmlStrEqual(prop, (const xmlChar *) "no")) { style->standalone = 0; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for standalone: %s\n", prop); if (style != NULL) style->warnings++; } xmlFree(prop); } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "indent", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "yes")) { style->indent = 1; } else if (xmlStrEqual(prop, (const xmlChar *) "no")) { style->indent = 0; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for indent: %s\n", prop); if (style != NULL) style->warnings++; } xmlFree(prop); } prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "omit-xml-declaration", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "yes")) { style->omitXmlDeclaration = 1; } else if (xmlStrEqual(prop, (const xmlChar *) "no")) { style->omitXmlDeclaration = 0; } else { xsltTransformError(ctxt, NULL, inst, "invalid value for omit-xml-declaration: %s\n", prop); if (style != NULL) style->warnings++; } xmlFree(prop); } elements = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *) "cdata-section-elements", NULL); if (elements != NULL) { if (style->stripSpaces == NULL) style->stripSpaces = xmlHashCreate(10); if (style->stripSpaces == NULL) return; element = elements; while (*element != 0) { while (IS_BLANK_CH(*element)) element++; if (*element == 0) break; end = element; while ((*end != 0) && (!IS_BLANK_CH(*end))) end++; element = xmlStrndup(element, end - element); if (element) { const xmlChar *URI; #ifdef WITH_XSLT_DEBUG_PARSING xsltGenericDebug(xsltGenericDebugContext, "add cdata section output element %s\n", element); #endif URI = xsltGetQNameURI(inst, &element); xmlHashAddEntry2(style->stripSpaces, element, URI, (xmlChar *) "cdata"); xmlFree(element); } element = end; } xmlFree(elements); } /* * Create a new document tree and process the element template */ XSLT_GET_IMPORT_PTR(method, style, method) XSLT_GET_IMPORT_PTR(doctypePublic, style, doctypePublic) XSLT_GET_IMPORT_PTR(doctypeSystem, style, doctypeSystem) XSLT_GET_IMPORT_PTR(version, style, version) XSLT_GET_IMPORT_PTR(encoding, style, encoding) if ((method != NULL) && (!xmlStrEqual(method, (const xmlChar *) "xml"))) { if (xmlStrEqual(method, (const xmlChar *) "html")) { ctxt->type = XSLT_OUTPUT_HTML; if (((doctypePublic != NULL) || (doctypeSystem != NULL))) res = htmlNewDoc(doctypeSystem, doctypePublic); else { if (version != NULL) { #ifdef XSLT_GENERATE_HTML_DOCTYPE xsltGetHTMLIDs(version, &doctypePublic, &doctypeSystem); #endif } res = htmlNewDocNoDtD(doctypeSystem, doctypePublic); } if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); } else if (xmlStrEqual(method, (const xmlChar *) "xhtml")) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: unsupported method xhtml\n"); ctxt->type = XSLT_OUTPUT_HTML; res = htmlNewDocNoDtD(doctypeSystem, doctypePublic); if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); } else if (xmlStrEqual(method, (const xmlChar *) "text")) { ctxt->type = XSLT_OUTPUT_TEXT; res = xmlNewDoc(style->version); if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); #ifdef WITH_XSLT_DEBUG xsltGenericDebug(xsltGenericDebugContext, "reusing transformation dict for output\n"); #endif } else { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: unsupported method (%s)\n", method); goto error; } } else { ctxt->type = XSLT_OUTPUT_XML; res = xmlNewDoc(style->version); if (res == NULL) goto error; res->dict = ctxt->dict; xmlDictReference(res->dict); #ifdef WITH_XSLT_DEBUG xsltGenericDebug(xsltGenericDebugContext, "reusing transformation dict for output\n"); #endif } res->charset = XML_CHAR_ENCODING_UTF8; if (encoding != NULL) res->encoding = xmlStrdup(encoding); ctxt->output = res; ctxt->insert = (xmlNodePtr) res; xsltApplySequenceConstructor(ctxt, node, inst->children, NULL); /* * Do some post processing work depending on the generated output */ root = xmlDocGetRootElement(res); if (root != NULL) { const xmlChar *doctype = NULL; if ((root->ns != NULL) && (root->ns->prefix != NULL)) doctype = xmlDictQLookup(ctxt->dict, root->ns->prefix, root->name); if (doctype == NULL) doctype = root->name; /* * Apply the default selection of the method */ if ((method == NULL) && (root->ns == NULL) && (!xmlStrcasecmp(root->name, (const xmlChar *) "html"))) { xmlNodePtr tmp; tmp = res->children; while ((tmp != NULL) && (tmp != root)) { if (tmp->type == XML_ELEMENT_NODE) break; if ((tmp->type == XML_TEXT_NODE) && (!xmlIsBlankNode(tmp))) break; tmp = tmp->next; } if (tmp == root) { ctxt->type = XSLT_OUTPUT_HTML; res->type = XML_HTML_DOCUMENT_NODE; if (((doctypePublic != NULL) || (doctypeSystem != NULL))) { res->intSubset = xmlCreateIntSubset(res, doctype, doctypePublic, doctypeSystem); #ifdef XSLT_GENERATE_HTML_DOCTYPE } else if (version != NULL) { xsltGetHTMLIDs(version, &doctypePublic, &doctypeSystem); if (((doctypePublic != NULL) || (doctypeSystem != NULL))) res->intSubset = xmlCreateIntSubset(res, doctype, doctypePublic, doctypeSystem); #endif } } } if (ctxt->type == XSLT_OUTPUT_XML) { XSLT_GET_IMPORT_PTR(doctypePublic, style, doctypePublic) XSLT_GET_IMPORT_PTR(doctypeSystem, style, doctypeSystem) if (((doctypePublic != NULL) || (doctypeSystem != NULL))) res->intSubset = xmlCreateIntSubset(res, doctype, doctypePublic, doctypeSystem); } } /* * Calls to redirect:write also take an optional attribute append. * Attribute append="true|yes" which will attempt to simply append * to an existing file instead of always opening a new file. The * default behavior of always overwriting the file still happens * if we do not specify append. * Note that append use will forbid use of remote URI target. */ prop = xsltEvalAttrValueTemplate(ctxt, inst, (const xmlChar *)"append", NULL); if (prop != NULL) { if (xmlStrEqual(prop, (const xmlChar *) "true") || xmlStrEqual(prop, (const xmlChar *) "yes")) { style->omitXmlDeclaration = 1; redirect_write_append = 1; } else style->omitXmlDeclaration = 0; xmlFree(prop); } if (redirect_write_append) { FILE *f; f = fopen((const char *) filename, "ab"); if (f == NULL) { ret = -1; } else { ret = xsltSaveResultToFile(f, res, style); fclose(f); } } else { ret = xsltSaveResultToFilename((const char *) filename, res, style, 0); } if (ret < 0) { xsltTransformError(ctxt, NULL, inst, "xsltDocumentElem: unable to save to %s\n", filename); ctxt->state = XSLT_STATE_ERROR; #ifdef WITH_XSLT_DEBUG_EXTRA } else { xsltGenericDebug(xsltGenericDebugContext, "Wrote %d bytes to %s\n", ret, filename); #endif } error: ctxt->output = oldOutput; ctxt->insert = oldInsert; ctxt->type = oldType; ctxt->outputFile = oldOutputFile; if (URL != NULL) xmlFree(URL); if (filename != NULL) xmlFree(filename); if (style != NULL) xsltFreeStylesheet(style); if (res != NULL) xmlFreeDoc(res); }
173,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char* cJSON_strdup( const char* str ) { size_t len; char* copy; len = strlen( str ) + 1; if ( ! ( copy = (char*) cJSON_malloc( len ) ) ) return 0; memcpy( copy, str, len ); return copy; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static char* cJSON_strdup( const char* str ) void cJSON_InitHooks(cJSON_Hooks* hooks) { if (!hooks) { /* Reset hooks */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; cJSON_free = (hooks->free_fn)?hooks->free_fn:free; }
167,298
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool WebRequestPermissions::HideRequest( const extensions::InfoMap* extension_info_map, const extensions::WebRequestInfo& request) { if (request.is_web_view) return false; if (request.is_pac_request) return true; bool is_request_from_browser = request.render_process_id == -1; bool is_request_from_webui_renderer = false; if (!is_request_from_browser) { if (request.is_web_view) return false; if (extension_info_map && extension_info_map->process_map().Contains(extensions::kWebStoreAppId, request.render_process_id)) { return true; } is_request_from_webui_renderer = content::ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings( request.render_process_id); } return IsSensitiveURL(request.url, is_request_from_browser || is_request_from_webui_renderer) || !HasWebRequestScheme(request.url); } Commit Message: Hide DevTools frontend from webRequest API Prevent extensions from observing requests for remote DevTools frontends and add regression tests. And update ExtensionTestApi to support initializing the embedded test server and port from SetUpCommandLine (before SetUpOnMainThread). BUG=797497,797500 TEST=browser_test --gtest_filter=DevToolsFrontendInWebRequestApiTest.HiddenRequests Cq-Include-Trybots: master.tryserver.chromium.linux:linux_mojo Change-Id: Ic8f44b5771f2d5796f8c3de128f0a7ab88a77735 Reviewed-on: https://chromium-review.googlesource.com/844316 Commit-Queue: Rob Wu <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Dmitry Gozman <[email protected]> Cr-Commit-Position: refs/heads/master@{#528187} CWE ID: CWE-200
bool WebRequestPermissions::HideRequest( const extensions::InfoMap* extension_info_map, const extensions::WebRequestInfo& request) { if (request.is_web_view) return false; if (request.is_pac_request) return true; bool is_request_from_browser = request.render_process_id == -1 && // Browser requests are often of the "other" resource type. // Main frame requests are not unconditionally seen as a sensitive browser // request, because a request can also be browser-driven if there is no // process to associate the request with. E.g. navigations via the // chrome.tabs.update extension API. request.type != content::RESOURCE_TYPE_MAIN_FRAME; bool is_request_from_webui_renderer = false; if (!is_request_from_browser) { if (request.is_web_view) return false; if (extension_info_map && extension_info_map->process_map().Contains(extensions::kWebStoreAppId, request.render_process_id)) { return true; } is_request_from_webui_renderer = content::ChildProcessSecurityPolicy::GetInstance()->HasWebUIBindings( request.render_process_id); } return IsSensitiveURL(request.url, is_request_from_browser || is_request_from_webui_renderer) || !HasWebRequestScheme(request.url); }
172,672
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; params = malloc(sizeof(TEE_Attribute) * param_count); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; } Commit Message: svc: check for allocation overflow in crypto calls Without checking for overflow there is a risk of allocating a buffer with size smaller than anticipated and as a consequence of that it might lead to a heap based overflow with attacker controlled data written outside the boundaries of the buffer. Fixes: OP-TEE-2018-0010: "Integer overflow in crypto system calls (x2)" Signed-off-by: Joakim Bech <[email protected]> Tested-by: Joakim Bech <[email protected]> (QEMU v7, v8) Reviewed-by: Jens Wiklander <[email protected]> Reported-by: Riscure <[email protected]> Reported-by: Alyssa Milburn <[email protected]> Acked-by: Etienne Carriere <[email protected]> CWE ID: CWE-119
TEE_Result syscall_cryp_derive_key(unsigned long state, const struct utee_attribute *usr_params, unsigned long param_count, unsigned long derived_key) { TEE_Result res = TEE_ERROR_NOT_SUPPORTED; struct tee_ta_session *sess; struct tee_obj *ko; struct tee_obj *so; struct tee_cryp_state *cs; struct tee_cryp_obj_secret *sk; const struct tee_cryp_obj_type_props *type_props; TEE_Attribute *params = NULL; struct user_ta_ctx *utc; res = tee_ta_get_current_session(&sess); if (res != TEE_SUCCESS) return res; utc = to_user_ta_ctx(sess->ctx); res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs); if (res != TEE_SUCCESS) return res; size_t alloc_size = 0; if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size)) return TEE_ERROR_OVERFLOW; params = malloc(alloc_size); if (!params) return TEE_ERROR_OUT_OF_MEMORY; res = copy_in_attrs(utc, usr_params, param_count, params); if (res != TEE_SUCCESS) goto out; /* Get key set in operation */ res = tee_obj_get(utc, cs->key1, &ko); if (res != TEE_SUCCESS) goto out; res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so); if (res != TEE_SUCCESS) goto out; /* Find information needed about the object to initialize */ sk = so->attr; /* Find description of object */ type_props = tee_svc_find_type_props(so->info.objectType); if (!type_props) { res = TEE_ERROR_NOT_SUPPORTED; goto out; } if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) { size_t alloc_size; struct bignum *pub; struct bignum *ss; if (param_count != 1 || params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } alloc_size = params[0].content.ref.length * 8; pub = crypto_bignum_allocate(alloc_size); ss = crypto_bignum_allocate(alloc_size); if (pub && ss) { crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, pub); res = crypto_acipher_dh_shared_secret(ko->attr, pub, ss); if (res == TEE_SUCCESS) { sk->key_size = crypto_bignum_num_bytes(ss); crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1)); so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } else { res = TEE_ERROR_OUT_OF_MEMORY; } crypto_bignum_free(pub); crypto_bignum_free(ss); } else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) { size_t alloc_size; struct ecc_public_key key_public; uint8_t *pt_secret; unsigned long pt_secret_len; if (param_count != 2 || params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X || params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } switch (cs->algo) { case TEE_ALG_ECDH_P192: alloc_size = 192; break; case TEE_ALG_ECDH_P224: alloc_size = 224; break; case TEE_ALG_ECDH_P256: alloc_size = 256; break; case TEE_ALG_ECDH_P384: alloc_size = 384; break; case TEE_ALG_ECDH_P521: alloc_size = 521; break; default: res = TEE_ERROR_NOT_IMPLEMENTED; goto out; } /* Create the public key */ res = crypto_acipher_alloc_ecc_public_key(&key_public, alloc_size); if (res != TEE_SUCCESS) goto out; key_public.curve = ((struct ecc_keypair *)ko->attr)->curve; crypto_bignum_bin2bn(params[0].content.ref.buffer, params[0].content.ref.length, key_public.x); crypto_bignum_bin2bn(params[1].content.ref.buffer, params[1].content.ref.length, key_public.y); pt_secret = (uint8_t *)(sk + 1); pt_secret_len = sk->alloc_size; res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public, pt_secret, &pt_secret_len); if (res == TEE_SUCCESS) { sk->key_size = pt_secret_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } /* free the public key */ crypto_acipher_free_ecc_public_key(&key_public); } #if defined(CFG_CRYPTO_HKDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) { void *salt, *info; size_t salt_len, info_len, okm_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ik = ko->attr; const uint8_t *ikm = (const uint8_t *)(ik + 1); res = get_hkdf_params(params, param_count, &salt, &salt_len, &info, &info_len, &okm_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (okm_len > ik->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len, info, info_len, (uint8_t *)(sk + 1), okm_len); if (res == TEE_SUCCESS) { sk->key_size = okm_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_CONCAT_KDF) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) { void *info; size_t info_len, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *shared_secret = (const uint8_t *)(ss + 1); res = get_concat_kdf_params(params, param_count, &info, &info_len, &derived_key_len); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size, info, info_len, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif #if defined(CFG_CRYPTO_PBKDF2) else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) { void *salt; size_t salt_len, iteration_count, derived_key_len; uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo); struct tee_cryp_obj_secret *ss = ko->attr; const uint8_t *password = (const uint8_t *)(ss + 1); res = get_pbkdf2_params(params, param_count, &salt, &salt_len, &derived_key_len, &iteration_count); if (res != TEE_SUCCESS) goto out; /* Requested size must fit into the output object's buffer */ if (derived_key_len > ss->alloc_size) { res = TEE_ERROR_BAD_PARAMETERS; goto out; } res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt, salt_len, iteration_count, (uint8_t *)(sk + 1), derived_key_len); if (res == TEE_SUCCESS) { sk->key_size = derived_key_len; so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED; set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE); } } #endif else res = TEE_ERROR_NOT_SUPPORTED; out: free(params); return res; }
169,467
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-1]; } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static int decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-1]; } return 0; }
173,983
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int vp8_remove_decoder_instances(struct frame_buffers *fb) { if(!fb->use_frame_threads) { VP8D_COMP *pbi = fb->pbi[0]; if (!pbi) return VPX_CODEC_ERROR; #if CONFIG_MULTITHREAD if (pbi->b_multithreaded_rd) vp8mt_de_alloc_temp_buffers(pbi, pbi->common.mb_rows); vp8_decoder_remove_threads(pbi); #endif /* decoder instance for single thread mode */ remove_decompressor(pbi); } else { /* TODO : remove frame threads and decoder instances for each * thread here */ } return VPX_CODEC_OK; } Commit Message: vp8:fix threading issues 1 - stops de allocating before threads are closed. 2 - limits threads to mb_rows when mb_rows < partitions BUG=webm:851 Bug: 30436808 Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b (cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e) CWE ID:
int vp8_remove_decoder_instances(struct frame_buffers *fb) { if(!fb->use_frame_threads) { VP8D_COMP *pbi = fb->pbi[0]; if (!pbi) return VPX_CODEC_ERROR; #if CONFIG_MULTITHREAD vp8_decoder_remove_threads(pbi); #endif /* decoder instance for single thread mode */ remove_decompressor(pbi); } else { /* TODO : remove frame threads and decoder instances for each * thread here */ } return VPX_CODEC_OK; }
174,065
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::vector<FilePath> GDataCache::GetCachePaths( const FilePath& cache_root_path) { std::vector<FilePath> cache_paths; cache_paths.push_back(cache_root_path.Append(kGDataCacheMetaDir)); cache_paths.push_back(cache_root_path.Append(kGDataCachePinnedDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheOutgoingDir)); cache_paths.push_back(cache_root_path.Append(kGDataCachePersistentDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDownloadsDir)); cache_paths.push_back(cache_root_path.Append(kGDataCacheTmpDocumentsDir)); return cache_paths; } Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories Broke linux_chromeos_valgrind: http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio In theory, we shouldn't have any invalid files left in the cache directories, but things can go wrong and invalid files may be left if the device shuts down unexpectedly, for instance. Besides, it's good to be defensive. BUG=134862 TEST=added unit tests Review URL: https://chromiumcodereview.appspot.com/10693020 [email protected] git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
std::vector<FilePath> GDataCache::GetCachePaths(
170,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_monitor_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_monitor_header { uint8_t pkt_type; uint8_t padding; uint8_t iif[2]; uint8_t service_id[4]; }; const struct juniper_monitor_header *mh; l2info.pictype = DLT_JUNIPER_MONITOR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; mh = (const struct juniper_monitor_header *)p; if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ", EXTRACT_32BITS(&mh->service_id), EXTRACT_16BITS(&mh->iif), mh->pkt_type)); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_monitor_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_monitor_header { uint8_t pkt_type; uint8_t padding; uint8_t iif[2]; uint8_t service_id[4]; }; const struct juniper_monitor_header *mh; l2info.pictype = DLT_JUNIPER_MONITOR; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; mh = (const struct juniper_monitor_header *)p; ND_TCHECK(*mh); if (ndo->ndo_eflag) ND_PRINT((ndo, "service-id %u, iif %u, pkt-type %u: ", EXTRACT_32BITS(&mh->service_id), EXTRACT_16BITS(&mh->iif), mh->pkt_type)); /* no proto field - lets guess by first byte of IP header*/ ip_heuristic_guess (ndo, p, l2info.length); return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; }
167,918
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; } Commit Message: Fix for bug #72790 and bug #72799 CWE ID: CWE-476
int php_wddx_deserialize_ex(char *value, int vallen, zval *return_value) { wddx_stack stack; XML_Parser parser; st_entry *ent; int retval; wddx_stack_init(&stack); parser = XML_ParserCreate("UTF-8"); XML_SetUserData(parser, &stack); XML_SetElementHandler(parser, php_wddx_push_element, php_wddx_pop_element); XML_SetCharacterDataHandler(parser, php_wddx_process_data); XML_Parse(parser, value, vallen, 1); XML_ParserFree(parser); if (stack.top == 1) { wddx_stack_top(&stack, (void**)&ent); if(ent->data == NULL) { retval = FAILURE; } else { *return_value = *(ent->data); zval_copy_ctor(return_value); retval = SUCCESS; } } else { retval = FAILURE; } wddx_stack_destroy(&stack); return retval; }
166,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, rs_ctx ); #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else if( f_rng_blind != NULL ) ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, f_rng_blind, p_rng_blind, rs_ctx ); else { mbedtls_hmac_drbg_context *p_rng_blind_det; #if !defined(MBEDTLS_ECP_RESTARTABLE) /* * To avoid reusing rng_ctx and risking incorrect behavior we seed a * second HMAC-DRBG with the same seed. We also apply a label to avoid * reusing the bits of the ephemeral key for blinding and eliminate the * risk that they leak this way. */ const char* blind_label = "BLINDING CONTEXT"; mbedtls_hmac_drbg_context rng_ctx_blind; mbedtls_hmac_drbg_init( &rng_ctx_blind ); p_rng_blind_det = &rng_ctx_blind; mbedtls_hmac_drbg_seed_buf( p_rng_blind_det, md_info, data, 2 * grp_len ); ret = mbedtls_hmac_drbg_update_ret( p_rng_blind_det, (const unsigned char*) blind_label, strlen( blind_label ) ); if( ret != 0 ) { mbedtls_hmac_drbg_free( &rng_ctx_blind ); goto cleanup; } #else /* * In the case of restartable computations we would either need to store * the second RNG in the restart context too or set it up at every * restart. The first option would penalize the correct application of * the function and the second would defeat the purpose of the * restartable feature. * * Therefore in this case we reuse the original RNG. This comes with the * price that the resulting signature might not be a valid deterministic * ECDSA signature with a very low probability (same magnitude as * successfully guessing the private key). However even then it is still * a valid ECDSA signature. */ p_rng_blind_det = p_rng; #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Since the output of the RNGs is always the same for the same key and * message, this limits the efficiency of blinding and leaks information * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL * won't be a valid value for f_rng_blind anymore. Therefore it should * be checked by the caller and this branch and check can be removed. */ ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, mbedtls_hmac_drbg_random, p_rng_blind_det, rs_ctx ); #if !defined(MBEDTLS_ECP_RESTARTABLE) mbedtls_hmac_drbg_free( &rng_ctx_blind ); #endif } #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); }
169,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int l2cap_parse_conf_req(struct sock *sk, void *data) { struct l2cap_pinfo *pi = l2cap_pi(sk); struct l2cap_conf_rsp *rsp = data; void *ptr = rsp->data; void *req = pi->conf_req; int len = pi->conf_len; int type, hint, olen; unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; u16 mtu = L2CAP_DEFAULT_MTU; u16 result = L2CAP_CONF_SUCCESS; BT_DBG("sk %p", sk); while (len >= L2CAP_CONF_OPT_SIZE) { len -= l2cap_get_conf_opt(&req, &type, &olen, &val); hint = type & L2CAP_CONF_HINT; type &= L2CAP_CONF_MASK; switch (type) { case L2CAP_CONF_MTU: mtu = val; break; case L2CAP_CONF_FLUSH_TO: pi->flush_to = val; break; case L2CAP_CONF_QOS: break; case L2CAP_CONF_RFC: if (olen == sizeof(rfc)) memcpy(&rfc, (void *) val, olen); break; default: if (hint) break; result = L2CAP_CONF_UNKNOWN; *((u8 *) ptr++) = type; break; } } if (result == L2CAP_CONF_SUCCESS) { /* Configure output options and let the other side know * which ones we don't like. */ if (rfc.mode == L2CAP_MODE_BASIC) { if (mtu < pi->omtu) result = L2CAP_CONF_UNACCEPT; else { pi->omtu = mtu; pi->conf_state |= L2CAP_CONF_OUTPUT_DONE; } l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu); } else { result = L2CAP_CONF_UNACCEPT; memset(&rfc, 0, sizeof(rfc)); rfc.mode = L2CAP_MODE_BASIC; l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc); } } rsp->scid = cpu_to_le16(pi->dcid); rsp->result = cpu_to_le16(result); rsp->flags = cpu_to_le16(0x0000); return ptr - data; } Commit Message: Bluetooth: Add configuration support for ERTM and Streaming mode Add support to config_req and config_rsp to configure ERTM and Streaming mode. If the remote device specifies ERTM or Streaming mode, then the same mode is proposed. Otherwise ERTM or Basic mode is used. And in case of a state 2 device, the remote device should propose the same mode. If not, then the channel gets disconnected. Signed-off-by: Gustavo F. Padovan <[email protected]> Signed-off-by: Marcel Holtmann <[email protected]> CWE ID: CWE-119
static int l2cap_parse_conf_req(struct sock *sk, void *data) { struct l2cap_pinfo *pi = l2cap_pi(sk); struct l2cap_conf_rsp *rsp = data; void *ptr = rsp->data; void *req = pi->conf_req; int len = pi->conf_len; int type, hint, olen; unsigned long val; struct l2cap_conf_rfc rfc = { .mode = L2CAP_MODE_BASIC }; u16 mtu = L2CAP_DEFAULT_MTU; u16 result = L2CAP_CONF_SUCCESS; BT_DBG("sk %p", sk); while (len >= L2CAP_CONF_OPT_SIZE) { len -= l2cap_get_conf_opt(&req, &type, &olen, &val); hint = type & L2CAP_CONF_HINT; type &= L2CAP_CONF_MASK; switch (type) { case L2CAP_CONF_MTU: mtu = val; break; case L2CAP_CONF_FLUSH_TO: pi->flush_to = val; break; case L2CAP_CONF_QOS: break; case L2CAP_CONF_RFC: if (olen == sizeof(rfc)) memcpy(&rfc, (void *) val, olen); break; default: if (hint) break; result = L2CAP_CONF_UNKNOWN; *((u8 *) ptr++) = type; break; } } if (pi->num_conf_rsp || pi->num_conf_req) goto done; switch (pi->mode) { case L2CAP_MODE_STREAMING: case L2CAP_MODE_ERTM: pi->conf_state |= L2CAP_CONF_STATE2_DEVICE; if (!l2cap_mode_supported(pi->mode, pi->conn->feat_mask)) return -ECONNREFUSED; break; default: pi->mode = l2cap_select_mode(rfc.mode, pi->conn->feat_mask); break; } done: if (pi->mode != rfc.mode) { result = L2CAP_CONF_UNACCEPT; rfc.mode = pi->mode; if (pi->num_conf_rsp == 1) return -ECONNREFUSED; l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc); } if (result == L2CAP_CONF_SUCCESS) { /* Configure output options and let the other side know * which ones we don't like. */ if (mtu < L2CAP_DEFAULT_MIN_MTU) result = L2CAP_CONF_UNACCEPT; else { pi->omtu = mtu; pi->conf_state |= L2CAP_CONF_MTU_DONE; } l2cap_add_conf_opt(&ptr, L2CAP_CONF_MTU, 2, pi->omtu); switch (rfc.mode) { case L2CAP_MODE_BASIC: pi->fcs = L2CAP_FCS_NONE; pi->conf_state |= L2CAP_CONF_MODE_DONE; break; case L2CAP_MODE_ERTM: pi->remote_tx_win = rfc.txwin_size; pi->remote_max_tx = rfc.max_transmit; pi->max_pdu_size = rfc.max_pdu_size; rfc.retrans_timeout = L2CAP_DEFAULT_RETRANS_TO; rfc.monitor_timeout = L2CAP_DEFAULT_MONITOR_TO; pi->conf_state |= L2CAP_CONF_MODE_DONE; break; case L2CAP_MODE_STREAMING: pi->remote_tx_win = rfc.txwin_size; pi->max_pdu_size = rfc.max_pdu_size; pi->conf_state |= L2CAP_CONF_MODE_DONE; break; default: result = L2CAP_CONF_UNACCEPT; memset(&rfc, 0, sizeof(rfc)); rfc.mode = pi->mode; } l2cap_add_conf_opt(&ptr, L2CAP_CONF_RFC, sizeof(rfc), (unsigned long) &rfc); if (result == L2CAP_CONF_SUCCESS) pi->conf_state |= L2CAP_CONF_OUTPUT_DONE; } rsp->scid = cpu_to_le16(pi->dcid); rsp->result = cpu_to_le16(result); rsp->flags = cpu_to_le16(0x0000); return ptr - data; }
167,625
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SaveCardBubbleControllerImpl::ShowBubbleForLocalSave( const CreditCard& card, const base::Closure& save_card_callback) { is_uploading_ = false; is_reshow_ = false; should_cvc_be_requested_ = false; legal_message_lines_.clear(); AutofillMetrics::LogSaveCardPromptMetric( AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_, is_reshow_, pref_service_->GetInteger( prefs::kAutofillAcceptSaveCreditCardPromptState)); card_ = card; save_card_callback_ = save_card_callback; ShowBubble(); } Commit Message: [autofill] Avoid duplicate instances of the SaveCardBubble. autofill::SaveCardBubbleControllerImpl::ShowBubble() expects (via DCHECK) to only be called when the save card bubble is not already visible. This constraint is violated if the user clicks multiple times on a submit button. If the underlying page goes away, the last SaveCardBubbleView created by the controller will be automatically cleaned up, but any others are left visible on the screen... holding a refence to a possibly-deleted controller. This CL early exits the ShowBubbleFor*** and ReshowBubble logic if the bubble is already visible. BUG=708819 Review-Url: https://codereview.chromium.org/2862933002 Cr-Commit-Position: refs/heads/master@{#469768} CWE ID: CWE-416
void SaveCardBubbleControllerImpl::ShowBubbleForLocalSave( const CreditCard& card, const base::Closure& save_card_callback) { // Don't show the bubble if it's already visible. if (save_card_bubble_view_) return; is_uploading_ = false; is_reshow_ = false; should_cvc_be_requested_ = false; legal_message_lines_.clear(); AutofillMetrics::LogSaveCardPromptMetric( AutofillMetrics::SAVE_CARD_PROMPT_SHOW_REQUESTED, is_uploading_, is_reshow_, pref_service_->GetInteger( prefs::kAutofillAcceptSaveCreditCardPromptState)); card_ = card; save_card_callback_ = save_card_callback; ShowBubble(); }
172,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerDevToolsAgentHost::WorkerRestarted(int worker_process_id, int worker_route_id) { DCHECK_EQ(WORKER_TERMINATED, state_); state_ = WORKER_NOT_READY; worker_process_id_ = worker_process_id; worker_route_id_ = worker_route_id; RenderProcessHost* host = RenderProcessHost::FromID(worker_process_id_); for (DevToolsSession* session : sessions()) session->SetRenderer(host, nullptr); } 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 ServiceWorkerDevToolsAgentHost::WorkerRestarted(int worker_process_id, int worker_route_id) { DCHECK_EQ(WORKER_TERMINATED, state_); state_ = WORKER_NOT_READY; worker_process_id_ = worker_process_id; worker_route_id_ = worker_route_id; for (DevToolsSession* session : sessions()) session->SetRenderer(worker_process_id_, nullptr); }
172,786
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) { #if LUA_VERSION_NUM < 502 size_t len = lua_objlen(L,-1), j; #else size_t len = lua_rawlen(L,-1), j; #endif mp_encode_array(L,buf,len); for (j = 1; j <= len; j++) { lua_pushnumber(L,j); lua_gettable(L,-2); mp_encode_lua_type(L,buf,level+1); } } Commit Message: Security: more cmsgpack fixes by @soloestoy. @soloestoy sent me this additional fixes, after searching for similar problems to the one reported in mp_pack(). I'm committing the changes because it was not possible during to make a public PR to protect Redis users and give Redis providers some time to patch their systems. CWE ID: CWE-119
void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) { #if LUA_VERSION_NUM < 502 size_t len = lua_objlen(L,-1), j; #else size_t len = lua_rawlen(L,-1), j; #endif mp_encode_array(L,buf,len); luaL_checkstack(L, 1, "in function mp_encode_lua_table_as_array"); for (j = 1; j <= len; j++) { lua_pushnumber(L,j); lua_gettable(L,-2); mp_encode_lua_type(L,buf,level+1); } }
169,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: log2vis_utf8 (PyObject * string, int unicode_length, FriBidiParType base_direction, int clean, int reordernsm) { FriBidiChar *logical = NULL; /* input fribidi unicode buffer */ FriBidiChar *visual = NULL; /* output fribidi unicode buffer */ char *visual_utf8 = NULL; /* output fribidi UTF-8 buffer */ FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */ PyObject *result = NULL; /* failure */ /* Allocate fribidi unicode buffers */ logical = PyMem_New (FriBidiChar, unicode_length + 1); if (logical == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } visual = PyMem_New (FriBidiChar, unicode_length + 1); if (visual == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } /* Convert to unicode and order visually */ fribidi_set_reorder_nsm(reordernsm); fribidi_utf8_to_unicode (PyString_AS_STRING (string), PyString_GET_SIZE (string), logical); if (!fribidi_log2vis (logical, unicode_length, &base_direction, visual, NULL, NULL, NULL)) { PyErr_SetString (PyExc_RuntimeError, "fribidi failed to order string"); goto cleanup; } /* Cleanup the string if requested */ if (clean) fribidi_remove_bidi_marks (visual, unicode_length, NULL, NULL, NULL); /* Allocate fribidi UTF-8 buffer */ visual_utf8 = PyMem_New(char, (unicode_length * 4)+1); if (visual_utf8 == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate UTF-8 buffer"); goto cleanup; } /* Encode the reordered string and create result string */ new_len = fribidi_unicode_to_utf8 (visual, unicode_length, visual_utf8); result = PyString_FromStringAndSize (visual_utf8, new_len); if (result == NULL) /* XXX does it raise any error? */ goto cleanup; cleanup: /* Delete unicode buffers */ PyMem_Del (logical); PyMem_Del (visual); PyMem_Del (visual_utf8); return result; } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119
log2vis_utf8 (PyObject * string, int unicode_length,
165,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int replace_map_fd_with_map_ptr(struct verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose("BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose("BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose("invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose("unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose("fd %d is not pointing to valid bpf_map\n", insn->imm); fdput(f); return PTR_ERR(map); } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* remember this map */ env->used_maps[env->used_map_cnt++] = map; /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ bpf_map_inc(map, false); fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } Commit Message: bpf: fix double-fdput in replace_map_fd_with_map_ptr() When bpf(BPF_PROG_LOAD, ...) was invoked with a BPF program whose bytecode references a non-map file descriptor as a map file descriptor, the error handling code called fdput() twice instead of once (in __bpf_map_get() and in replace_map_fd_with_map_ptr()). If the file descriptor table of the current task is shared, this causes f_count to be decremented too much, allowing the struct file to be freed while it is still in use (use-after-free). This can be exploited to gain root privileges by an unprivileged user. This bug was introduced in commit 0246e64d9a5f ("bpf: handle pseudo BPF_LD_IMM64 insn"), but is only exploitable since commit 1be7f75d1668 ("bpf: enable non-root eBPF programs") because previously, CAP_SYS_ADMIN was required to reach the vulnerable code. (posted publicly according to request by maintainer) Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> Acked-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
static int replace_map_fd_with_map_ptr(struct verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose("BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose("BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose("invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose("unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose("fd %d is not pointing to valid bpf_map\n", insn->imm); return PTR_ERR(map); } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* remember this map */ env->used_maps[env->used_map_cnt++] = map; /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ bpf_map_inc(map, false); fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; }
167,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc( size ); if( object ) { g_signal_connect( object, "postclose", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); } Commit Message: zero memory on malloc to prevent write of uninit memory under some error conditions thanks Balint CWE ID: CWE-200
vips_malloc( VipsObject *object, size_t size ) { void *buf; buf = g_malloc0( size ); if( object ) { g_signal_connect( object, "postclose", G_CALLBACK( vips_malloc_cb ), buf ); object->local_memory += size; } return( buf ); }
169,739
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); return MP4buffer; } } return NULL; } Commit Message: fixed many security issues with the too crude mp4 reader CWE ID: CWE-787
uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) { mp4object *mp4 = (mp4object *)handle; if (mp4 == NULL) return NULL; uint32_t *MP4buffer = NULL; if (index < mp4->indexcount && mp4->mediafp) { MP4buffer = (uint32_t *)realloc((void *)lastpayload, mp4->metasizes[index]); if (MP4buffer) { if (mp4->filesize > mp4->metaoffsets[index]+mp4->metasizes[index]) { LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); mp4->filepos = mp4->metaoffsets[index] + mp4->metasizes[index]; return MP4buffer; } } } return NULL; }
169,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: toomany(struct magic_set *ms, const char *name, uint16_t num) { if (file_printf(ms, ", too many %s header sections (%u)", name, num ) == -1) return -1; return 0; } Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander Cherepanov) - Restructure ELF note printing so that we don't print the same message multiple times on repeated notes of the same kind. CWE ID: CWE-399
toomany(struct magic_set *ms, const char *name, uint16_t num) { if (file_printf(ms, ", too many %s (%u)", name, num ) == -1) return -1; return 0; }
166,781
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; ps_dec->process_called = 1; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; ps_dec->u4_stop_threads = 0; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ { if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } } ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base; u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8)); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; if(buflen >= MAX_NAL_UNIT_SIZE) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); H264_DEC_DEBUG_PRINT( "\nNal Size exceeded %d, Processing Stopped..\n", MAX_NAL_UNIT_SIZE); ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA; ps_dec_op->e_pic_type = -1; /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /*signal end of frame decode for curren frame*/ if(ps_dec->u4_pic_buf_got == 0) { if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return IV_FAIL; } else { ps_dec->u1_pic_decode_done = 1; continue; } } { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) && (ps_dec->u4_pic_buf_got == 1)) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); if(ret != 0) { return IV_FAIL; } } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((0 == ps_dec->u4_num_reorder_frames_at_init) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; } Commit Message: Decoder: Moved end of pic processing to end of decode call ih264d_end_of_pic() was called after parsing slice of a new picture. This is now being done at the end of decode of the current picture. decode_gaps_in_frame_num which needs frame_num of new slice is now done after decoding frame_num in new slice. This helps in handling errors in picaff streams with gaps in frames Bug: 33588051 Bug: 33641588 Bug: 34097231 Change-Id: I1a26e611aaa2c19e2043e05a210849bd21b22220 CWE ID: CWE-119
WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) { /* ! */ dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); WORD32 i4_err_status = 0; UWORD8 *pu1_buf = NULL; WORD32 buflen; UWORD32 u4_max_ofst, u4_length_of_start_code = 0; UWORD32 bytes_consumed = 0; UWORD32 cur_slice_is_nonref = 0; UWORD32 u4_next_is_aud; UWORD32 u4_first_start_code_found = 0; WORD32 ret = 0,api_ret_value = IV_SUCCESS; WORD32 header_data_left = 0,frame_data_left = 0; UWORD8 *pu1_bitstrm_buf; ivd_video_decode_ip_t *ps_dec_ip; ivd_video_decode_op_t *ps_dec_op; ithread_set_name((void*)"Parse_thread"); ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; { UWORD32 u4_size; u4_size = ps_dec_op->u4_size; memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); ps_dec_op->u4_size = u4_size; } ps_dec->pv_dec_out = ps_dec_op; ps_dec->process_called = 1; if(ps_dec->init_done != 1) { return IV_FAIL; } /*Data memory barries instruction,so that bitstream write by the application is complete*/ DATA_SYNC(); if(0 == ps_dec->u1_flushfrm) { if(ps_dec_ip->pv_stream_buffer == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; return IV_FAIL; } if(ps_dec_ip->u4_num_Bytes <= 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; return IV_FAIL; } } ps_dec->u1_pic_decode_done = 0; ps_dec_op->u4_num_bytes_consumed = 0; ps_dec->ps_out_buffer = NULL; if(ps_dec_ip->u4_size >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 0; ps_dec->s_disp_op.u4_error_code = 1; ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; ps_dec->u4_stop_threads = 0; if(0 == ps_dec->u4_share_disp_buf && ps_dec->i4_decode_header == 0) { UWORD32 i; if(ps_dec->ps_out_buffer->u4_num_bufs == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; return IV_FAIL; } for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) { if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; return IV_FAIL; } if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) { ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; return IV_FAIL; } } } if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) { ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; return IV_FAIL; } /* ! */ ps_dec->u4_ts = ps_dec_ip->u4_ts; ps_dec_op->u4_error_code = 0; ps_dec_op->e_pic_type = -1; ps_dec_op->u4_output_present = 0; ps_dec_op->u4_frame_decoded_flag = 0; ps_dec->i4_frametype = -1; ps_dec->i4_content_type = -1; ps_dec->u4_slice_start_code_found = 0; /* In case the deocder is not in flush mode(in shared mode), then decoder has to pick up a buffer to write current frame. Check if a frame is available in such cases */ if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 && ps_dec->u1_flushfrm == 0) { UWORD32 i; WORD32 disp_avail = 0, free_id; /* Check if at least one buffer is available with the codec */ /* If not then return to application with error */ for(i = 0; i < ps_dec->u1_pic_bufs; i++) { if(0 == ps_dec->u4_disp_buf_mapping[i] || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) { disp_avail = 1; break; } } if(0 == disp_avail) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } while(1) { pic_buffer_t *ps_pic_buf; ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); if(ps_pic_buf == NULL) { UWORD32 i, display_queued = 0; /* check if any buffer was given for display which is not returned yet */ for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) { if(0 != ps_dec->u4_disp_buf_mapping[i]) { display_queued = 1; break; } } /* If some buffer is queued for display, then codec has to singal an error and wait for that buffer to be returned. If nothing is queued for display then codec has ownership of all display buffers and it can reuse any of the existing buffers and continue decoding */ if(1 == display_queued) { /* If something is queued for display wait for that buffer to be returned */ ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); return (IV_FAIL); } } else { /* If the buffer is with display, then mark it as in use and then look for a buffer again */ if(1 == ps_dec->u4_disp_buf_mapping[free_id]) { ih264_buf_mgr_set_status( (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); } else { /** * Found a free buffer for present call. Release it now. * Will be again obtained later. */ ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, free_id, BUF_MGR_IO); break; } } } } if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; ps_dec->u4_output_present = 1; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; ps_dec_op->u4_new_seq = 0; ps_dec_op->u4_output_present = ps_dec->u4_output_present; ps_dec_op->u4_progressive_frame_flag = ps_dec->s_disp_op.u4_progressive_frame_flag; ps_dec_op->e_output_format = ps_dec->s_disp_op.e_output_format; ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; /*In the case of flush ,since no frame is decoded set pic type as invalid*/ ps_dec_op->u4_is_ref_flag = -1; ps_dec_op->e_pic_type = IV_NA_FRAME; ps_dec_op->u4_frame_decoded_flag = 0; if(0 == ps_dec->s_disp_op.u4_error_code) { return (IV_SUCCESS); } else return (IV_FAIL); } if(ps_dec->u1_res_changed == 1) { /*if resolution has changed and all buffers have been flushed, reset decoder*/ ih264d_init_decoder(ps_dec); } ps_dec->u4_prev_nal_skipped = 0; ps_dec->u2_cur_mb_addr = 0; ps_dec->u2_total_mbs_coded = 0; ps_dec->u2_cur_slice_num = 0; ps_dec->cur_dec_mb_num = 0; ps_dec->cur_recon_mb_num = 0; ps_dec->u4_first_slice_in_pic = 2; ps_dec->u1_first_pb_nal_in_pic = 1; ps_dec->u1_slice_header_done = 0; ps_dec->u1_dangling_field = 0; ps_dec->u4_dec_thread_created = 0; ps_dec->u4_bs_deblk_thread_created = 0; ps_dec->u4_cur_bs_mb_num = 0; ps_dec->u4_start_recon_deblk = 0; DEBUG_THREADS_PRINTF(" Starting process call\n"); ps_dec->u4_pic_buf_got = 0; do { pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + ps_dec_op->u4_num_bytes_consumed; u4_max_ofst = ps_dec_ip->u4_num_Bytes - ps_dec_op->u4_num_bytes_consumed; pu1_bitstrm_buf = ps_dec->ps_mem_tab[MEM_REC_BITSBUF].pv_base; u4_next_is_aud = 0; buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, &u4_length_of_start_code, &u4_next_is_aud); if(buflen == -1) buflen = 0; /* Ignore bytes beyond the allocated size of intermediate buffer */ /* Since 8 bytes are read ahead, ensure 8 bytes are free at the end of the buffer, which will be memset to 0 after emulation prevention */ buflen = MIN(buflen, (WORD32)(ps_dec->ps_mem_tab[MEM_REC_BITSBUF].u4_mem_size - 8)); bytes_consumed = buflen + u4_length_of_start_code; ps_dec_op->u4_num_bytes_consumed += bytes_consumed; if(buflen >= MAX_NAL_UNIT_SIZE) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); H264_DEC_DEBUG_PRINT( "\nNal Size exceeded %d, Processing Stopped..\n", MAX_NAL_UNIT_SIZE); ps_dec->i4_error_code = 1 << IVD_CORRUPTEDDATA; ps_dec_op->e_pic_type = -1; /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /*signal end of frame decode for curren frame*/ if(ps_dec->u4_pic_buf_got == 0) { if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return IV_FAIL; } else { ps_dec->u1_pic_decode_done = 1; continue; } } { UWORD8 u1_firstbyte, u1_nal_ref_idc; if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) { u1_firstbyte = *(pu1_buf + u4_length_of_start_code); u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); if(u1_nal_ref_idc == 0) { /*skip non reference frames*/ cur_slice_is_nonref = 1; continue; } else { if(1 == cur_slice_is_nonref) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->e_pic_type = IV_B_FRAME; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } } } } if(buflen) { memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, buflen); u4_first_start_code_found = 1; } else { /*start code not found*/ if(u4_first_start_code_found == 0) { /*no start codes found in current process call*/ ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; if(ps_dec->u4_pic_buf_got == 0) { ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); ps_dec_op->u4_error_code = ps_dec->i4_error_code; ps_dec_op->u4_frame_decoded_flag = 0; return (IV_FAIL); } else { ps_dec->u1_pic_decode_done = 1; continue; } } else { /* a start code has already been found earlier in the same process call*/ frame_data_left = 0; header_data_left = 0; continue; } } ps_dec->u4_return_to_app = 0; ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, pu1_bitstrm_buf, buflen); if(ret != OK) { UWORD32 error = ih264d_map_error(ret); ps_dec_op->u4_error_code = error | ret; api_ret_value = IV_FAIL; if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { ps_dec->u4_slice_start_code_found = 0; break; } if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; api_ret_value = IV_FAIL; break; } if(ret == ERROR_IN_LAST_SLICE_OF_PIC) { api_ret_value = IV_FAIL; break; } } if(ps_dec->u4_return_to_app) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } header_data_left = ((ps_dec->i4_decode_header == 1) && (ps_dec->i4_header_decoded != 3) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); frame_data_left = (((ps_dec->i4_decode_header == 0) && ((ps_dec->u1_pic_decode_done == 0) || (u4_next_is_aud == 1))) && (ps_dec_op->u4_num_bytes_consumed < ps_dec_ip->u4_num_Bytes)); } while(( header_data_left == 1)||(frame_data_left == 1)); if((ps_dec->u4_slice_start_code_found == 1) && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) { WORD32 num_mb_skipped; WORD32 prev_slice_err; pocstruct_t temp_poc; WORD32 ret1; WORD32 ht_in_mbs; ht_in_mbs = ps_dec->u2_pic_ht >> (4 + ps_dec->ps_cur_slice->u1_field_pic_flag); num_mb_skipped = (ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) - ps_dec->u2_total_mbs_coded; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) prev_slice_err = 1; else prev_slice_err = 2; if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) prev_slice_err = 1; ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, &temp_poc, prev_slice_err); if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T) || (ret1 == ERROR_INV_SPS_PPS_T)) { ret = ret1; } } if((ret == IVD_RES_CHANGED) || (ret == IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED) || (ret == ERROR_UNAVAIL_PICBUF_T) || (ret == ERROR_UNAVAIL_MVBUF_T) || (ret == ERROR_INV_SPS_PPS_T)) { /* signal the decode thread */ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet */ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } /* dont consume bitstream for change in resolution case */ if(ret == IVD_RES_CHANGED) { ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; } return IV_FAIL; } if(ps_dec->u1_separate_parse) { /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_num_cores == 2) { /*do deblocking of all mbs*/ if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) { UWORD32 u4_num_mbs,u4_max_addr; tfr_ctxt_t s_tfr_ctxt; tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; /*BS is done for all mbs while parsing*/ u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, ps_dec->u2_frm_wd_in_mbs, 0); u4_num_mbs = u4_max_addr - ps_dec->u4_cur_deblk_mb_num + 1; DEBUG_PERF_PRINTF("mbs left for deblocking= %d \n",u4_num_mbs); if(u4_num_mbs != 0) ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, ps_tfr_cxt,1); ps_dec->u4_start_recon_deblk = 0; } } /*signal the decode thread*/ ih264d_signal_decode_thread(ps_dec); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } } DATA_SYNC(); if((ps_dec_op->u4_error_code & 0xff) != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) { ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; } if(ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) { ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); } if(ps_dec->u4_prev_nal_skipped) { /*We have encountered a referenced frame,return to app*/ ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); ps_dec_op->u4_frame_decoded_flag = 0; ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } return (IV_FAIL); } if((ps_dec->u4_slice_start_code_found == 1) && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) { /* * For field pictures, set the bottom and top picture decoded u4_flag correctly. */ if(ps_dec->ps_cur_slice->u1_field_pic_flag) { if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) { ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; } else { ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; } } /* if new frame in not found (if we are still getting slices from previous frame) * ih264d_deblock_display is not called. Such frames will not be added to reference /display */ if (((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) && (ps_dec->u4_pic_buf_got == 1)) { /* Calling Function to deblock Picture and Display */ ret = ih264d_deblock_display(ps_dec); } /*set to complete ,as we dont support partial frame decode*/ if(ps_dec->i4_header_decoded == 3) { ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; } /*Update the i4_frametype at the end of picture*/ if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) { ps_dec->i4_frametype = IV_IDR_FRAME; } else if(ps_dec->i4_pic_type == B_SLICE) { ps_dec->i4_frametype = IV_B_FRAME; } else if(ps_dec->i4_pic_type == P_SLICE) { ps_dec->i4_frametype = IV_P_FRAME; } else if(ps_dec->i4_pic_type == I_SLICE) { ps_dec->i4_frametype = IV_I_FRAME; } else { H264_DEC_DEBUG_PRINT("Shouldn't come here\n"); } ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded - ps_dec->ps_cur_slice->u1_field_pic_flag; } /* close deblock thread if it is not closed yet*/ if(ps_dec->u4_num_cores == 3) { ih264d_signal_bs_deblk_thread(ps_dec); } { /* In case the decoder is configured to run in low delay mode, * then get display buffer and then format convert. * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles */ if((0 == ps_dec->u4_num_reorder_frames_at_init) && ps_dec->u1_init_dec_flag) { ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, &(ps_dec->s_disp_op)); if(0 == ps_dec->s_disp_op.u4_error_code) { ps_dec->u4_fmt_conv_cur_row = 0; ps_dec->u4_output_present = 1; } } ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); /* If Format conversion is not complete, complete it here */ if(ps_dec->u4_output_present && (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) { ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht - ps_dec->u4_fmt_conv_cur_row; ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), ps_dec->u4_fmt_conv_cur_row, ps_dec->u4_fmt_conv_num_rows); ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; } ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); } if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) { ps_dec_op->u4_progressive_frame_flag = 1; if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) { if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) ps_dec_op->u4_progressive_frame_flag = 0; } } if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) { ps_dec->u1_top_bottom_decoded = 0; } /*--------------------------------------------------------------------*/ /* Do End of Pic processing. */ /* Should be called only if frame was decoded in previous process call*/ /*--------------------------------------------------------------------*/ if(ps_dec->u4_pic_buf_got == 1) { if(1 == ps_dec->u1_last_pic_not_decoded) { ret = ih264d_end_of_pic_dispbuf_mgr(ps_dec); if(ret != OK) return ret; ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } else { ret = ih264d_end_of_pic(ps_dec); if(ret != OK) return ret; } } /*Data memory barrier instruction,so that yuv write by the library is complete*/ DATA_SYNC(); H264_DEC_DEBUG_PRINT("The num bytes consumed: %d\n", ps_dec_op->u4_num_bytes_consumed); return api_ret_value; }
174,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void uv__process_child_init(const uv_process_options_t* options, int stdio_count, int (*pipes)[2], int error_fd) { int close_fd; int use_fd; int fd; if (options->flags & UV_PROCESS_DETACHED) setsid(); for (fd = 0; fd < stdio_count; fd++) { close_fd = pipes[fd][0]; use_fd = pipes[fd][1]; if (use_fd < 0) { if (fd >= 3) continue; else { /* redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is * set */ use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR); close_fd = use_fd; if (use_fd == -1) { uv__write_int(error_fd, -errno); perror("failed to open stdio"); _exit(127); } } } if (fd == use_fd) uv__cloexec(use_fd, 0); else dup2(use_fd, fd); if (fd <= 2) uv__nonblock(fd, 0); if (close_fd != -1) uv__close(close_fd); } for (fd = 0; fd < stdio_count; fd++) { use_fd = pipes[fd][1]; if (use_fd >= 0 && fd != use_fd) close(use_fd); } if (options->cwd != NULL && chdir(options->cwd)) { uv__write_int(error_fd, -errno); perror("chdir()"); _exit(127); } if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid)) { uv__write_int(error_fd, -errno); perror("setgid()"); _exit(127); } if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid)) { uv__write_int(error_fd, -errno); perror("setuid()"); _exit(127); } if (options->env != NULL) { environ = options->env; } execvp(options->file, options->args); uv__write_int(error_fd, -errno); perror("execvp()"); _exit(127); } Commit Message: unix: call setgoups before calling setuid/setgid Partial fix for #1093 CWE ID: CWE-264
static void uv__process_child_init(const uv_process_options_t* options, int stdio_count, int (*pipes)[2], int error_fd) { int close_fd; int use_fd; int fd; if (options->flags & UV_PROCESS_DETACHED) setsid(); for (fd = 0; fd < stdio_count; fd++) { close_fd = pipes[fd][0]; use_fd = pipes[fd][1]; if (use_fd < 0) { if (fd >= 3) continue; else { /* redirect stdin, stdout and stderr to /dev/null even if UV_IGNORE is * set */ use_fd = open("/dev/null", fd == 0 ? O_RDONLY : O_RDWR); close_fd = use_fd; if (use_fd == -1) { uv__write_int(error_fd, -errno); perror("failed to open stdio"); _exit(127); } } } if (fd == use_fd) uv__cloexec(use_fd, 0); else dup2(use_fd, fd); if (fd <= 2) uv__nonblock(fd, 0); if (close_fd != -1) uv__close(close_fd); } for (fd = 0; fd < stdio_count; fd++) { use_fd = pipes[fd][1]; if (use_fd >= 0 && fd != use_fd) close(use_fd); } if (options->cwd != NULL && chdir(options->cwd)) { uv__write_int(error_fd, -errno); perror("chdir()"); _exit(127); } if (options->flags & (UV_PROCESS_SETUID | UV_PROCESS_SETGID)) { /* When dropping privileges from root, the `setgroups` call will * remove any extraneous groups. If we don't call this, then * even though our uid has dropped, we may still have groups * that enable us to do super-user things. This will fail if we * aren't root, so don't bother checking the return value, this * is just done as an optimistic privilege dropping function. */ SAVE_ERRNO(setgroups(0, NULL)); } if ((options->flags & UV_PROCESS_SETGID) && setgid(options->gid)) { uv__write_int(error_fd, -errno); perror("setgid()"); _exit(127); } if ((options->flags & UV_PROCESS_SETUID) && setuid(options->uid)) { uv__write_int(error_fd, -errno); perror("setuid()"); _exit(127); } if (options->env != NULL) { environ = options->env; } execvp(options->file, options->args); uv__write_int(error_fd, -errno); perror("execvp()"); _exit(127); }
166,728
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; } Commit Message: netfilter: x_tables: make sure e->next_offset covers remaining blob size Otherwise this function may read data beyond the ruleset blob. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
check_compat_entry_size_and_hooks(struct compat_ip6t_entry *e, struct xt_table_info *newinfo, unsigned int *size, const unsigned char *base, const unsigned char *limit, const unsigned int *hook_entries, const unsigned int *underflows, const char *name) { struct xt_entry_match *ematch; struct xt_entry_target *t; struct xt_target *target; unsigned int entry_offset; unsigned int j; int ret, off, h; duprintf("check_compat_entry_size_and_hooks %p\n", e); if ((unsigned long)e % __alignof__(struct compat_ip6t_entry) != 0 || (unsigned char *)e + sizeof(struct compat_ip6t_entry) >= limit || (unsigned char *)e + e->next_offset > limit) { duprintf("Bad offset %p, limit = %p\n", e, limit); return -EINVAL; } if (e->next_offset < sizeof(struct compat_ip6t_entry) + sizeof(struct compat_xt_entry_target)) { duprintf("checking: element %p size %u\n", e, e->next_offset); return -EINVAL; } /* For purposes of check_entry casting the compat entry is fine */ ret = check_entry((struct ip6t_entry *)e); if (ret) return ret; off = sizeof(struct ip6t_entry) - sizeof(struct compat_ip6t_entry); entry_offset = (void *)e - (void *)base; j = 0; xt_ematch_foreach(ematch, e) { ret = compat_find_calc_match(ematch, name, &e->ipv6, &off); if (ret != 0) goto release_matches; ++j; } t = compat_ip6t_get_target(e); target = xt_request_find_target(NFPROTO_IPV6, t->u.user.name, t->u.user.revision); if (IS_ERR(target)) { duprintf("check_compat_entry_size_and_hooks: `%s' not found\n", t->u.user.name); ret = PTR_ERR(target); goto release_matches; } t->u.kernel.target = target; off += xt_compat_target_offset(target); *size += off; ret = xt_compat_add_offset(AF_INET6, entry_offset, off); if (ret) goto out; /* Check hooks & underflows */ for (h = 0; h < NF_INET_NUMHOOKS; h++) { if ((unsigned char *)e - base == hook_entries[h]) newinfo->hook_entry[h] = hook_entries[h]; if ((unsigned char *)e - base == underflows[h]) newinfo->underflow[h] = underflows[h]; } /* Clear counters and comefrom */ memset(&e->counters, 0, sizeof(e->counters)); e->comefrom = 0; return 0; out: module_put(t->u.kernel.target->me); release_matches: xt_ematch_foreach(ematch, e) { if (j-- == 0) break; module_put(ematch->u.kernel.match->me); } return ret; }
167,213
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameHostImpl::OnDidAddMessageToConsole( int32_t level, const base::string16& message, int32_t line_no, const base::string16& source_id) { if (level < logging::LOG_VERBOSE || level > logging::LOG_FATAL) { bad_message::ReceivedBadMessage( GetProcess(), bad_message::RFH_DID_ADD_CONSOLE_MESSAGE_BAD_SEVERITY); return; } if (delegate_->DidAddMessageToConsole(level, message, line_no, source_id)) return; const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(level, message, line_no, is_builtin_component, is_off_the_record, source_id); } 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
void RenderFrameHostImpl::OnDidAddMessageToConsole( void RenderFrameHostImpl::DidAddMessageToConsole( blink::mojom::ConsoleMessageLevel log_level, const base::string16& message, int32_t line_no, const base::string16& source_id) { // TODO(https://crbug.com/786836): Update downstream code to use // ConsoleMessageLevel everywhere to avoid this conversion. logging::LogSeverity log_severity = logging::LOG_VERBOSE; switch (log_level) { case blink::mojom::ConsoleMessageLevel::kVerbose: log_severity = logging::LOG_VERBOSE; break; case blink::mojom::ConsoleMessageLevel::kInfo: log_severity = logging::LOG_INFO; break; case blink::mojom::ConsoleMessageLevel::kWarning: log_severity = logging::LOG_WARNING; break; case blink::mojom::ConsoleMessageLevel::kError: log_severity = logging::LOG_ERROR; break; } if (delegate_->DidAddMessageToConsole(log_severity, message, line_no, source_id)) { return; } // Pass through log severity only on builtin components pages to limit console const bool is_builtin_component = HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) || GetContentClient()->browser()->IsBuiltinComponent( GetProcess()->GetBrowserContext(), GetLastCommittedOrigin()); const bool is_off_the_record = GetSiteInstance()->GetBrowserContext()->IsOffTheRecord(); LogConsoleMessage(log_severity, message, line_no, is_builtin_component, is_off_the_record, source_id); }
172,485
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static struct nfs4_state *nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data) { struct inode *inode; struct nfs4_state *state = NULL; struct nfs_delegation *delegation; int ret; if (!data->rpc_done) { state = nfs4_try_open_cached(data); goto out; } ret = -EAGAIN; if (!(data->f_attr.valid & NFS_ATTR_FATTR)) goto err; inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh, &data->f_attr); ret = PTR_ERR(inode); if (IS_ERR(inode)) goto err; ret = -ENOMEM; state = nfs4_get_open_state(inode, data->owner); if (state == NULL) goto err_put_inode; if (data->o_res.delegation_type != 0) { int delegation_flags = 0; rcu_read_lock(); delegation = rcu_dereference(NFS_I(inode)->delegation); if (delegation) delegation_flags = delegation->flags; rcu_read_unlock(); if ((delegation_flags & 1UL<<NFS_DELEGATION_NEED_RECLAIM) == 0) nfs_inode_set_delegation(state->inode, data->owner->so_cred, &data->o_res); else nfs_inode_reclaim_delegation(state->inode, data->owner->so_cred, &data->o_res); } update_open_stateid(state, &data->o_res.stateid, NULL, data->o_arg.open_flags); iput(inode); out: return state; err_put_inode: iput(inode); err: return ERR_PTR(ret); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <[email protected]> CWE ID:
static struct nfs4_state *nfs4_opendata_to_nfs4_state(struct nfs4_opendata *data) { struct inode *inode; struct nfs4_state *state = NULL; struct nfs_delegation *delegation; int ret; if (!data->rpc_done) { state = nfs4_try_open_cached(data); goto out; } ret = -EAGAIN; if (!(data->f_attr.valid & NFS_ATTR_FATTR)) goto err; inode = nfs_fhget(data->dir->d_sb, &data->o_res.fh, &data->f_attr); ret = PTR_ERR(inode); if (IS_ERR(inode)) goto err; ret = -ENOMEM; state = nfs4_get_open_state(inode, data->owner); if (state == NULL) goto err_put_inode; if (data->o_res.delegation_type != 0) { int delegation_flags = 0; rcu_read_lock(); delegation = rcu_dereference(NFS_I(inode)->delegation); if (delegation) delegation_flags = delegation->flags; rcu_read_unlock(); if ((delegation_flags & 1UL<<NFS_DELEGATION_NEED_RECLAIM) == 0) nfs_inode_set_delegation(state->inode, data->owner->so_cred, &data->o_res); else nfs_inode_reclaim_delegation(state->inode, data->owner->so_cred, &data->o_res); } update_open_stateid(state, &data->o_res.stateid, NULL, data->o_arg.fmode); iput(inode); out: return state; err_put_inode: iput(inode); err: return ERR_PTR(ret); }
165,701
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: atm_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t llchdr; u_int hdrlen = 0; if (caplen < 1 || length < 1) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* Cisco Style NLPID ? */ if (*p == LLC_UI) { if (ndo->ndo_eflag) ND_PRINT((ndo, "CNLPID ")); isoclns_print(ndo, p + 1, length - 1, caplen - 1); return hdrlen; } /* * Must have at least a DSAP, an SSAP, and the first byte of the * control field. */ if (caplen < 3 || length < 3) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* * Extract the presumed LLC header into a variable, for quick * testing. * Then check for a header that's neither a header for a SNAP * packet nor an RFC 2684 routed NLPID-formatted PDU nor * an 802.2-but-no-SNAP IP packet. */ llchdr = EXTRACT_24BITS(p); if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) && llchdr != LLC_UI_HDR(LLCSAP_ISONS) && llchdr != LLC_UI_HDR(LLCSAP_IP)) { /* * XXX - assume 802.6 MAC header from Fore driver. * * Unfortunately, the above list doesn't check for * all known SAPs, doesn't check for headers where * the source and destination SAP aren't the same, * and doesn't check for non-UI frames. It also * runs the risk of an 802.6 MAC header that happens * to begin with one of those values being * incorrectly treated as an 802.2 header. * * So is that Fore driver still around? And, if so, * is it still putting 802.6 MAC headers on ATM * packets? If so, could it be changed to use a * new DLT_IEEE802_6 value if we added it? */ if (caplen < 20 || length < 20) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%08x%08x %08x%08x ", EXTRACT_32BITS(p), EXTRACT_32BITS(p+4), EXTRACT_32BITS(p+8), EXTRACT_32BITS(p+12))); p += 20; length -= 20; caplen -= 20; hdrlen += 20; } hdrlen += atm_llc_print(ndo, p, length, caplen); return (hdrlen); } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
atm_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, const u_char *p) { u_int caplen = h->caplen; u_int length = h->len; uint32_t llchdr; u_int hdrlen = 0; if (caplen < 1 || length < 1) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* Cisco Style NLPID ? */ if (*p == LLC_UI) { if (ndo->ndo_eflag) ND_PRINT((ndo, "CNLPID ")); isoclns_print(ndo, p + 1, length - 1); return hdrlen; } /* * Must have at least a DSAP, an SSAP, and the first byte of the * control field. */ if (caplen < 3 || length < 3) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } /* * Extract the presumed LLC header into a variable, for quick * testing. * Then check for a header that's neither a header for a SNAP * packet nor an RFC 2684 routed NLPID-formatted PDU nor * an 802.2-but-no-SNAP IP packet. */ llchdr = EXTRACT_24BITS(p); if (llchdr != LLC_UI_HDR(LLCSAP_SNAP) && llchdr != LLC_UI_HDR(LLCSAP_ISONS) && llchdr != LLC_UI_HDR(LLCSAP_IP)) { /* * XXX - assume 802.6 MAC header from Fore driver. * * Unfortunately, the above list doesn't check for * all known SAPs, doesn't check for headers where * the source and destination SAP aren't the same, * and doesn't check for non-UI frames. It also * runs the risk of an 802.6 MAC header that happens * to begin with one of those values being * incorrectly treated as an 802.2 header. * * So is that Fore driver still around? And, if so, * is it still putting 802.6 MAC headers on ATM * packets? If so, could it be changed to use a * new DLT_IEEE802_6 value if we added it? */ if (caplen < 20 || length < 20) { ND_PRINT((ndo, "%s", tstr)); return (caplen); } if (ndo->ndo_eflag) ND_PRINT((ndo, "%08x%08x %08x%08x ", EXTRACT_32BITS(p), EXTRACT_32BITS(p+4), EXTRACT_32BITS(p+8), EXTRACT_32BITS(p+12))); p += 20; length -= 20; caplen -= 20; hdrlen += 20; } hdrlen += atm_llc_print(ndo, p, length, caplen); return (hdrlen); }
167,942
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ContentEncoding::ParseEncryptionEntry(long long start, long long size, IMkvReader* pReader, ContentEncryption* encryption) { assert(pReader); assert(encryption); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E1) { encryption->algo = UnserializeUInt(pReader, pos, size); if (encryption->algo != 5) return E_FILE_FORMAT_INVALID; } else if (id == 0x7E2) { delete[] encryption -> key_id; encryption->key_id = NULL; encryption->key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->key_id = buf; encryption->key_id_len = buflen; } else if (id == 0x7E3) { delete[] encryption -> signature; encryption->signature = NULL; encryption->signature_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->signature = buf; encryption->signature_len = buflen; } else if (id == 0x7E4) { delete[] encryption -> sig_key_id; encryption->sig_key_id = NULL; encryption->sig_key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); typedef unsigned char* buf_t; const buf_t buf = new (std::nothrow) unsigned char[buflen]; if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->sig_key_id = buf; encryption->sig_key_id_len = buflen; } else if (id == 0x7E5) { encryption->sig_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E6) { encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E7) { const long status = ParseContentEncAESSettingsEntry( pos, size, pReader, &encryption->aes_settings); if (status) return status; } pos += size; // consume payload assert(pos <= stop); } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long ContentEncoding::ParseEncryptionEntry(long long start, long long size, IMkvReader* pReader, ContentEncryption* encryption) { assert(pReader); assert(encryption); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E1) { encryption->algo = UnserializeUInt(pReader, pos, size); if (encryption->algo != 5) return E_FILE_FORMAT_INVALID; } else if (id == 0x7E2) { delete[] encryption->key_id; encryption->key_id = NULL; encryption->key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen); if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->key_id = buf; encryption->key_id_len = buflen; } else if (id == 0x7E3) { delete[] encryption->signature; encryption->signature = NULL; encryption->signature_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen); if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->signature = buf; encryption->signature_len = buflen; } else if (id == 0x7E4) { delete[] encryption->sig_key_id; encryption->sig_key_id = NULL; encryption->sig_key_id_len = 0; if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen); if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } encryption->sig_key_id = buf; encryption->sig_key_id_len = buflen; } else if (id == 0x7E5) { encryption->sig_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E6) { encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size); } else if (id == 0x7E7) { const long status = ParseContentEncAESSettingsEntry( pos, size, pReader, &encryption->aes_settings); if (status) return status; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } return 0; }
173,854
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { assert(pReader); long long total, available; long status = pReader->Length(&total, &available); if (status < 0) // error return status; pos = 0; long long end = (available >= 1024) ? 1024 : available; for (;;) { unsigned char b = 0; while (pos < end) { status = pReader->Read(pos, 1, &b); if (status < 0) // error return status; if (b == 0x1A) break; ++pos; } if (b != 0x1A) { if (pos >= 1024) return E_FILE_FORMAT_INVALID; // don't bother looking anymore if ((total >= 0) && ((total - available) < 5)) return E_FILE_FORMAT_INVALID; return available + 5; // 5 = 4-byte ID + 1st byte of size } if ((total >= 0) && ((total - pos) < 5)) return E_FILE_FORMAT_INVALID; if ((available - pos) < 5) return pos + 5; // try again later long len; const long long result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; if (result == 0x0A45DFA3) { // EBML Header ID pos += len; // consume ID break; } ++pos; // throw away just the 0x1A byte, and try again } long len; long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return result; if (result > 0) // need more data return result; assert(len > 0); assert(len <= 8); if ((total >= 0) && ((total - pos) < len)) return E_FILE_FORMAT_INVALID; if ((available - pos) < len) return pos + len; // try again later result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; pos += len; // consume size field if ((total >= 0) && ((total - pos) < result)) return E_FILE_FORMAT_INVALID; if ((available - pos) < result) return pos + result; end = pos + result; Init(); while (pos < end) { long long id, size; status = ParseElementHeader(pReader, pos, end, id, size); if (status < 0) // error return status; if (size == 0) // weird return E_FILE_FORMAT_INVALID; if (id == 0x0286) { // version m_version = UnserializeUInt(pReader, pos, size); if (m_version <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F7) { // read version m_readVersion = UnserializeUInt(pReader, pos, size); if (m_readVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F2) { // max id length m_maxIdLength = UnserializeUInt(pReader, pos, size); if (m_maxIdLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F3) { // max size length m_maxSizeLength = UnserializeUInt(pReader, pos, size); if (m_maxSizeLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0282) { // doctype if (m_docType) return E_FILE_FORMAT_INVALID; status = UnserializeString(pReader, pos, size, m_docType); if (status) // error return status; } else if (id == 0x0287) { // doctype version m_docTypeVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0285) { // doctype read version m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeReadVersion <= 0) return E_FILE_FORMAT_INVALID; } pos += size; } assert(pos == end); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { if (!pReader) return E_FILE_FORMAT_INVALID; long long total, available; long status = pReader->Length(&total, &available); if (status < 0) // error return status; pos = 0; long long end = (available >= 1024) ? 1024 : available; for (;;) { unsigned char b = 0; while (pos < end) { status = pReader->Read(pos, 1, &b); if (status < 0) // error return status; if (b == 0x1A) break; ++pos; } if (b != 0x1A) { if (pos >= 1024) return E_FILE_FORMAT_INVALID; // don't bother looking anymore if ((total >= 0) && ((total - available) < 5)) return E_FILE_FORMAT_INVALID; return available + 5; // 5 = 4-byte ID + 1st byte of size } if ((total >= 0) && ((total - pos) < 5)) return E_FILE_FORMAT_INVALID; if ((available - pos) < 5) return pos + 5; // try again later long len; const long long result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; if (result == 0x0A45DFA3) { // EBML Header ID pos += len; // consume ID break; } ++pos; // throw away just the 0x1A byte, and try again } long len; long long result = GetUIntLength(pReader, pos, len); if (result < 0) // error return result; if (result > 0) // need more data return result; if (len < 1 || len > 8) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((total - pos) < len)) return E_FILE_FORMAT_INVALID; if ((available - pos) < len) return pos + len; // try again later result = ReadUInt(pReader, pos, len); if (result < 0) // error return result; pos += len; // consume size field if ((total >= 0) && ((total - pos) < result)) return E_FILE_FORMAT_INVALID; if ((available - pos) < result) return pos + result; end = pos + result; Init(); while (pos < end) { long long id, size; status = ParseElementHeader(pReader, pos, end, id, size); if (status < 0) // error return status; if (size == 0) // weird return E_FILE_FORMAT_INVALID; if (id == 0x0286) { // version m_version = UnserializeUInt(pReader, pos, size); if (m_version <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F7) { // read version m_readVersion = UnserializeUInt(pReader, pos, size); if (m_readVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F2) { // max id length m_maxIdLength = UnserializeUInt(pReader, pos, size); if (m_maxIdLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x02F3) { // max size length m_maxSizeLength = UnserializeUInt(pReader, pos, size); if (m_maxSizeLength <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0282) { // doctype if (m_docType) return E_FILE_FORMAT_INVALID; status = UnserializeString(pReader, pos, size, m_docType); if (status) // error return status; } else if (id == 0x0287) { // doctype version m_docTypeVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeVersion <= 0) return E_FILE_FORMAT_INVALID; } else if (id == 0x0285) { // doctype read version m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); if (m_docTypeReadVersion <= 0) return E_FILE_FORMAT_INVALID; } pos += size; } if (pos != end) return E_FILE_FORMAT_INVALID; return 0; }
173,834
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; access_token_.clear(); expires_in_seconds_ = 0; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; request_.reset(new UrlFetcher(GURL(provider_info_.access_token_url), UrlFetcher::POST)); request_->SetRequestContext(request_context_getter_); request_->SetUploadData("application/x-www-form-urlencoded", post_body); request_->Start( base::Bind(&GaiaOAuthClient::Core::OnAuthTokenFetchComplete, this)); } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::RefreshToken( const OAuthClientInfo& oauth_client_info, const std::string& refresh_token, GaiaOAuthClient::Delegate* delegate) { DCHECK(!request_.get()) << "Tried to fetch two things at once!"; delegate_ = delegate; access_token_.clear(); expires_in_seconds_ = 0; std::string post_body = "refresh_token=" + net::EscapeUrlEncodedData(refresh_token, true) + "&client_id=" + net::EscapeUrlEncodedData(oauth_client_info.client_id, true) + "&client_secret=" + net::EscapeUrlEncodedData(oauth_client_info.client_secret, true) + "&grant_type=refresh_token"; request_.reset(net::URLFetcher::Create( GURL(provider_info_.access_token_url), net::URLFetcher::POST, this)); request_->SetRequestContext(request_context_getter_); request_->SetUploadData("application/x-www-form-urlencoded", post_body); url_fetcher_type_ = URL_FETCHER_REFRESH_TOKEN; request_->Start(); } void GaiaOAuthClient::Core::OnURLFetchComplete( const net::URLFetcher* source) { std::string response_string; source->GetResponseAsString(&response_string); switch (url_fetcher_type_) { case URL_FETCHER_REFRESH_TOKEN: OnAuthTokenFetchComplete(source->GetStatus(), source->GetResponseCode(), response_string); break; case URL_FETCHER_GET_USER_INFO: OnUserInfoFetchComplete(source->GetStatus(), source->GetResponseCode(), response_string); break; default: LOG(ERROR) << "Unrecognised URLFetcher type: " << url_fetcher_type_; } }
170,809
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_@_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_@_mod(PNG_CONST image_transform *this,
173,601
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void MockRenderThread::RemoveRoute(int32 routing_id) { EXPECT_EQ(routing_id_, routing_id); widget_ = NULL; } 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
void MockRenderThread::RemoveRoute(int32 routing_id) { // We may hear this for views created from OnMsgCreateWindow as well, // in which case we don't want to track the new widget. if (routing_id_ == routing_id) widget_ = NULL; }
171,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "BoundingBox:" #define BeginDocument "BeginDocument:" #define BeginXMPPacket "<?xpacket begin=" #define EndXMPPacket "<?xpacket end=" #define ICCProfile "BeginICCProfile:" #define CMYKCustomColor "CMYKCustomColor:" #define CMYKProcessColor "CMYKProcessColor:" #define DocumentMedia "DocumentMedia:" #define DocumentCustomColors "DocumentCustomColors:" #define DocumentProcessColors "DocumentProcessColors:" #define EndDocument "EndDocument:" #define HiResBoundingBox "HiResBoundingBox:" #define ImageData "ImageData:" #define PageBoundingBox "PageBoundingBox:" #define LanguageLevel "LanguageLevel:" #define PageMedia "PageMedia:" #define Pages "Pages:" #define PhotoshopProfile "BeginPhotoshop:" #define PostscriptLevel "!PS-" #define RenderPostscriptText " Rendering Postscript... " #define SpotColor "+ " char command[MagickPathExtent], *density, filename[MagickPathExtent], geometry[MagickPathExtent], input_filename[MagickPathExtent], message[MagickPathExtent], *options, postscript_filename[MagickPathExtent]; const char *option; const DelegateInfo *delegate_info; GeometryInfo geometry_info; Image *image, *next, *postscript_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, fitPage, skip, status; MagickStatusType flags; PointInfo delta, resolution; RectangleInfo page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; short int hex_digits[256]; size_t length; ssize_t count, priority; StringInfo *profile; unsigned long columns, extent, language_level, pages, rows, scene, spotcolor; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) memset(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution=image->resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) memset(&bounds,0,sizeof(bounds)); (void) memset(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) memset(&hires_bounds,0,sizeof(hires_bounds)); columns=0; rows=0; priority=0; rows=0; extent=0; spotcolor=0; language_level=1; pages=(~0UL); skip=MagickFalse; p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,"ps:Level",command+4,exception); if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel " %lu",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages " %lu",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData " %lu %lu",&columns,&rows); /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MagickPathExtent], *value; register char *q; /* Note spot names. */ (void) FormatLocaleString(property,MagickPathExtent, "ps:SpotColor-%.20g",(double) (spotcolor++)); for (q=command; *q != '\0'; q++) if (isspace((int) (unsigned char) *q) != 0) break; value=ConstantString(q); (void) SubstituteString(&value,"(",""); (void) SubstituteString(&value,")",""); (void) StripString(value); if (*value != '\0') (void) SetImageProperty(image,property,value,exception); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"ps:HiResBoundingBox",geometry,exception); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"eps:fit-page"); if (option != (char *) NULL) { char *page_geometry; page_geometry=GetPageGeometry(option); flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width, &page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->resolution.y/ delta.y) -0.5); page_geometry=DestroyString(page_geometry); fitPage=MagickTrue; } if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {" "dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n" "<</UseCIEColor true>>setpagedevice\n",MagickPathExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MagickPathExtent]; (void) FormatLocaleString(translate_geometry,MagickPathExtent, "%g %g translate\n",-bounds.x1,-bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MagickPathExtent,"%gx%g",resolution.x, resolution.y); (void) FormatLocaleString(options,MagickPathExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MagickPathExtent]; (void) FormatLocaleString(pages,MagickPathExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g ",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MagickPathExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,"eps:use-cropbox"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,"-dEPSCrop ",MagickPathExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dEPSFitPage ", MagickPathExtent); } (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MagickPathExtent); (void) FormatLocaleString(command,MagickPathExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename,exception); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command," -c showpage",MagickPathExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(), DelegateError,"PostscriptDelegateFailed","`%s'",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } (void) SeekBlob(image,0,SEEK_SET); for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MagickPathExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *q; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent); if (count != 1) continue; length=extent; if ((MagickSizeType) length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { q=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *q++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=(ssize_t) GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,(size_t) (i+1)); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,(size_t) i); (void) SetImageProfile(image,"xmp",profile,exception); profile=DestroyStringInfo(profile); continue; } } (void) CloseBlob(image); if (image_info->number_scenes != 0) { Image *clone_image; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename, MagickPathExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MagickPathExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1601 CWE ID: CWE-399
static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "BoundingBox:" #define BeginDocument "BeginDocument:" #define BeginXMPPacket "<?xpacket begin=" #define EndXMPPacket "<?xpacket end=" #define ICCProfile "BeginICCProfile:" #define CMYKCustomColor "CMYKCustomColor:" #define CMYKProcessColor "CMYKProcessColor:" #define DocumentMedia "DocumentMedia:" #define DocumentCustomColors "DocumentCustomColors:" #define DocumentProcessColors "DocumentProcessColors:" #define EndDocument "EndDocument:" #define HiResBoundingBox "HiResBoundingBox:" #define ImageData "ImageData:" #define PageBoundingBox "PageBoundingBox:" #define LanguageLevel "LanguageLevel:" #define PageMedia "PageMedia:" #define Pages "Pages:" #define PhotoshopProfile "BeginPhotoshop:" #define PostscriptLevel "!PS-" #define RenderPostscriptText " Rendering Postscript... " #define SpotColor "+ " char command[MagickPathExtent], *density, filename[MagickPathExtent], geometry[MagickPathExtent], input_filename[MagickPathExtent], message[MagickPathExtent], *options, postscript_filename[MagickPathExtent]; const char *option; const DelegateInfo *delegate_info; GeometryInfo geometry_info; Image *image, *next, *postscript_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, fitPage, skip, status; MagickStatusType flags; PointInfo delta, resolution; RectangleInfo page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; short int hex_digits[256]; size_t length; ssize_t count, priority; StringInfo *profile; unsigned long columns, extent, language_level, pages, rows, scene, spotcolor; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) memset(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution=image->resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) memset(&bounds,0,sizeof(bounds)); (void) memset(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) memset(&hires_bounds,0,sizeof(hires_bounds)); columns=0; rows=0; priority=0; rows=0; extent=0; spotcolor=0; language_level=1; pages=(~0UL); skip=MagickFalse; p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,"ps:Level",command+4,exception); if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel " %lu",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages " %lu",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData " %lu %lu",&columns,&rows); /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MagickPathExtent], *value; register char *q; /* Note spot names. */ (void) FormatLocaleString(property,MagickPathExtent, "ps:SpotColor-%.20g",(double) (spotcolor++)); for (q=command; *q != '\0'; q++) if (isspace((int) (unsigned char) *q) != 0) break; value=ConstantString(q); (void) SubstituteString(&value,"(",""); (void) SubstituteString(&value,")",""); (void) StripString(value); if (*value != '\0') (void) SetImageProperty(image,property,value,exception); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"ps:HiResBoundingBox",geometry,exception); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"eps:fit-page"); if (option != (char *) NULL) { char *page_geometry; page_geometry=GetPageGeometry(option); flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width, &page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); page_geometry=DestroyString(page_geometry); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->resolution.y/ delta.y) -0.5); page_geometry=DestroyString(page_geometry); fitPage=MagickTrue; } if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {" "dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n" "<</UseCIEColor true>>setpagedevice\n",MagickPathExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MagickPathExtent]; (void) FormatLocaleString(translate_geometry,MagickPathExtent, "%g %g translate\n",-bounds.x1,-bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MagickPathExtent,"%gx%g",resolution.x, resolution.y); (void) FormatLocaleString(options,MagickPathExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MagickPathExtent]; (void) FormatLocaleString(pages,MagickPathExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g ",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MagickPathExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,"eps:use-cropbox"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,"-dEPSCrop ",MagickPathExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dEPSFitPage ", MagickPathExtent); } (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MagickPathExtent); (void) FormatLocaleString(command,MagickPathExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename,exception); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command," -c showpage",MagickPathExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(), DelegateError,"PostscriptDelegateFailed","`%s'",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } (void) SeekBlob(image,0,SEEK_SET); for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MagickPathExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *q; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent); if (count != 1) continue; length=extent; if ((MagickSizeType) length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { q=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *q++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=(ssize_t) GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,(size_t) (i+1)); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,(size_t) i); (void) SetImageProfile(image,"xmp",profile,exception); profile=DestroyStringInfo(profile); continue; } } (void) CloseBlob(image); if (image_info->number_scenes != 0) { Image *clone_image; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename, MagickPathExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MagickPathExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); }
170,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_parse_color(xps_document *doc, char *base_uri, char *string, fz_colorspace **csp, float *samples) { char *p; int i, n; char buf[1024]; char *profile; *csp = fz_device_rgb(doc->ctx); samples[0] = 1; samples[1] = 0; samples[3] = 0; if (string[0] == '#') { if (strlen(string) == 9) { samples[0] = unhex(string[1]) * 16 + unhex(string[2]); samples[1] = unhex(string[3]) * 16 + unhex(string[4]); samples[2] = unhex(string[5]) * 16 + unhex(string[6]); samples[3] = unhex(string[7]) * 16 + unhex(string[8]); } else { samples[0] = 255; samples[1] = unhex(string[1]) * 16 + unhex(string[2]); samples[2] = unhex(string[3]) * 16 + unhex(string[4]); samples[3] = unhex(string[5]) * 16 + unhex(string[6]); } samples[0] /= 255; samples[1] /= 255; samples[2] /= 255; samples[3] /= 255; } else if (string[0] == 's' && string[1] == 'c' && string[2] == '#') { if (count_commas(string) == 2) sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3); if (count_commas(string) == 3) sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3); } else if (strstr(string, "ContextColor ") == string) { /* Crack the string for profile name and sample values */ fz_strlcpy(buf, string, sizeof buf); profile = strchr(buf, ' '); profile = strchr(buf, ' '); if (!profile) { fz_warn(doc->ctx, "cannot find icc profile uri in '%s'", string); return; } p = strchr(profile, ' '); p = strchr(profile, ' '); if (!p) { fz_warn(doc->ctx, "cannot find component values in '%s'", profile); return; } *p++ = 0; n = count_commas(p) + 1; i = 0; while (i < n) { p ++; } while (i < n) { samples[i++] = 0; } /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; default: *csp = fz_device_gray(doc->ctx); break; } } } for (i = 0; i < colorspace->n; i++) doc->color[i] = samples[i + 1]; doc->alpha = samples[0] * doc->opacity[doc->opacity_top]; } Commit Message: CWE ID: CWE-119
xps_parse_color(xps_document *doc, char *base_uri, char *string, fz_colorspace **csp, float *samples) { fz_context *ctx = doc->ctx; char *p; int i, n; char buf[1024]; char *profile; *csp = fz_device_rgb(ctx); samples[0] = 1; samples[1] = 0; samples[3] = 0; if (string[0] == '#') { if (strlen(string) == 9) { samples[0] = unhex(string[1]) * 16 + unhex(string[2]); samples[1] = unhex(string[3]) * 16 + unhex(string[4]); samples[2] = unhex(string[5]) * 16 + unhex(string[6]); samples[3] = unhex(string[7]) * 16 + unhex(string[8]); } else { samples[0] = 255; samples[1] = unhex(string[1]) * 16 + unhex(string[2]); samples[2] = unhex(string[3]) * 16 + unhex(string[4]); samples[3] = unhex(string[5]) * 16 + unhex(string[6]); } samples[0] /= 255; samples[1] /= 255; samples[2] /= 255; samples[3] /= 255; } else if (string[0] == 's' && string[1] == 'c' && string[2] == '#') { if (count_commas(string) == 2) sscanf(string, "sc#%g,%g,%g", samples + 1, samples + 2, samples + 3); if (count_commas(string) == 3) sscanf(string, "sc#%g,%g,%g,%g", samples, samples + 1, samples + 2, samples + 3); } else if (strstr(string, "ContextColor ") == string) { /* Crack the string for profile name and sample values */ fz_strlcpy(buf, string, sizeof buf); profile = strchr(buf, ' '); profile = strchr(buf, ' '); if (!profile) { fz_warn(ctx, "cannot find icc profile uri in '%s'", string); return; } p = strchr(profile, ' '); p = strchr(profile, ' '); if (!p) { fz_warn(ctx, "cannot find component values in '%s'", profile); return; } *p++ = 0; n = count_commas(p) + 1; if (n > FZ_MAX_COLORS) { fz_warn(ctx, "ignoring %d color components (max %d allowed)", n - FZ_MAX_COLORS, FZ_MAX_COLORS); n = FZ_MAX_COLORS; } i = 0; while (i < n) { p ++; } while (i < n) { samples[i++] = 0; } /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(doc->ctx); break; case 4: *csp = fz_device_rgb(doc->ctx); break; case 5: *csp = fz_device_cmyk(doc->ctx); break; /* TODO: load ICC profile */ switch (n) { case 2: *csp = fz_device_gray(ctx); break; case 4: *csp = fz_device_rgb(ctx); break; case 5: *csp = fz_device_cmyk(ctx); break; default: *csp = fz_device_gray(ctx); break; } } } for (i = 0; i < colorspace->n; i++) doc->color[i] = samples[i + 1]; doc->alpha = samples[0] * doc->opacity[doc->opacity_top]; }
165,228
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void buf_to_pages(const void *buf, size_t buflen, struct page **pages, unsigned int *pgbase) { const void *p = buf; *pgbase = offset_in_page(buf); p -= *pgbase; while (p < buf + buflen) { *(pages++) = virt_to_page(p); p += PAGE_CACHE_SIZE; } } Commit Message: NFSv4: include bitmap in nfsv4 get acl data The NFSv4 bitmap size is unbounded: a server can return an arbitrary sized bitmap in an FATTR4_WORD0_ACL request. Replace using the nfs4_fattr_bitmap_maxsz as a guess to the maximum bitmask returned by a server with the inclusion of the bitmap (xdr length plus bitmasks) and the acl data xdr length to the (cached) acl page data. This is a general solution to commit e5012d1f "NFSv4.1: update nfs4_fattr_bitmap_maxsz" and fixes hitting a BUG_ON in xdr_shrink_bufhead when getting ACLs. Fix a bug in decode_getacl that returned -EINVAL on ACLs > page when getxattr was called with a NULL buffer, preventing ACL > PAGE_SIZE from being retrieved. Cc: [email protected] Signed-off-by: Andy Adamson <[email protected]> Signed-off-by: Trond Myklebust <[email protected]> CWE ID: CWE-189
static void buf_to_pages(const void *buf, size_t buflen,
165,717
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ihevcd_parse_sei_payload(codec_t *ps_codec, UWORD32 u4_payload_type, UWORD32 u4_payload_size, WORD8 i1_nal_type) { parse_ctxt_t *ps_parse = &ps_codec->s_parse; bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm; WORD32 payload_bits_remaining = 0; sps_t *ps_sps; UWORD32 i; for(i = 0; i < MAX_SPS_CNT; i++) { ps_sps = ps_codec->ps_sps_base + i; if(ps_sps->i1_sps_valid) { break; } } if(NULL == ps_sps) { return; } if(NAL_PREFIX_SEI == i1_nal_type) { switch(u4_payload_type) { case SEI_BUFFERING_PERIOD: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_buffering_period_sei(ps_codec, ps_sps); break; case SEI_PICTURE_TIMING: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_pic_timing_sei(ps_codec, ps_sps); break; case SEI_TIME_CODE: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_time_code_sei(ps_codec); break; case SEI_MASTERING_DISPLAY_COLOUR_VOLUME: ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1; ihevcd_parse_mastering_disp_params_sei(ps_codec); break; case SEI_USER_DATA_REGISTERED_ITU_T_T35: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_user_data_registered_itu_t_t35(ps_codec, u4_payload_size); break; default: for(i = 0; i < u4_payload_size; i++) { ihevcd_bits_flush(ps_bitstrm, 8); } break; } } else /* NAL_SUFFIX_SEI */ { switch(u4_payload_type) { case SEI_USER_DATA_REGISTERED_ITU_T_T35: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_user_data_registered_itu_t_t35(ps_codec, u4_payload_size); break; default: for(i = 0; i < u4_payload_size; i++) { ihevcd_bits_flush(ps_bitstrm, 8); } break; } } /** * By definition the underlying bitstream terminates in a byte-aligned manner. * 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data * 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker * 3. Extract the remainingreserved_payload_extension_data bits. * * If there are fewer than 9 bits available, extract them. */ payload_bits_remaining = ihevcd_bits_num_bits_remaining(ps_bitstrm); if(payload_bits_remaining) /* more_data_in_payload() */ { WORD32 final_bits; WORD32 final_payload_bits = 0; WORD32 mask = 0xFF; UWORD32 u4_dummy; UWORD32 u4_reserved_payload_extension_data; UNUSED(u4_dummy); UNUSED(u4_reserved_payload_extension_data); while(payload_bits_remaining > 9) { BITS_PARSE("reserved_payload_extension_data", u4_reserved_payload_extension_data, ps_bitstrm, 1); payload_bits_remaining--; } final_bits = ihevcd_bits_nxt(ps_bitstrm, payload_bits_remaining); while(final_bits & (mask >> final_payload_bits)) { final_payload_bits++; continue; } while(payload_bits_remaining > (9 - final_payload_bits)) { BITS_PARSE("reserved_payload_extension_data", u4_reserved_payload_extension_data, ps_bitstrm, 1); payload_bits_remaining--; } BITS_PARSE("payload_bit_equal_to_one", u4_dummy, ps_bitstrm, 1); payload_bits_remaining--; while(payload_bits_remaining) { BITS_PARSE("payload_bit_equal_to_zero", u4_dummy, ps_bitstrm, 1); payload_bits_remaining--; } } return; } Commit Message: Fix overflow in sei user data parsing Bug: 37968960 Bug: 65484460 Test: ran POC post-patch Change-Id: I73e91b4b2976b954b5fd4f29182d6072abbc7f70 CWE ID: CWE-190
void ihevcd_parse_sei_payload(codec_t *ps_codec, UWORD32 u4_payload_type, UWORD32 u4_payload_size, WORD8 i1_nal_type) { parse_ctxt_t *ps_parse = &ps_codec->s_parse; bitstrm_t *ps_bitstrm = &ps_parse->s_bitstrm; WORD32 payload_bits_remaining = 0; sps_t *ps_sps; UWORD32 i; for(i = 0; i < MAX_SPS_CNT; i++) { ps_sps = ps_codec->ps_sps_base + i; if(ps_sps->i1_sps_valid) { break; } } if(NULL == ps_sps) { return; } if(NAL_PREFIX_SEI == i1_nal_type) { switch(u4_payload_type) { case SEI_BUFFERING_PERIOD: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_buffering_period_sei(ps_codec, ps_sps); break; case SEI_PICTURE_TIMING: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_pic_timing_sei(ps_codec, ps_sps); break; case SEI_TIME_CODE: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; ihevcd_parse_time_code_sei(ps_codec); break; case SEI_MASTERING_DISPLAY_COLOUR_VOLUME: ps_parse->s_sei_params.i4_sei_mastering_disp_colour_vol_params_present_flags = 1; ihevcd_parse_mastering_disp_params_sei(ps_codec); break; case SEI_USER_DATA_REGISTERED_ITU_T_T35: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; if(ps_parse->s_sei_params.i4_sei_user_data_cnt >= USER_DATA_MAX) { for(i = 0; i < u4_payload_size / 4; i++) { ihevcd_bits_flush(ps_bitstrm, 4 * 8); } ihevcd_bits_flush(ps_bitstrm, (u4_payload_size - i * 4) * 8); } else { ihevcd_parse_user_data_registered_itu_t_t35(ps_codec, u4_payload_size); } break; default: for(i = 0; i < u4_payload_size; i++) { ihevcd_bits_flush(ps_bitstrm, 8); } break; } } else /* NAL_SUFFIX_SEI */ { switch(u4_payload_type) { case SEI_USER_DATA_REGISTERED_ITU_T_T35: ps_parse->s_sei_params.i1_sei_parameters_present_flag = 1; if(ps_parse->s_sei_params.i4_sei_user_data_cnt >= USER_DATA_MAX) { for(i = 0; i < u4_payload_size / 4; i++) { ihevcd_bits_flush(ps_bitstrm, 4 * 8); } ihevcd_bits_flush(ps_bitstrm, (u4_payload_size - i * 4) * 8); } else { ihevcd_parse_user_data_registered_itu_t_t35(ps_codec, u4_payload_size); } break; default: for(i = 0; i < u4_payload_size; i++) { ihevcd_bits_flush(ps_bitstrm, 8); } break; } } /** * By definition the underlying bitstream terminates in a byte-aligned manner. * 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data * 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker * 3. Extract the remainingreserved_payload_extension_data bits. * * If there are fewer than 9 bits available, extract them. */ payload_bits_remaining = ihevcd_bits_num_bits_remaining(ps_bitstrm); if(payload_bits_remaining) /* more_data_in_payload() */ { WORD32 final_bits; WORD32 final_payload_bits = 0; WORD32 mask = 0xFF; UWORD32 u4_dummy; UWORD32 u4_reserved_payload_extension_data; UNUSED(u4_dummy); UNUSED(u4_reserved_payload_extension_data); while(payload_bits_remaining > 9) { BITS_PARSE("reserved_payload_extension_data", u4_reserved_payload_extension_data, ps_bitstrm, 1); payload_bits_remaining--; } final_bits = ihevcd_bits_nxt(ps_bitstrm, payload_bits_remaining); while(final_bits & (mask >> final_payload_bits)) { final_payload_bits++; continue; } while(payload_bits_remaining > (9 - final_payload_bits)) { BITS_PARSE("reserved_payload_extension_data", u4_reserved_payload_extension_data, ps_bitstrm, 1); payload_bits_remaining--; } BITS_PARSE("payload_bit_equal_to_one", u4_dummy, ps_bitstrm, 1); payload_bits_remaining--; while(payload_bits_remaining) { BITS_PARSE("payload_bit_equal_to_zero", u4_dummy, ps_bitstrm, 1); payload_bits_remaining--; } } return; }
174,102
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: __switch_to(struct task_struct *prev_p, struct task_struct *next_p) { struct thread_struct *prev = &prev_p->thread; struct thread_struct *next = &next_p->thread; int cpu = smp_processor_id(); struct tss_struct *tss = &per_cpu(init_tss, cpu); unsigned fsindex, gsindex; fpu_switch_t fpu; fpu = switch_fpu_prepare(prev_p, next_p, cpu); /* * Reload esp0, LDT and the page table pointer: */ load_sp0(tss, next); /* * Switch DS and ES. * This won't pick up thread selector changes, but I guess that is ok. */ savesegment(es, prev->es); if (unlikely(next->es | prev->es)) loadsegment(es, next->es); savesegment(ds, prev->ds); if (unlikely(next->ds | prev->ds)) loadsegment(ds, next->ds); /* We must save %fs and %gs before load_TLS() because * %fs and %gs may be cleared by load_TLS(). * * (e.g. xen_load_tls()) */ savesegment(fs, fsindex); savesegment(gs, gsindex); load_TLS(next, cpu); /* * Leave lazy mode, flushing any hypercalls made here. * This must be done before restoring TLS segments so * the GDT and LDT are properly updated, and must be * done before math_state_restore, so the TS bit is up * to date. */ arch_end_context_switch(next_p); /* * Switch FS and GS. * * Segment register != 0 always requires a reload. Also * reload when it has changed. When prev process used 64bit * base always reload to avoid an information leak. */ if (unlikely(fsindex | next->fsindex | prev->fs)) { loadsegment(fs, next->fsindex); /* * Check if the user used a selector != 0; if yes * clear 64bit base, since overloaded base is always * mapped to the Null selector */ if (fsindex) prev->fs = 0; } /* when next process has a 64bit base use it */ if (next->fs) wrmsrl(MSR_FS_BASE, next->fs); prev->fsindex = fsindex; if (unlikely(gsindex | next->gsindex | prev->gs)) { load_gs_index(next->gsindex); if (gsindex) prev->gs = 0; } if (next->gs) wrmsrl(MSR_KERNEL_GS_BASE, next->gs); prev->gsindex = gsindex; switch_fpu_finish(next_p, fpu); /* * Switch the PDA and FPU contexts. */ prev->usersp = this_cpu_read(old_rsp); this_cpu_write(old_rsp, next->usersp); this_cpu_write(current_task, next_p); /* * If it were not for PREEMPT_ACTIVE we could guarantee that the * preempt_count of all tasks was equal here and this would not be * needed. */ task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count); this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count); this_cpu_write(kernel_stack, (unsigned long)task_stack_page(next_p) + THREAD_SIZE - KERNEL_STACK_OFFSET); /* * Now maybe reload the debug registers and handle I/O bitmaps */ if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT || task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV)) __switch_to_xtra(prev_p, next_p, tss); return prev_p; } Commit Message: x86_64, switch_to(): Load TLS descriptors before switching DS and ES Otherwise, if buggy user code points DS or ES into the TLS array, they would be corrupted after a context switch. This also significantly improves the comments and documents some gotchas in the code. Before this patch, the both tests below failed. With this patch, the es test passes, although the gsbase test still fails. ----- begin es test ----- /* * Copyright (c) 2014 Andy Lutomirski * GPL v2 */ static unsigned short GDT3(int idx) { return (idx << 3) | 3; } static int create_tls(int idx, unsigned int base) { struct user_desc desc = { .entry_number = idx, .base_addr = base, .limit = 0xfffff, .seg_32bit = 1, .contents = 0, /* Data, grow-up */ .read_exec_only = 0, .limit_in_pages = 1, .seg_not_present = 0, .useable = 0, }; if (syscall(SYS_set_thread_area, &desc) != 0) err(1, "set_thread_area"); return desc.entry_number; } int main() { int idx = create_tls(-1, 0); printf("Allocated GDT index %d\n", idx); unsigned short orig_es; asm volatile ("mov %%es,%0" : "=rm" (orig_es)); int errors = 0; int total = 1000; for (int i = 0; i < total; i++) { asm volatile ("mov %0,%%es" : : "rm" (GDT3(idx))); usleep(100); unsigned short es; asm volatile ("mov %%es,%0" : "=rm" (es)); asm volatile ("mov %0,%%es" : : "rm" (orig_es)); if (es != GDT3(idx)) { if (errors == 0) printf("[FAIL]\tES changed from 0x%hx to 0x%hx\n", GDT3(idx), es); errors++; } } if (errors) { printf("[FAIL]\tES was corrupted %d/%d times\n", errors, total); return 1; } else { printf("[OK]\tES was preserved\n"); return 0; } } ----- end es test ----- ----- begin gsbase test ----- /* * gsbase.c, a gsbase test * Copyright (c) 2014 Andy Lutomirski * GPL v2 */ static unsigned char *testptr, *testptr2; static unsigned char read_gs_testvals(void) { unsigned char ret; asm volatile ("movb %%gs:%1, %0" : "=r" (ret) : "m" (*testptr)); return ret; } int main() { int errors = 0; testptr = mmap((void *)0x200000000UL, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); if (testptr == MAP_FAILED) err(1, "mmap"); testptr2 = mmap((void *)0x300000000UL, 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); if (testptr2 == MAP_FAILED) err(1, "mmap"); *testptr = 0; *testptr2 = 1; if (syscall(SYS_arch_prctl, ARCH_SET_GS, (unsigned long)testptr2 - (unsigned long)testptr) != 0) err(1, "ARCH_SET_GS"); usleep(100); if (read_gs_testvals() == 1) { printf("[OK]\tARCH_SET_GS worked\n"); } else { printf("[FAIL]\tARCH_SET_GS failed\n"); errors++; } asm volatile ("mov %0,%%gs" : : "r" (0)); if (read_gs_testvals() == 0) { printf("[OK]\tWriting 0 to gs worked\n"); } else { printf("[FAIL]\tWriting 0 to gs failed\n"); errors++; } usleep(100); if (read_gs_testvals() == 0) { printf("[OK]\tgsbase is still zero\n"); } else { printf("[FAIL]\tgsbase was corrupted\n"); errors++; } return errors == 0 ? 0 : 1; } ----- end gsbase test ----- Signed-off-by: Andy Lutomirski <[email protected]> Cc: <[email protected]> Cc: Andi Kleen <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/509d27c9fec78217691c3dad91cec87e1006b34a.1418075657.git.luto@amacapital.net Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-200
__switch_to(struct task_struct *prev_p, struct task_struct *next_p) { struct thread_struct *prev = &prev_p->thread; struct thread_struct *next = &next_p->thread; int cpu = smp_processor_id(); struct tss_struct *tss = &per_cpu(init_tss, cpu); unsigned fsindex, gsindex; fpu_switch_t fpu; fpu = switch_fpu_prepare(prev_p, next_p, cpu); /* Reload esp0 and ss1. */ load_sp0(tss, next); /* We must save %fs and %gs before load_TLS() because * %fs and %gs may be cleared by load_TLS(). * * (e.g. xen_load_tls()) */ savesegment(fs, fsindex); savesegment(gs, gsindex); /* * Load TLS before restoring any segments so that segment loads * reference the correct GDT entries. */ load_TLS(next, cpu); /* * Leave lazy mode, flushing any hypercalls made here. This * must be done after loading TLS entries in the GDT but before * loading segments that might reference them, and and it must * be done before math_state_restore, so the TS bit is up to * date. */ arch_end_context_switch(next_p); /* Switch DS and ES. * * Reading them only returns the selectors, but writing them (if * nonzero) loads the full descriptor from the GDT or LDT. The * LDT for next is loaded in switch_mm, and the GDT is loaded * above. * * We therefore need to write new values to the segment * registers on every context switch unless both the new and old * values are zero. * * Note that we don't need to do anything for CS and SS, as * those are saved and restored as part of pt_regs. */ savesegment(es, prev->es); if (unlikely(next->es | prev->es)) loadsegment(es, next->es); savesegment(ds, prev->ds); if (unlikely(next->ds | prev->ds)) loadsegment(ds, next->ds); /* * Switch FS and GS. * * These are even more complicated than FS and GS: they have * 64-bit bases are that controlled by arch_prctl. Those bases * only differ from the values in the GDT or LDT if the selector * is 0. * * Loading the segment register resets the hidden base part of * the register to 0 or the value from the GDT / LDT. If the * next base address zero, writing 0 to the segment register is * much faster than using wrmsr to explicitly zero the base. * * The thread_struct.fs and thread_struct.gs values are 0 * if the fs and gs bases respectively are not overridden * from the values implied by fsindex and gsindex. They * are nonzero, and store the nonzero base addresses, if * the bases are overridden. * * (fs != 0 && fsindex != 0) || (gs != 0 && gsindex != 0) should * be impossible. * * Therefore we need to reload the segment registers if either * the old or new selector is nonzero, and we need to override * the base address if next thread expects it to be overridden. * * This code is unnecessarily slow in the case where the old and * new indexes are zero and the new base is nonzero -- it will * unnecessarily write 0 to the selector before writing the new * base address. * * Note: This all depends on arch_prctl being the only way that * user code can override the segment base. Once wrfsbase and * wrgsbase are enabled, most of this code will need to change. */ if (unlikely(fsindex | next->fsindex | prev->fs)) { loadsegment(fs, next->fsindex); /* * If user code wrote a nonzero value to FS, then it also * cleared the overridden base address. * * XXX: if user code wrote 0 to FS and cleared the base * address itself, we won't notice and we'll incorrectly * restore the prior base address next time we reschdule * the process. */ if (fsindex) prev->fs = 0; } if (next->fs) wrmsrl(MSR_FS_BASE, next->fs); prev->fsindex = fsindex; if (unlikely(gsindex | next->gsindex | prev->gs)) { load_gs_index(next->gsindex); /* This works (and fails) the same way as fsindex above. */ if (gsindex) prev->gs = 0; } if (next->gs) wrmsrl(MSR_KERNEL_GS_BASE, next->gs); prev->gsindex = gsindex; switch_fpu_finish(next_p, fpu); /* * Switch the PDA and FPU contexts. */ prev->usersp = this_cpu_read(old_rsp); this_cpu_write(old_rsp, next->usersp); this_cpu_write(current_task, next_p); /* * If it were not for PREEMPT_ACTIVE we could guarantee that the * preempt_count of all tasks was equal here and this would not be * needed. */ task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count); this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count); this_cpu_write(kernel_stack, (unsigned long)task_stack_page(next_p) + THREAD_SIZE - KERNEL_STACK_OFFSET); /* * Now maybe reload the debug registers and handle I/O bitmaps */ if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT || task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV)) __switch_to_xtra(prev_p, next_p, tss); return prev_p; }
166,237
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void nbd_recv_coroutines_enter_all(NBDClientSession *s) { int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } } Commit Message: CWE ID: CWE-20
static void nbd_recv_coroutines_enter_all(NBDClientSession *s) static void nbd_recv_coroutines_enter_all(BlockDriverState *bs) { NBDClientSession *s = nbd_get_client_session(bs); int i; for (i = 0; i < MAX_NBD_REQUESTS; i++) { qemu_coroutine_enter(s->recv_coroutine[i]); qemu_coroutine_enter(s->recv_coroutine[i]); } }
165,449
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int snd_timer_user_release(struct inode *inode, struct file *file) { struct snd_timer_user *tu; if (file->private_data) { tu = file->private_data; file->private_data = NULL; if (tu->timeri) snd_timer_close(tu->timeri); kfree(tu->queue); kfree(tu->tqueue); kfree(tu); } return 0; } Commit Message: ALSA: timer: Fix race among timer ioctls ALSA timer ioctls have an open race and this may lead to a use-after-free of timer instance object. A simplistic fix is to make each ioctl exclusive. We have already tread_sem for controlling the tread, and extend this as a global mutex to be applied to each ioctl. The downside is, of course, the worse concurrency. But these ioctls aren't to be parallel accessible, in anyway, so it should be fine to serialize there. Reported-by: Dmitry Vyukov <[email protected]> Tested-by: Dmitry Vyukov <[email protected]> Cc: <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-362
static int snd_timer_user_release(struct inode *inode, struct file *file) { struct snd_timer_user *tu; if (file->private_data) { tu = file->private_data; file->private_data = NULL; mutex_lock(&tu->ioctl_lock); if (tu->timeri) snd_timer_close(tu->timeri); mutex_unlock(&tu->ioctl_lock); kfree(tu->queue); kfree(tu->tqueue); kfree(tu); } return 0; }
167,406
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; } Commit Message: CVE-2017-12993/Juniper: Add more bounds checks. This fixes a buffer over-read discovered by Kamil Frankowicz. Add tests using the capture files supplied by the reporter(s). CWE ID: CWE-125
juniper_ggsn_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; struct juniper_ggsn_header { uint8_t svc_id; uint8_t flags_len; uint8_t proto; uint8_t flags; uint8_t vlan_id[2]; uint8_t res[2]; }; const struct juniper_ggsn_header *gh; l2info.pictype = DLT_JUNIPER_GGSN; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; p+=l2info.header_len; gh = (struct juniper_ggsn_header *)&l2info.cookie; ND_TCHECK(*gh); if (ndo->ndo_eflag) { ND_PRINT((ndo, "proto %s (%u), vlan %u: ", tok2str(juniper_protocol_values,"Unknown",gh->proto), gh->proto, EXTRACT_16BITS(&gh->vlan_id[0]))); } switch (gh->proto) { case JUNIPER_PROTO_IPV4: ip_print(ndo, p, l2info.length); break; case JUNIPER_PROTO_IPV6: ip6_print(ndo, p, l2info.length); break; default: if (!ndo->ndo_eflag) ND_PRINT((ndo, "unknown GGSN proto (%u)", gh->proto)); } return l2info.header_len; trunc: ND_PRINT((ndo, "[|juniper_services]")); return l2info.header_len; }
167,917
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: T42_Face_Init( FT_Stream stream, FT_Face t42face, /* T42_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { T42_Face face = (T42_Face)t42face; FT_Error error; FT_Service_PsCMaps psnames; PSAux_Service psaux; FT_Face root = (FT_Face)&face->root; T1_Font type1 = &face->type1; PS_FontInfo info = &type1->font_info; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); face->ttf_face = NULL; face->root.num_faces = 1; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); face->psnames = psnames; face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); psaux = (PSAux_Service)face->psaux; if ( !psaux ) { FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } FT_TRACE2(( "Type 42 driver\n" )); /* open the tokenizer, this will also check the font format */ error = T42_Open_Face( face ); if ( error ) goto Exit; /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ if ( face_index > 0 ) { FT_ERROR(( "T42_Face_Init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* Now load the font program into the face object */ /* Init the face object fields */ /* Now set up root face fields */ root->num_glyphs = type1->num_glyphs; root->num_charmaps = 0; root->face_index = 0; root->face_flags |= FT_FACE_FLAG_SCALABLE | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_GLYPH_NAMES; if ( info->is_fixed_pitch ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; /* We only set this flag if we have the patented bytecode interpreter. */ /* There are no known `tricky' Type42 fonts that could be loaded with */ /* the unpatented interpreter. */ #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER root->face_flags |= FT_FACE_FLAG_HINTER; #endif /* XXX: TODO -- add kerning with .afm support */ /* get style name -- be careful, some broken fonts only */ /* have a `/FontName' dictionary entry! */ root->family_name = info->family_name; /* assume "Regular" style if we don't know better */ root->style_name = (char *)"Regular"; if ( root->family_name ) { char* full = info->full_name; char* family = root->family_name; if ( full ) { while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { if ( !*family ) root->style_name = full; break; } } } } } else { /* do we have a `/FontName'? */ if ( type1->font_name ) root->family_name = type1->font_name; } /* no embedded bitmap support */ root->num_fixed_sizes = 0; root->available_sizes = 0; /* Load the TTF font embedded in the T42 font */ { FT_Open_Args args; args.flags = FT_OPEN_MEMORY; args.memory_base = face->ttf_data; args.memory_size = face->ttf_size; args.flags |= FT_OPEN_PARAMS; args.num_params = num_params; args.params = params; } error = FT_Open_Face( FT_FACE_LIBRARY( face ), &args, 0, &face->ttf_face ); } Commit Message: CWE ID:
T42_Face_Init( FT_Stream stream, FT_Face t42face, /* T42_Face */ FT_Int face_index, FT_Int num_params, FT_Parameter* params ) { T42_Face face = (T42_Face)t42face; FT_Error error; FT_Service_PsCMaps psnames; PSAux_Service psaux; FT_Face root = (FT_Face)&face->root; T1_Font type1 = &face->type1; PS_FontInfo info = &type1->font_info; FT_UNUSED( num_params ); FT_UNUSED( params ); FT_UNUSED( stream ); face->ttf_face = NULL; face->root.num_faces = 1; FT_FACE_FIND_GLOBAL_SERVICE( face, psnames, POSTSCRIPT_CMAPS ); face->psnames = psnames; face->psaux = FT_Get_Module_Interface( FT_FACE_LIBRARY( face ), "psaux" ); psaux = (PSAux_Service)face->psaux; if ( !psaux ) { FT_ERROR(( "T42_Face_Init: cannot access `psaux' module\n" )); error = FT_THROW( Missing_Module ); goto Exit; } FT_TRACE2(( "Type 42 driver\n" )); /* open the tokenizer, this will also check the font format */ error = T42_Open_Face( face ); if ( error ) goto Exit; /* if we just wanted to check the format, leave successfully now */ if ( face_index < 0 ) goto Exit; /* check the face index */ if ( face_index > 0 ) { FT_ERROR(( "T42_Face_Init: invalid face index\n" )); error = FT_THROW( Invalid_Argument ); goto Exit; } /* Now load the font program into the face object */ /* Init the face object fields */ /* Now set up root face fields */ root->num_glyphs = type1->num_glyphs; root->num_charmaps = 0; root->face_index = 0; root->face_flags |= FT_FACE_FLAG_SCALABLE | FT_FACE_FLAG_HORIZONTAL | FT_FACE_FLAG_GLYPH_NAMES; if ( info->is_fixed_pitch ) root->face_flags |= FT_FACE_FLAG_FIXED_WIDTH; /* We only set this flag if we have the patented bytecode interpreter. */ /* There are no known `tricky' Type42 fonts that could be loaded with */ /* the unpatented interpreter. */ #ifdef TT_CONFIG_OPTION_BYTECODE_INTERPRETER root->face_flags |= FT_FACE_FLAG_HINTER; #endif /* XXX: TODO -- add kerning with .afm support */ /* get style name -- be careful, some broken fonts only */ /* have a `/FontName' dictionary entry! */ root->family_name = info->family_name; /* assume "Regular" style if we don't know better */ root->style_name = (char *)"Regular"; if ( root->family_name ) { char* full = info->full_name; char* family = root->family_name; if ( full ) { while ( *full ) { if ( *full == *family ) { family++; full++; } else { if ( *full == ' ' || *full == '-' ) full++; else if ( *family == ' ' || *family == '-' ) family++; else { if ( !*family ) root->style_name = full; break; } } } } } else { /* do we have a `/FontName'? */ if ( type1->font_name ) root->family_name = type1->font_name; } /* no embedded bitmap support */ root->num_fixed_sizes = 0; root->available_sizes = 0; /* Load the TTF font embedded in the T42 font */ { FT_Open_Args args; args.flags = FT_OPEN_MEMORY | FT_OPEN_DRIVER; args.driver = FT_Get_Module( FT_FACE_LIBRARY( face ), "truetype" ); args.memory_base = face->ttf_data; args.memory_size = face->ttf_size; args.flags |= FT_OPEN_PARAMS; args.num_params = num_params; args.params = params; } error = FT_Open_Face( FT_FACE_LIBRARY( face ), &args, 0, &face->ttf_face ); }
164,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } }
167,061
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool generic_new(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, unsigned int *timeouts) { return true; } Commit Message: netfilter: conntrack: disable generic tracking for known protocols Given following iptables ruleset: -P FORWARD DROP -A FORWARD -m sctp --dport 9 -j ACCEPT -A FORWARD -p tcp --dport 80 -j ACCEPT -A FORWARD -p tcp -m conntrack -m state ESTABLISHED,RELATED -j ACCEPT One would assume that this allows SCTP on port 9 and TCP on port 80. Unfortunately, if the SCTP conntrack module is not loaded, this allows *all* SCTP communication, to pass though, i.e. -p sctp -j ACCEPT, which we think is a security issue. This is because on the first SCTP packet on port 9, we create a dummy "generic l4" conntrack entry without any port information (since conntrack doesn't know how to extract this information). All subsequent packets that are unknown will then be in established state since they will fallback to proto_generic and will match the 'generic' entry. Our originally proposed version [1] completely disabled generic protocol tracking, but Jozsef suggests to not track protocols for which a more suitable helper is available, hence we now mitigate the issue for in tree known ct protocol helpers only, so that at least NAT and direction information will still be preserved for others. [1] http://www.spinics.net/lists/netfilter-devel/msg33430.html Joint work with Daniel Borkmann. Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> Acked-by: Jozsef Kadlecsik <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-254
static bool generic_new(struct nf_conn *ct, const struct sk_buff *skb, unsigned int dataoff, unsigned int *timeouts) { return nf_generic_should_process(nf_ct_protonum(ct)); }
166,809
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void free_bprm(struct linux_binprm *bprm) { free_arg_pages(bprm); if (bprm->cred) { mutex_unlock(&current->signal->cred_guard_mutex); abort_creds(bprm->cred); } kfree(bprm); } Commit Message: exec: do not leave bprm->interp on stack If a series of scripts are executed, each triggering module loading via unprintable bytes in the script header, kernel stack contents can leak into the command line. Normally execution of binfmt_script and binfmt_misc happens recursively. However, when modules are enabled, and unprintable bytes exist in the bprm->buf, execution will restart after attempting to load matching binfmt modules. Unfortunately, the logic in binfmt_script and binfmt_misc does not expect to get restarted. They leave bprm->interp pointing to their local stack. This means on restart bprm->interp is left pointing into unused stack memory which can then be copied into the userspace argv areas. After additional study, it seems that both recursion and restart remains the desirable way to handle exec with scripts, misc, and modules. As such, we need to protect the changes to interp. This changes the logic to require allocation for any changes to the bprm->interp. To avoid adding a new kmalloc to every exec, the default value is left as-is. Only when passing through binfmt_script or binfmt_misc does an allocation take place. For a proof of concept, see DoTest.sh from: http://www.halfdog.net/Security/2012/LinuxKernelBinfmtScriptStackDataDisclosure/ Signed-off-by: Kees Cook <[email protected]> Cc: halfdog <[email protected]> Cc: P J P <[email protected]> Cc: Alexander Viro <[email protected]> Cc: <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-200
void free_bprm(struct linux_binprm *bprm) { free_arg_pages(bprm); if (bprm->cred) { mutex_unlock(&current->signal->cred_guard_mutex); abort_creds(bprm->cred); } /* If a binfmt changed the interp, free it. */ if (bprm->interp != bprm->filename) kfree(bprm->interp); kfree(bprm); }
166,199
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg) { struct oabi_flock64 user; struct flock64 kernel; mm_segment_t fs = USER_DS; /* initialized to kill a warning */ unsigned long local_arg = arg; int ret; switch (cmd) { case F_OFD_GETLK: case F_OFD_SETLK: case F_OFD_SETLKW: case F_GETLK64: case F_SETLK64: case F_SETLKW64: if (copy_from_user(&user, (struct oabi_flock64 __user *)arg, sizeof(user))) return -EFAULT; kernel.l_type = user.l_type; kernel.l_whence = user.l_whence; kernel.l_start = user.l_start; kernel.l_len = user.l_len; kernel.l_pid = user.l_pid; local_arg = (unsigned long)&kernel; fs = get_fs(); set_fs(KERNEL_DS); } ret = sys_fcntl64(fd, cmd, local_arg); switch (cmd) { case F_GETLK64: if (!ret) { user.l_type = kernel.l_type; user.l_whence = kernel.l_whence; user.l_start = kernel.l_start; user.l_len = kernel.l_len; user.l_pid = kernel.l_pid; if (copy_to_user((struct oabi_flock64 __user *)arg, &user, sizeof(user))) ret = -EFAULT; } case F_SETLK64: case F_SETLKW64: set_fs(fs); } return ret; } Commit Message: [PATCH] arm: fix handling of F_OFD_... in oabi_fcntl64() Cc: [email protected] # 3.15+ Reviewed-by: Jeff Layton <[email protected]> Signed-off-by: Al Viro <[email protected]> CWE ID: CWE-264
asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, static long do_locks(unsigned int fd, unsigned int cmd, unsigned long arg) { struct flock64 kernel; struct oabi_flock64 user; mm_segment_t fs; long ret; if (copy_from_user(&user, (struct oabi_flock64 __user *)arg, sizeof(user))) return -EFAULT; kernel.l_type = user.l_type; kernel.l_whence = user.l_whence; kernel.l_start = user.l_start; kernel.l_len = user.l_len; kernel.l_pid = user.l_pid; fs = get_fs(); set_fs(KERNEL_DS); ret = sys_fcntl64(fd, cmd, (unsigned long)&kernel); set_fs(fs); if (!ret && (cmd == F_GETLK64 || cmd == F_OFD_GETLK)) { user.l_type = kernel.l_type; user.l_whence = kernel.l_whence; user.l_start = kernel.l_start; user.l_len = kernel.l_len; user.l_pid = kernel.l_pid; if (copy_to_user((struct oabi_flock64 __user *)arg, &user, sizeof(user))) ret = -EFAULT; } return ret; } asmlinkage long sys_oabi_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg) { switch (cmd) { case F_OFD_GETLK: case F_OFD_SETLK: case F_OFD_SETLKW: case F_GETLK64: case F_SETLK64: case F_SETLKW64: return do_locks(fd, cmd, arg); default: return sys_fcntl64(fd, cmd, arg); } }
167,458
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; size_t newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; }
168,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintWebViewHelper::OnPrintingDone(bool success) { notify_browser_of_print_failure_ = false; if (!success) LOG(ERROR) << "Failure in OnPrintingDone"; DidFinishPrinting(success ? OK : FAIL_PRINT); } Commit Message: Crash on nested IPC handlers in PrintWebViewHelper Class is not designed to handle nested IPC. Regular flows also does not expect them. Still during printing of plugging them may show message boxes and start nested message loops. For now we are going just crash. If stats show us that this case is frequent we will have to do something more complicated. BUG=502562 Review URL: https://codereview.chromium.org/1228693002 Cr-Commit-Position: refs/heads/master@{#338100} CWE ID:
void PrintWebViewHelper::OnPrintingDone(bool success) { CHECK_LE(ipc_nesting_level_, 1); notify_browser_of_print_failure_ = false; if (!success) LOG(ERROR) << "Failure in OnPrintingDone"; DidFinishPrinting(success ? OK : FAIL_PRINT); }
171,877
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_policy_2_svc(cpol_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; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, NULL, NULL)) { ret.code = KADM5_AUTH_ADD; log_unauth("kadm5_create_policy", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_create_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } 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
create_policy_2_svc(cpol_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; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, NULL, NULL)) { ret.code = KADM5_AUTH_ADD; log_unauth("kadm5_create_policy", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_create_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void put_ucounts(struct ucounts *ucounts) { unsigned long flags; if (atomic_dec_and_test(&ucounts->count)) { spin_lock_irqsave(&ucounts_lock, flags); hlist_del_init(&ucounts->node); spin_unlock_irqrestore(&ucounts_lock, flags); kfree(ucounts); } } Commit Message: ucount: Remove the atomicity from ucount->count Always increment/decrement ucount->count under the ucounts_lock. The increments are there already and moving the decrements there means the locking logic of the code is simpler. This simplification in the locking logic fixes a race between put_ucounts and get_ucounts that could result in a use-after-free because the count could go zero then be found by get_ucounts and then be freed by put_ucounts. A bug presumably this one was found by a combination of syzkaller and KASAN. JongWhan Kim reported the syzkaller failure and Dmitry Vyukov spotted the race in the code. Cc: [email protected] Fixes: f6b2db1a3e8d ("userns: Make the count of user namespaces per user") Reported-by: JongHwan Kim <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Reviewed-by: Andrei Vagin <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]> CWE ID: CWE-416
static void put_ucounts(struct ucounts *ucounts) { unsigned long flags; spin_lock_irqsave(&ucounts_lock, flags); ucounts->count -= 1; if (!ucounts->count) hlist_del_init(&ucounts->node); else ucounts = NULL; spin_unlock_irqrestore(&ucounts_lock, flags); kfree(ucounts); }
168,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::Handle<v8::Value> V8Proxy::throwNotEnoughArgumentsError() { return throwError(TypeError, "Not enough arguments"); } Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError() https://bugs.webkit.org/show_bug.cgi?id=86983 Reviewed by Adam Barth. The objective is to pass Isolate around in V8 bindings. This patch passes Isolate to throwNotEnoughArgumentsError(). No tests. No change in behavior. * bindings/scripts/CodeGeneratorV8.pm: (GenerateArgumentsCountCheck): (GenerateEventConstructorCallback): * bindings/scripts/test/V8/V8Float64Array.cpp: (WebCore::Float64ArrayV8Internal::fooCallback): * bindings/scripts/test/V8/V8TestActiveDOMObject.cpp: (WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback): (WebCore::TestActiveDOMObjectV8Internal::postMessageCallback): * bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp: (WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback): * bindings/scripts/test/V8/V8TestEventConstructor.cpp: (WebCore::V8TestEventConstructor::constructorCallback): * bindings/scripts/test/V8/V8TestEventTarget.cpp: (WebCore::TestEventTargetV8Internal::itemCallback): (WebCore::TestEventTargetV8Internal::dispatchEventCallback): * bindings/scripts/test/V8/V8TestInterface.cpp: (WebCore::TestInterfaceV8Internal::supplementalMethod2Callback): (WebCore::V8TestInterface::constructorCallback): * bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp: (WebCore::TestMediaQueryListListenerV8Internal::methodCallback): * bindings/scripts/test/V8/V8TestNamedConstructor.cpp: (WebCore::V8TestNamedConstructorConstructorCallback): * bindings/scripts/test/V8/V8TestObj.cpp: (WebCore::TestObjV8Internal::voidMethodWithArgsCallback): (WebCore::TestObjV8Internal::intMethodWithArgsCallback): (WebCore::TestObjV8Internal::objMethodWithArgsCallback): (WebCore::TestObjV8Internal::methodWithSequenceArgCallback): (WebCore::TestObjV8Internal::methodReturningSequenceCallback): (WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback): (WebCore::TestObjV8Internal::serializedValueCallback): (WebCore::TestObjV8Internal::idbKeyCallback): (WebCore::TestObjV8Internal::optionsObjectCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback): (WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback): (WebCore::TestObjV8Internal::methodWithCallbackArgCallback): (WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback): (WebCore::TestObjV8Internal::overloadedMethod1Callback): (WebCore::TestObjV8Internal::overloadedMethod2Callback): (WebCore::TestObjV8Internal::overloadedMethod3Callback): (WebCore::TestObjV8Internal::overloadedMethod4Callback): (WebCore::TestObjV8Internal::overloadedMethod5Callback): (WebCore::TestObjV8Internal::overloadedMethod6Callback): (WebCore::TestObjV8Internal::overloadedMethod7Callback): (WebCore::TestObjV8Internal::overloadedMethod11Callback): (WebCore::TestObjV8Internal::overloadedMethod12Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback): (WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback): (WebCore::TestObjV8Internal::convert1Callback): (WebCore::TestObjV8Internal::convert2Callback): (WebCore::TestObjV8Internal::convert3Callback): (WebCore::TestObjV8Internal::convert4Callback): (WebCore::TestObjV8Internal::convert5Callback): (WebCore::TestObjV8Internal::strictFunctionCallback): (WebCore::V8TestObj::constructorCallback): * bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp: (WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback): (WebCore::V8TestSerializedScriptValueInterface::constructorCallback): * bindings/v8/ScriptController.cpp: (WebCore::setValueAndClosePopupCallback): * bindings/v8/V8Proxy.cpp: (WebCore::V8Proxy::throwNotEnoughArgumentsError): * bindings/v8/V8Proxy.h: (V8Proxy): * bindings/v8/custom/V8AudioContextCustom.cpp: (WebCore::V8AudioContext::constructorCallback): * bindings/v8/custom/V8DataViewCustom.cpp: (WebCore::V8DataView::getInt8Callback): (WebCore::V8DataView::getUint8Callback): (WebCore::V8DataView::setInt8Callback): (WebCore::V8DataView::setUint8Callback): * bindings/v8/custom/V8DirectoryEntryCustom.cpp: (WebCore::V8DirectoryEntry::getDirectoryCallback): (WebCore::V8DirectoryEntry::getFileCallback): * bindings/v8/custom/V8IntentConstructor.cpp: (WebCore::V8Intent::constructorCallback): * bindings/v8/custom/V8SVGLengthCustom.cpp: (WebCore::V8SVGLength::convertToSpecifiedUnitsCallback): * bindings/v8/custom/V8WebGLRenderingContextCustom.cpp: (WebCore::getObjectParameter): (WebCore::V8WebGLRenderingContext::getAttachedShadersCallback): (WebCore::V8WebGLRenderingContext::getExtensionCallback): (WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback): (WebCore::V8WebGLRenderingContext::getParameterCallback): (WebCore::V8WebGLRenderingContext::getProgramParameterCallback): (WebCore::V8WebGLRenderingContext::getShaderParameterCallback): (WebCore::V8WebGLRenderingContext::getUniformCallback): (WebCore::vertexAttribAndUniformHelperf): (WebCore::uniformHelperi): (WebCore::uniformMatrixHelper): * bindings/v8/custom/V8WebKitMutationObserverCustom.cpp: (WebCore::V8WebKitMutationObserver::constructorCallback): (WebCore::V8WebKitMutationObserver::observeCallback): * bindings/v8/custom/V8WebSocketCustom.cpp: (WebCore::V8WebSocket::constructorCallback): (WebCore::V8WebSocket::sendCallback): * bindings/v8/custom/V8XMLHttpRequestCustom.cpp: (WebCore::V8XMLHttpRequest::openCallback): git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
v8::Handle<v8::Value> V8Proxy::throwNotEnoughArgumentsError() v8::Handle<v8::Value> V8Proxy::throwNotEnoughArgumentsError(v8::Isolate* isolate) { return throwError(TypeError, "Not enough arguments", isolate); }
171,110
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int xwd_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { AVFrame *p = data; const uint8_t *buf = avpkt->data; int i, ret, buf_size = avpkt->size; uint32_t version, header_size, vclass, ncolors; uint32_t xoffset, be, bpp, lsize, rsize; uint32_t pixformat, pixdepth, bunit, bitorder, bpad; uint32_t rgb[3]; uint8_t *ptr; GetByteContext gb; if (buf_size < XWD_HEADER_SIZE) return AVERROR_INVALIDDATA; bytestream2_init(&gb, buf, buf_size); header_size = bytestream2_get_be32u(&gb); version = bytestream2_get_be32u(&gb); if (version != XWD_VERSION) { av_log(avctx, AV_LOG_ERROR, "unsupported version\n"); return AVERROR_INVALIDDATA; } if (buf_size < header_size || header_size < XWD_HEADER_SIZE) { av_log(avctx, AV_LOG_ERROR, "invalid header size\n"); return AVERROR_INVALIDDATA; } pixformat = bytestream2_get_be32u(&gb); pixdepth = bytestream2_get_be32u(&gb); avctx->width = bytestream2_get_be32u(&gb); avctx->height = bytestream2_get_be32u(&gb); xoffset = bytestream2_get_be32u(&gb); be = bytestream2_get_be32u(&gb); bunit = bytestream2_get_be32u(&gb); bitorder = bytestream2_get_be32u(&gb); bpad = bytestream2_get_be32u(&gb); bpp = bytestream2_get_be32u(&gb); lsize = bytestream2_get_be32u(&gb); vclass = bytestream2_get_be32u(&gb); rgb[0] = bytestream2_get_be32u(&gb); rgb[1] = bytestream2_get_be32u(&gb); rgb[2] = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, 8); ncolors = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20)); av_log(avctx, AV_LOG_DEBUG, "pixformat %"PRIu32", pixdepth %"PRIu32", bunit %"PRIu32", bitorder %"PRIu32", bpad %"PRIu32"\n", pixformat, pixdepth, bunit, bitorder, bpad); av_log(avctx, AV_LOG_DEBUG, "vclass %"PRIu32", ncolors %"PRIu32", bpp %"PRIu32", be %"PRIu32", lsize %"PRIu32", xoffset %"PRIu32"\n", vclass, ncolors, bpp, be, lsize, xoffset); av_log(avctx, AV_LOG_DEBUG, "red %0"PRIx32", green %0"PRIx32", blue %0"PRIx32"\n", rgb[0], rgb[1], rgb[2]); if (pixformat > XWD_Z_PIXMAP) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap format\n"); return AVERROR_INVALIDDATA; } if (pixdepth == 0 || pixdepth > 32) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap depth\n"); return AVERROR_INVALIDDATA; } if (xoffset) { avpriv_request_sample(avctx, "xoffset %"PRIu32"", xoffset); return AVERROR_PATCHWELCOME; } if (be > 1) { av_log(avctx, AV_LOG_ERROR, "invalid byte order\n"); return AVERROR_INVALIDDATA; } if (bitorder > 1) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap bit order\n"); return AVERROR_INVALIDDATA; } if (bunit != 8 && bunit != 16 && bunit != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap unit\n"); return AVERROR_INVALIDDATA; } if (bpad != 8 && bpad != 16 && bpad != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap scan-line pad\n"); return AVERROR_INVALIDDATA; } if (bpp == 0 || bpp > 32) { av_log(avctx, AV_LOG_ERROR, "invalid bits per pixel\n"); return AVERROR_INVALIDDATA; } if (ncolors > 256) { av_log(avctx, AV_LOG_ERROR, "invalid number of entries in colormap\n"); return AVERROR_INVALIDDATA; } if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0) return ret; rsize = FFALIGN(avctx->width * bpp, bpad) / 8; if (lsize < rsize) { av_log(avctx, AV_LOG_ERROR, "invalid bytes per scan-line\n"); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) { av_log(avctx, AV_LOG_ERROR, "input buffer too small\n"); return AVERROR_INVALIDDATA; } if (pixformat != XWD_Z_PIXMAP) { avpriv_report_missing_feature(avctx, "Pixmap format %"PRIu32, pixformat); return AVERROR_PATCHWELCOME; } avctx->pix_fmt = AV_PIX_FMT_NONE; switch (vclass) { case XWD_STATIC_GRAY: case XWD_GRAY_SCALE: if (bpp != 1 && bpp != 8) return AVERROR_INVALIDDATA; if (pixdepth == 1) { avctx->pix_fmt = AV_PIX_FMT_MONOWHITE; } else if (pixdepth == 8) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } break; case XWD_STATIC_COLOR: case XWD_PSEUDO_COLOR: if (bpp == 8) avctx->pix_fmt = AV_PIX_FMT_PAL8; break; case XWD_TRUE_COLOR: case XWD_DIRECT_COLOR: if (bpp != 16 && bpp != 24 && bpp != 32) return AVERROR_INVALIDDATA; if (bpp == 16 && pixdepth == 15) { if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE; else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00) avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE; } else if (bpp == 16 && pixdepth == 16) { if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE; else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800) avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE; } else if (bpp == 24) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24; } else if (bpp == 32) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA; } bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE); break; default: av_log(avctx, AV_LOG_ERROR, "invalid visual class\n"); return AVERROR_INVALIDDATA; } if (avctx->pix_fmt == AV_PIX_FMT_NONE) { avpriv_request_sample(avctx, "Unknown file: bpp %"PRIu32", pixdepth %"PRIu32", vclass %"PRIu32"", bpp, pixdepth, vclass); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { uint32_t *dst = (uint32_t *)p->data[1]; uint8_t red, green, blue; for (i = 0; i < ncolors; i++) { bytestream2_skipu(&gb, 4); // skip colormap entry number red = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); green = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); blue = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 3); // skip bitmask flag and padding dst[i] = red << 16 | green << 8 | blue; } } ptr = p->data[0]; for (i = 0; i < avctx->height; i++) { bytestream2_get_bufferu(&gb, ptr, rsize); bytestream2_skipu(&gb, lsize - rsize); ptr += p->linesize[0]; } *got_frame = 1; return buf_size; } Commit Message: avcodec/xwddec: Check bpp more completely Fixes out of array access Fixes: 1399/clusterfuzz-testcase-minimized-4866094172995584 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int xwd_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { AVFrame *p = data; const uint8_t *buf = avpkt->data; int i, ret, buf_size = avpkt->size; uint32_t version, header_size, vclass, ncolors; uint32_t xoffset, be, bpp, lsize, rsize; uint32_t pixformat, pixdepth, bunit, bitorder, bpad; uint32_t rgb[3]; uint8_t *ptr; GetByteContext gb; if (buf_size < XWD_HEADER_SIZE) return AVERROR_INVALIDDATA; bytestream2_init(&gb, buf, buf_size); header_size = bytestream2_get_be32u(&gb); version = bytestream2_get_be32u(&gb); if (version != XWD_VERSION) { av_log(avctx, AV_LOG_ERROR, "unsupported version\n"); return AVERROR_INVALIDDATA; } if (buf_size < header_size || header_size < XWD_HEADER_SIZE) { av_log(avctx, AV_LOG_ERROR, "invalid header size\n"); return AVERROR_INVALIDDATA; } pixformat = bytestream2_get_be32u(&gb); pixdepth = bytestream2_get_be32u(&gb); avctx->width = bytestream2_get_be32u(&gb); avctx->height = bytestream2_get_be32u(&gb); xoffset = bytestream2_get_be32u(&gb); be = bytestream2_get_be32u(&gb); bunit = bytestream2_get_be32u(&gb); bitorder = bytestream2_get_be32u(&gb); bpad = bytestream2_get_be32u(&gb); bpp = bytestream2_get_be32u(&gb); lsize = bytestream2_get_be32u(&gb); vclass = bytestream2_get_be32u(&gb); rgb[0] = bytestream2_get_be32u(&gb); rgb[1] = bytestream2_get_be32u(&gb); rgb[2] = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, 8); ncolors = bytestream2_get_be32u(&gb); bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20)); av_log(avctx, AV_LOG_DEBUG, "pixformat %"PRIu32", pixdepth %"PRIu32", bunit %"PRIu32", bitorder %"PRIu32", bpad %"PRIu32"\n", pixformat, pixdepth, bunit, bitorder, bpad); av_log(avctx, AV_LOG_DEBUG, "vclass %"PRIu32", ncolors %"PRIu32", bpp %"PRIu32", be %"PRIu32", lsize %"PRIu32", xoffset %"PRIu32"\n", vclass, ncolors, bpp, be, lsize, xoffset); av_log(avctx, AV_LOG_DEBUG, "red %0"PRIx32", green %0"PRIx32", blue %0"PRIx32"\n", rgb[0], rgb[1], rgb[2]); if (pixformat > XWD_Z_PIXMAP) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap format\n"); return AVERROR_INVALIDDATA; } if (pixdepth == 0 || pixdepth > 32) { av_log(avctx, AV_LOG_ERROR, "invalid pixmap depth\n"); return AVERROR_INVALIDDATA; } if (xoffset) { avpriv_request_sample(avctx, "xoffset %"PRIu32"", xoffset); return AVERROR_PATCHWELCOME; } if (be > 1) { av_log(avctx, AV_LOG_ERROR, "invalid byte order\n"); return AVERROR_INVALIDDATA; } if (bitorder > 1) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap bit order\n"); return AVERROR_INVALIDDATA; } if (bunit != 8 && bunit != 16 && bunit != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap unit\n"); return AVERROR_INVALIDDATA; } if (bpad != 8 && bpad != 16 && bpad != 32) { av_log(avctx, AV_LOG_ERROR, "invalid bitmap scan-line pad\n"); return AVERROR_INVALIDDATA; } if (bpp == 0 || bpp > 32) { av_log(avctx, AV_LOG_ERROR, "invalid bits per pixel\n"); return AVERROR_INVALIDDATA; } if (ncolors > 256) { av_log(avctx, AV_LOG_ERROR, "invalid number of entries in colormap\n"); return AVERROR_INVALIDDATA; } if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0) return ret; rsize = FFALIGN(avctx->width * bpp, bpad) / 8; if (lsize < rsize) { av_log(avctx, AV_LOG_ERROR, "invalid bytes per scan-line\n"); return AVERROR_INVALIDDATA; } if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) { av_log(avctx, AV_LOG_ERROR, "input buffer too small\n"); return AVERROR_INVALIDDATA; } if (pixformat != XWD_Z_PIXMAP) { avpriv_report_missing_feature(avctx, "Pixmap format %"PRIu32, pixformat); return AVERROR_PATCHWELCOME; } avctx->pix_fmt = AV_PIX_FMT_NONE; switch (vclass) { case XWD_STATIC_GRAY: case XWD_GRAY_SCALE: if (bpp != 1 && bpp != 8) return AVERROR_INVALIDDATA; if (bpp == 1 && pixdepth == 1) { avctx->pix_fmt = AV_PIX_FMT_MONOWHITE; } else if (bpp == 8 && pixdepth == 8) { avctx->pix_fmt = AV_PIX_FMT_GRAY8; } break; case XWD_STATIC_COLOR: case XWD_PSEUDO_COLOR: if (bpp == 8) avctx->pix_fmt = AV_PIX_FMT_PAL8; break; case XWD_TRUE_COLOR: case XWD_DIRECT_COLOR: if (bpp != 16 && bpp != 24 && bpp != 32) return AVERROR_INVALIDDATA; if (bpp == 16 && pixdepth == 15) { if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE; else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00) avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE; } else if (bpp == 16 && pixdepth == 16) { if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F) avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE; else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800) avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE; } else if (bpp == 24) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24; } else if (bpp == 32) { if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF) avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA; else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000) avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA; } bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE); break; default: av_log(avctx, AV_LOG_ERROR, "invalid visual class\n"); return AVERROR_INVALIDDATA; } if (avctx->pix_fmt == AV_PIX_FMT_NONE) { avpriv_request_sample(avctx, "Unknown file: bpp %"PRIu32", pixdepth %"PRIu32", vclass %"PRIu32"", bpp, pixdepth, vclass); return AVERROR_PATCHWELCOME; } if ((ret = ff_get_buffer(avctx, p, 0)) < 0) return ret; p->key_frame = 1; p->pict_type = AV_PICTURE_TYPE_I; if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { uint32_t *dst = (uint32_t *)p->data[1]; uint8_t red, green, blue; for (i = 0; i < ncolors; i++) { bytestream2_skipu(&gb, 4); // skip colormap entry number red = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); green = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 1); blue = bytestream2_get_byteu(&gb); bytestream2_skipu(&gb, 3); // skip bitmask flag and padding dst[i] = red << 16 | green << 8 | blue; } } ptr = p->data[0]; for (i = 0; i < avctx->height; i++) { bytestream2_get_bufferu(&gb, ptr, rsize); bytestream2_skipu(&gb, lsize - rsize); ptr += p->linesize[0]; } *got_frame = 1; return buf_size; }
168,075
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: __imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax) { ImlibUpdate *nu = NULL, *uu; struct _tile *t; int tw, th, x, y, i; int *gaps = NULL; /* if theres no rects to process.. return NULL */ if (!u) return NULL; tw = w >> TB; if (w & TM) tw++; th = h >> TB; if (h & TM) th++; t = malloc(tw * th * sizeof(struct _tile)); /* fill in tiles to be all not used */ for (i = 0, y = 0; y < th; y++) { for (x = 0; x < tw; x++) t[i++].used = T_UNUSED; } /* fill in all tiles */ for (uu = u; uu; uu = uu->next) { CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h); for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++) { for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++) T(x, y).used = T_USED; } } /* scan each line - if > hgapmax gaps between tiles, then fill smallest */ gaps = malloc(tw * sizeof(int)); for (y = 0; y < th; y++) { int hgaps = 0, start = -1, min; char have = 1, gap = 0; for (x = 0; x < tw; x++) gaps[x] = 0; for (x = 0; x < tw; x++) { if ((have) && (T(x, y).used == T_UNUSED)) { start = x; gap = 1; have = 0; } else if ((!have) && (gap) && (T(x, y).used & T_USED)) { gap = 0; hgaps++; have = 1; gaps[start] = x - start; } else if (T(x, y).used & T_USED) have = 1; } while (hgaps > hgapmax) { start = -1; min = tw; for (x = 0; x < tw; x++) { if ((gaps[x] > 0) && (gaps[x] < min)) { start = x; min = gaps[x]; } } if (start >= 0) { gaps[start] = 0; for (x = start; T(x, y).used == T_UNUSED; T(x++, y).used = T_USED); hgaps--; } } } free(gaps); /* coalesce tiles into larger blocks and make new rect list */ for (y = 0; y < th; y++) { for (x = 0; x < tw; x++) { if (T(x, y).used & T_USED) { int xx, yy, ww, hh, ok, xww; for (xx = x + 1, ww = 1; (T(xx, y).used & T_USED) && (xx < tw); xx++, ww++); xww = x + ww; for (yy = y + 1, hh = 1, ok = 1; (yy < th) && (ok); yy++, hh++) { for (xx = x; xx < xww; xx++) { if (!(T(xx, yy).used & T_USED)) { ok = 0; hh--; break; } } } for (yy = y; yy < (y + hh); yy++) { for (xx = x; xx < xww; xx++) T(xx, yy).used = T_UNUSED; } nu = __imlib_AddUpdate(nu, (x << TB), (y << TB), (ww << TB), (hh << TB)); } } } free(t); __imlib_FreeUpdates(u); return nu; } Commit Message: CWE ID: CWE-119
__imlib_MergeUpdate(ImlibUpdate * u, int w, int h, int hgapmax) { ImlibUpdate *nu = NULL, *uu; struct _tile *t; int tw, th, x, y, i; int *gaps = NULL; /* if theres no rects to process.. return NULL */ if (!u) return NULL; tw = w >> TB; if (w & TM) tw++; th = h >> TB; if (h & TM) th++; t = malloc(tw * th * sizeof(struct _tile)); /* fill in tiles to be all not used */ for (i = 0, y = 0; y < th; y++) { for (x = 0; x < tw; x++) t[i++].used = T_UNUSED; } /* fill in all tiles */ for (uu = u; uu; uu = uu->next) { CLIP(uu->x, uu->y, uu->w, uu->h, 0, 0, w, h); for (y = uu->y >> TB; y <= ((uu->y + uu->h - 1) >> TB); y++) { for (x = uu->x >> TB; x <= ((uu->x + uu->w - 1) >> TB); x++) T(x, y).used = T_USED; } } /* scan each line - if > hgapmax gaps between tiles, then fill smallest */ gaps = malloc(tw * sizeof(int)); for (y = 0; y < th; y++) { int hgaps = 0, start = -1, min; char have = 1, gap = 0; for (x = 0; x < tw; x++) gaps[x] = 0; for (x = 0; x < tw; x++) { if ((have) && (T(x, y).used == T_UNUSED)) { start = x; gap = 1; have = 0; } else if ((!have) && (gap) && (T(x, y).used & T_USED)) { gap = 0; hgaps++; have = 1; gaps[start] = x - start; } else if (T(x, y).used & T_USED) have = 1; } while (hgaps > hgapmax) { start = -1; min = tw; for (x = 0; x < tw; x++) { if ((gaps[x] > 0) && (gaps[x] < min)) { start = x; min = gaps[x]; } } if (start >= 0) { gaps[start] = 0; for (x = start; T(x, y).used == T_UNUSED; T(x++, y).used = T_USED); hgaps--; } } } free(gaps); /* coalesce tiles into larger blocks and make new rect list */ for (y = 0; y < th; y++) { for (x = 0; x < tw; x++) { if (T(x, y).used & T_USED) { int xx, yy, ww, hh, ok, xww; for (xx = x + 1, ww = 1; (xx < tw) && (T(xx, y).used & T_USED); xx++, ww++); xww = x + ww; for (yy = y + 1, hh = 1, ok = 1; (yy < th) && (ok); yy++, hh++) { for (xx = x; xx < xww; xx++) { if (!(T(xx, yy).used & T_USED)) { ok = 0; hh--; break; } } } for (yy = y; yy < (y + hh); yy++) { for (xx = x; xx < xww; xx++) T(xx, yy).used = T_UNUSED; } nu = __imlib_AddUpdate(nu, (x << TB), (y << TB), (ww << TB), (hh << TB)); } } } free(t); __imlib_FreeUpdates(u); return nu; }
165,080
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: ContextualSearchFieldTrial::ContextualSearchFieldTrial() : is_resolver_url_prefix_cached_(false), is_surrounding_size_cached_(false), surrounding_size_(0), is_icing_surrounding_size_cached_(false), icing_surrounding_size_(0), is_send_base_page_url_disabled_cached_(false), is_send_base_page_url_disabled_(false), is_decode_mentions_disabled_cached_(false), is_decode_mentions_disabled_(false), is_now_on_tap_bar_integration_enabled_cached_(false), is_now_on_tap_bar_integration_enabled_(false) {} Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID:
ContextualSearchFieldTrial::ContextualSearchFieldTrial() : is_resolver_url_prefix_cached_(false), is_surrounding_size_cached_(false), surrounding_size_(0), is_icing_surrounding_size_cached_(false), icing_surrounding_size_(0), is_send_base_page_url_disabled_cached_(false), is_send_base_page_url_disabled_(false), is_decode_mentions_disabled_cached_(false), is_decode_mentions_disabled_(false),
171,643
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: void GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() { request_.reset(new UrlFetcher( GURL(provider_info_.user_info_url), UrlFetcher::GET)); request_->SetRequestContext(request_context_getter_); request_->SetHeader("Authorization", "Bearer " + access_token_); request_->Start( base::Bind(&GaiaOAuthClient::Core::OnUserInfoFetchComplete, this)); } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void GaiaOAuthClient::Core::FetchUserInfoAndInvokeCallback() { request_.reset(net::URLFetcher::Create( GURL(provider_info_.user_info_url), net::URLFetcher::GET, this)); request_->SetRequestContext(request_context_getter_); request_->AddExtraRequestHeader("Authorization: Bearer " + access_token_); url_fetcher_type_ = URL_FETCHER_GET_USER_INFO; request_->Start(); }
170,806
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Display::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) { // ChapterString ID status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) { // ChapterLanguage ID status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) { // ChapterCountry ID status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long Chapters::Display::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x05) { // ChapterString ID status = UnserializeString(pReader, pos, size, m_string); if (status) return status; } else if (id == 0x037C) { // ChapterLanguage ID status = UnserializeString(pReader, pos, size, m_language); if (status) return status; } else if (id == 0x037E) { // ChapterCountry ID status = UnserializeString(pReader, pos, size, m_country); if (status) return status; } pos += size; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; } Tags::Tags(Segment* pSegment, long long payload_start, long long payload_size, long long element_start, long long element_size) : m_pSegment(pSegment), m_start(payload_start), m_size(payload_size), m_element_start(element_start), m_element_size(element_size), m_tags(NULL), m_tags_size(0), m_tags_count(0) {} Tags::~Tags() { while (m_tags_count > 0) { Tag& t = m_tags[--m_tags_count]; t.Clear(); } delete[] m_tags; } long Tags::Parse() { IMkvReader* const pReader = m_pSegment->m_pReader; long long pos = m_start; // payload start const long long stop = pos + m_size; // payload stop while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) return status; if (size == 0) // 0 length tag, read another continue; if (id == 0x3373) { // Tag ID status = ParseTag(pos, size); if (status < 0) return status; } pos += size; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; } int Tags::GetTagCount() const { return m_tags_count; } const Tags::Tag* Tags::GetTag(int idx) const { if (idx < 0) return NULL; if (idx >= m_tags_count) return NULL; return m_tags + idx; } bool Tags::ExpandTagsArray() { if (m_tags_size > m_tags_count) return true; // nothing else to do const int size = (m_tags_size == 0) ? 1 : 2 * m_tags_size; Tag* const tags = new (std::nothrow) Tag[size]; if (tags == NULL) return false; for (int idx = 0; idx < m_tags_count; ++idx) { m_tags[idx].ShallowCopy(tags[idx]); } delete[] m_tags; m_tags = tags; m_tags_size = size; return true; } long Tags::ParseTag(long long pos, long long size) { if (!ExpandTagsArray()) return -1; Tag& t = m_tags[m_tags_count++]; t.Init(); return t.Parse(m_pSegment->m_pReader, pos, size); } Tags::Tag::Tag() {} Tags::Tag::~Tag() {} int Tags::Tag::GetSimpleTagCount() const { return m_simple_tags_count; } const Tags::SimpleTag* Tags::Tag::GetSimpleTag(int index) const { if (index < 0) return NULL; if (index >= m_simple_tags_count) return NULL; return m_simple_tags + index; } void Tags::Tag::Init() { m_simple_tags = NULL; m_simple_tags_size = 0; m_simple_tags_count = 0; } void Tags::Tag::ShallowCopy(Tag& rhs) const { rhs.m_simple_tags = m_simple_tags; rhs.m_simple_tags_size = m_simple_tags_size; rhs.m_simple_tags_count = m_simple_tags_count; } void Tags::Tag::Clear() { while (m_simple_tags_count > 0) { SimpleTag& d = m_simple_tags[--m_simple_tags_count]; d.Clear(); } delete[] m_simple_tags; m_simple_tags = NULL; m_simple_tags_size = 0; } long Tags::Tag::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) return status; if (size == 0) // 0 length tag, read another continue; if (id == 0x27C8) { // SimpleTag ID status = ParseSimpleTag(pReader, pos, size); if (status < 0) return status; } pos += size; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; } long Tags::Tag::ParseSimpleTag(IMkvReader* pReader, long long pos, long long size) { if (!ExpandSimpleTagsArray()) return -1; SimpleTag& st = m_simple_tags[m_simple_tags_count++]; st.Init(); return st.Parse(pReader, pos, size); } bool Tags::Tag::ExpandSimpleTagsArray() { if (m_simple_tags_size > m_simple_tags_count) return true; // nothing else to do const int size = (m_simple_tags_size == 0) ? 1 : 2 * m_simple_tags_size; SimpleTag* const displays = new (std::nothrow) SimpleTag[size]; if (displays == NULL) return false; for (int idx = 0; idx < m_simple_tags_count; ++idx) { m_simple_tags[idx].ShallowCopy(displays[idx]); } delete[] m_simple_tags; m_simple_tags = displays; m_simple_tags_size = size; return true; } Tags::SimpleTag::SimpleTag() {} Tags::SimpleTag::~SimpleTag() {} const char* Tags::SimpleTag::GetTagName() const { return m_tag_name; } const char* Tags::SimpleTag::GetTagString() const { return m_tag_string; } void Tags::SimpleTag::Init() { m_tag_name = NULL; m_tag_string = NULL; } void Tags::SimpleTag::ShallowCopy(SimpleTag& rhs) const { rhs.m_tag_name = m_tag_name; rhs.m_tag_string = m_tag_string; } void Tags::SimpleTag::Clear() { delete[] m_tag_name; m_tag_name = NULL; delete[] m_tag_string; m_tag_string = NULL; } long Tags::SimpleTag::Parse(IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x5A3) { // TagName ID status = UnserializeString(pReader, pos, size, m_tag_name); if (status) return status; } else if (id == 0x487) { // TagString ID status = UnserializeString(pReader, pos, size, m_tag_string); if (status) return status; } pos += size; if (pos > stop) return E_FILE_FORMAT_INVALID; } if (pos != stop) return E_FILE_FORMAT_INVALID; return 0; }
173,841
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); NTSTATUS ntStatus; switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_DRIVER_VERSION: case TC_IOCTL_LEGACY_GET_DRIVER_VERSION: if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput)) { LONG tmp = VERSION_NUM; memcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4); Irp->IoStatus.Information = sizeof (LONG); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_GET_DEVICE_REFCOUNT: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { *(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { LONG deviceObjectCount = 0; *(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled; if (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1) *(int *) Irp->AssociatedIrp.SystemBuffer = TRUE; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_IS_ANY_VOLUME_MOUNTED: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { int drive; *(int *) Irp->AssociatedIrp.SystemBuffer = 0; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { if (GetVirtualVolumeDeviceObject (drive)) { *(int *) Irp->AssociatedIrp.SystemBuffer = 1; break; } } if (IsBootDriveMounted()) *(int *) Irp->AssociatedIrp.SystemBuffer = 1; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_OPEN_TEST: { OPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE NtFileHandle; UNICODE_STRING FullFileName; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; ACCESS_MASK access = FILE_READ_ATTRIBUTES; if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput)) break; EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName)); RtlInitUnicodeString (&FullFileName, opentest->wszFileName); InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs) access |= FILE_READ_DATA; ntStatus = ZwCreateFile (&NtFileHandle, SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (NT_SUCCESS (ntStatus)) { opentest->TCBootLoaderDetected = FALSE; opentest->FilesystemDetected = FALSE; memset (opentest->VolumeIDComputed, 0, sizeof (opentest->VolumeIDComputed)); memset (opentest->volumeIDs, 0, sizeof (opentest->volumeIDs)); if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs) { byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE); if (!readBuffer) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; } else { if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem) { offset.QuadPart = 0; ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &offset, NULL); if (NT_SUCCESS (ntStatus)) { size_t i; if (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS) { for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i) { if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) { opentest->TCBootLoaderDetected = TRUE; break; } } } if (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64)) { switch (BE64 (*(uint64 *) readBuffer)) { case 0xEB52904E54465320ULL: // NTFS case 0xEB3C904D53444F53ULL: // FAT16/FAT32 case 0xEB58904D53444F53ULL: // FAT32 case 0xEB76904558464154ULL: // exFAT case 0x0000005265465300ULL: // ReFS case 0xEB58906D6B66732EULL: // FAT32 mkfs.fat case 0xEB58906D6B646F73ULL: // FAT32 mkfs.vfat/mkdosfs case 0xEB3C906D6B66732EULL: // FAT16/FAT12 mkfs.fat case 0xEB3C906D6B646F73ULL: // FAT16/FAT12 mkfs.vfat/mkdosfs opentest->FilesystemDetected = TRUE; break; case 0x0000000000000000ULL: if (IsAllZeroes (readBuffer + 8, TC_VOLUME_HEADER_EFFECTIVE_SIZE - 8)) opentest->FilesystemDetected = TRUE; break; } } } } if (opentest->bComputeVolumeIDs && (!opentest->DetectFilesystem || !opentest->FilesystemDetected)) { int volumeType; for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++) { /* Read the volume header */ switch (volumeType) { case TC_VOLUME_TYPE_NORMAL: offset.QuadPart = TC_VOLUME_HEADER_OFFSET; break; case TC_VOLUME_TYPE_HIDDEN: offset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; break; } ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &offset, NULL); if (NT_SUCCESS (ntStatus)) { /* compute the ID of this volume: SHA-256 of the effective header */ sha256 (opentest->volumeIDs[volumeType], readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); opentest->VolumeIDComputed[volumeType] = TRUE; } } } TCfree (readBuffer); } } ZwClose (NtFileHandle); Dump ("Open test on file %ls success.\n", opentest->wszFileName); } else { #if 0 Dump ("Open test on file %ls failed NTSTATUS 0x%08x\n", opentest->wszFileName, ntStatus); #endif } Irp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0; Irp->IoStatus.Status = ntStatus; } break; case TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG: { GetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE NtFileHandle; UNICODE_STRING FullFileName; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; byte readBuffer [TC_SECTOR_SIZE_BIOS]; if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput)) break; EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath)); RtlInitUnicodeString (&FullFileName, request->DevicePath); InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); ntStatus = ZwCreateFile (&NtFileHandle, SYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0); if (NT_SUCCESS (ntStatus)) { offset.QuadPart = 0; // MBR ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, sizeof(readBuffer), &offset, NULL); if (NT_SUCCESS (ntStatus)) { size_t i; request->DriveIsDynamic = FALSE; if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa) { int i; for (i = 0; i < 4; ++i) { if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM) { request->DriveIsDynamic = TRUE; break; } } } request->BootLoaderVersion = 0; request->Configuration = 0; request->UserConfiguration = 0; request->CustomUserMessage[0] = 0; for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i) { if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) { request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET)); request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET]; if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM) { request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); } break; } } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*request); } else { Irp->IoStatus.Status = ntStatus; Irp->IoStatus.Information = 0; } ZwClose (NtFileHandle); } else { Irp->IoStatus.Status = ntStatus; Irp->IoStatus.Information = 0; } } break; case TC_IOCTL_WIPE_PASSWORD_CACHE: WipeCache (); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: Irp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case TC_IOCTL_SET_PORTABLE_MODE_STATUS: if (!UserCanAccessDriveDevice()) { Irp->IoStatus.Status = STATUS_ACCESS_DENIED; Irp->IoStatus.Information = 0; } else { PortableMode = TRUE; Dump ("Setting portable mode\n"); } break; case TC_IOCTL_GET_PORTABLE_MODE_STATUS: Irp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY; Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_MOUNTED_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput)) { MOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice; int drive; list->ulMountedDrives = 0; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { PEXTENSION ListExtension; ListDevice = GetVirtualVolumeDeviceObject (drive); if (!ListDevice) continue; ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) { list->ulMountedDrives |= (1 << ListExtension->nDosDriveNo); RtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume); RtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel); memcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE); list->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength; list->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea; if (ListExtension->cryptoInfo->hiddenVolume) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN; // Hidden volume else if (ListExtension->cryptoInfo->bHiddenVolProtectionAction) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED; // Normal/outer volume (hidden volume protected AND write already prevented) else if (ListExtension->cryptoInfo->bProtectHiddenVolume) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected) else list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode; } } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT); } break; case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput)) { memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); *(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength; } break; case TC_IOCTL_GET_VOLUME_PROPERTIES: if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput)) { VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo); Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; if (ListDevice) { PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) { prop->uniqueId = ListExtension->UniqueVolumeId; RtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume); RtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel); memcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE); prop->bDriverSetLabel = ListExtension->bDriverSetLabel; prop->diskLength = ListExtension->DiskLength; prop->ea = ListExtension->cryptoInfo->ea; prop->mode = ListExtension->cryptoInfo->mode; prop->pkcs5 = ListExtension->cryptoInfo->pkcs5; prop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations; prop->volumePim = ListExtension->cryptoInfo->volumePim; #if 0 prop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time; prop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time; #endif prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags; prop->readOnly = ListExtension->bReadOnly; prop->removable = ListExtension->bRemovable; prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope; prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume; if (ListExtension->cryptoInfo->bProtectHiddenVolume) prop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE; else prop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE; prop->totalBytesRead = ListExtension->Queue.TotalBytesRead; prop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten; prop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT); } } } break; case TC_IOCTL_GET_RESOLVED_SYMLINK: if (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput)) { RESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; EnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName)); ntStatus = SymbolicLinkToTarget (resolve->symLinkName, resolve->targetName, sizeof (resolve->targetName)); Irp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case TC_IOCTL_GET_DRIVE_PARTITION_INFO: if (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput)) { DISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { PARTITION_INFORMATION_EX pi; NTSTATUS ntStatus; EnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName)); ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi)); if (NT_SUCCESS(ntStatus)) { memset (&info->partInfo, 0, sizeof (info->partInfo)); info->partInfo.PartitionLength = pi.PartitionLength; info->partInfo.PartitionNumber = pi.PartitionNumber; info->partInfo.StartingOffset = pi.StartingOffset; if (pi.PartitionStyle == PARTITION_STYLE_MBR) { info->partInfo.PartitionType = pi.Mbr.PartitionType; info->partInfo.BootIndicator = pi.Mbr.BootIndicator; } info->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT; } else { ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo)); info->IsGPT = FALSE; } if (!NT_SUCCESS (ntStatus)) { GET_LENGTH_INFORMATION lengthInfo; ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo)); if (NT_SUCCESS (ntStatus)) { memset (&info->partInfo, 0, sizeof (info->partInfo)); info->partInfo.PartitionLength = lengthInfo.Length; } } info->IsDynamic = FALSE; if (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6) { # define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS) if (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic)))) info->IsDynamic = FALSE; } Irp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case TC_IOCTL_GET_DRIVE_GEOMETRY: if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput)) { DISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &g->diskGeometry, sizeof (g->diskGeometry)); Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case VC_IOCTL_GET_DRIVE_GEOMETRY_EX: if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_EX_STRUCT), ValidateInputOutput)) { DISK_GEOMETRY_EX_STRUCT *g = (DISK_GEOMETRY_EX_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; PVOID buffer = TCalloc (256); // enough for DISK_GEOMETRY_EX and padded data if (buffer) { EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY_EX on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, buffer, 256); if (NT_SUCCESS(ntStatus)) { PDISK_GEOMETRY_EX pGeo = (PDISK_GEOMETRY_EX) buffer; memcpy (&g->diskGeometry, &pGeo->Geometry, sizeof (DISK_GEOMETRY)); g->DiskSize.QuadPart = pGeo->DiskSize.QuadPart; } else { DISK_GEOMETRY dg = {0}; Dump ("Failed. Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &dg, sizeof (dg)); if (NT_SUCCESS(ntStatus)) { memcpy (&g->diskGeometry, &dg, sizeof (DISK_GEOMETRY)); g->DiskSize.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector; if (OsMajorVersion >= 6) { STORAGE_READ_CAPACITY storage = {0}; NTSTATUS lStatus; storage.Version = sizeof (STORAGE_READ_CAPACITY); Dump ("Calling IOCTL_STORAGE_READ_CAPACITY on %ls\n", g->deviceName); lStatus = TCDeviceIoControl (g->deviceName, IOCTL_STORAGE_READ_CAPACITY, NULL, 0, &storage, sizeof (STORAGE_READ_CAPACITY)); if ( NT_SUCCESS(lStatus) && (storage.Size == sizeof (STORAGE_READ_CAPACITY)) ) { g->DiskSize.QuadPart = storage.DiskLength.QuadPart; } } } } TCfree (buffer); Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX_STRUCT); Irp->IoStatus.Status = ntStatus; } else { Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; Irp->IoStatus.Information = 0; } } } break; case TC_IOCTL_PROBE_REAL_DRIVE_SIZE: if (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput)) { ProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer; NTSTATUS status; UNICODE_STRING name; PFILE_OBJECT fileObject; PDEVICE_OBJECT deviceObject; EnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName)); RtlInitUnicodeString (&name, request->DeviceName); status = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); if (!NT_SUCCESS (status)) { Irp->IoStatus.Information = 0; Irp->IoStatus.Status = status; break; } status = ProbeRealDriveSize (deviceObject, &request->RealDriveSize); ObDereferenceObject (fileObject); if (status == STATUS_TIMEOUT) { request->TimeOut = TRUE; Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); Irp->IoStatus.Status = STATUS_SUCCESS; } else if (!NT_SUCCESS (status)) { Irp->IoStatus.Information = 0; Irp->IoStatus.Status = status; } else { request->TimeOut = FALSE; Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); Irp->IoStatus.Status = status; } } break; case TC_IOCTL_MOUNT_VOLUME: if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput)) { MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID || mount->VolumePim < -1 || mount->VolumePim == INT_MAX || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID || (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE) ) { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; break; } EnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume)); EnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel)); Irp->IoStatus.Information = sizeof (MOUNT_STRUCT); Irp->IoStatus.Status = MountDevice (DeviceObject, mount); burn (&mount->VolumePassword, sizeof (mount->VolumePassword)); burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword)); burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf)); burn (&mount->VolumePim, sizeof (mount->VolumePim)); burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode)); burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf)); burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim)); } break; case TC_IOCTL_DISMOUNT_VOLUME: if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo); unmount->nReturnCode = ERR_DRIVE_NOT_FOUND; if (ListDevice) { PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) unmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles); } Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_DISMOUNT_ALL_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles); Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_BOOT_ENCRYPTION_SETUP: Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP: Irp->IoStatus.Status = AbortBootEncryptionSetup(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: GetBootEncryptionStatus (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT: Irp->IoStatus.Information = 0; Irp->IoStatus.Status = GetSetupResult(); break; case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: GetBootDriveVolumeProperties (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_LOADER_VERSION: GetBootLoaderVersion (Irp, irpSp); break; case TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER: ReopenBootVolumeHeader (Irp, irpSp); break; case VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT: GetBootLoaderFingerprint (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME: GetBootEncryptionAlgorithmName (Irp, irpSp); break; case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { *(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_START_DECOY_SYSTEM_WIPE: Irp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE: Irp->IoStatus.Status = AbortDecoySystemWipe(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT: Irp->IoStatus.Status = GetDecoySystemWipeResult(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: GetDecoySystemWipeStatus (Irp, irpSp); break; case TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR: Irp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_WARNING_FLAGS: if (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput)) { GetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer; flags->PagingFileCreationPrevented = PagingFileCreationPrevented; PagingFileCreationPrevented = FALSE; flags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty; SystemFavoriteVolumeDirty = FALSE; Irp->IoStatus.Information = sizeof (GetWarningFlagsRequest); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY: if (UserCanAccessDriveDevice()) { SystemFavoriteVolumeDirty = TRUE; Irp->IoStatus.Status = STATUS_SUCCESS; } else Irp->IoStatus.Status = STATUS_ACCESS_DENIED; Irp->IoStatus.Information = 0; break; case TC_IOCTL_REREAD_DRIVER_CONFIG: Irp->IoStatus.Status = ReadRegistryConfigFlags (FALSE); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG: if ( (ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput)) && (Irp->RequestorMode == KernelMode) ) { GetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer; request->BootDriveFilterExtension = GetBootDriveFilterExtension(); if (IsBootDriveMounted() && request->BootDriveFilterExtension) { request->HwEncryptionEnabled = IsHwEncryptionEnabled(); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*request); } else { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; } } break; default: return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); } #if defined(DEBUG) || defined(DEBUG_TRACE) if (!NT_SUCCESS (Irp->IoStatus.Status)) { switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_MOUNTED_VOLUMES: case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: case TC_IOCTL_GET_PORTABLE_MODE_STATUS: case TC_IOCTL_SET_PORTABLE_MODE_STATUS: case TC_IOCTL_OPEN_TEST: case TC_IOCTL_GET_RESOLVED_SYMLINK: case TC_IOCTL_GET_DRIVE_PARTITION_INFO: case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: break; default: Dump ("IOCTL error 0x%08x\n", Irp->IoStatus.Status); } } #endif return TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); } Commit Message: Windows: fix low severity vulnerability in driver that allowed reading 3 bytes of kernel stack memory (with a rare possibility of 25 additional bytes). Reported by Tim Harrison. CWE ID: CWE-119
NTSTATUS ProcessMainDeviceControlIrp (PDEVICE_OBJECT DeviceObject, PEXTENSION Extension, PIRP Irp) { PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation (Irp); NTSTATUS ntStatus; switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_DRIVER_VERSION: case TC_IOCTL_LEGACY_GET_DRIVER_VERSION: if (ValidateIOBufferSize (Irp, sizeof (LONG), ValidateOutput)) { LONG tmp = VERSION_NUM; memcpy (Irp->AssociatedIrp.SystemBuffer, &tmp, 4); Irp->IoStatus.Information = sizeof (LONG); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_GET_DEVICE_REFCOUNT: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { *(int *) Irp->AssociatedIrp.SystemBuffer = DeviceObject->ReferenceCount; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_IS_DRIVER_UNLOAD_DISABLED: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { LONG deviceObjectCount = 0; *(int *) Irp->AssociatedIrp.SystemBuffer = DriverUnloadDisabled; if (IoEnumerateDeviceObjectList (TCDriverObject, NULL, 0, &deviceObjectCount) == STATUS_BUFFER_TOO_SMALL && deviceObjectCount > 1) *(int *) Irp->AssociatedIrp.SystemBuffer = TRUE; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_IS_ANY_VOLUME_MOUNTED: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { int drive; *(int *) Irp->AssociatedIrp.SystemBuffer = 0; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { if (GetVirtualVolumeDeviceObject (drive)) { *(int *) Irp->AssociatedIrp.SystemBuffer = 1; break; } } if (IsBootDriveMounted()) *(int *) Irp->AssociatedIrp.SystemBuffer = 1; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_OPEN_TEST: { OPEN_TEST_STRUCT *opentest = (OPEN_TEST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE NtFileHandle; UNICODE_STRING FullFileName; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; ACCESS_MASK access = FILE_READ_ATTRIBUTES; if (!ValidateIOBufferSize (Irp, sizeof (OPEN_TEST_STRUCT), ValidateInputOutput)) break; EnsureNullTerminatedString (opentest->wszFileName, sizeof (opentest->wszFileName)); RtlInitUnicodeString (&FullFileName, opentest->wszFileName); InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs) access |= FILE_READ_DATA; ntStatus = ZwCreateFile (&NtFileHandle, SYNCHRONIZE | access, &ObjectAttributes, &IoStatus, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if (NT_SUCCESS (ntStatus)) { opentest->TCBootLoaderDetected = FALSE; opentest->FilesystemDetected = FALSE; memset (opentest->VolumeIDComputed, 0, sizeof (opentest->VolumeIDComputed)); memset (opentest->volumeIDs, 0, sizeof (opentest->volumeIDs)); if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem || opentest->bComputeVolumeIDs) { byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE); if (!readBuffer) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; } else { if (opentest->bDetectTCBootLoader || opentest->DetectFilesystem) { offset.QuadPart = 0; ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &offset, NULL); if (NT_SUCCESS (ntStatus)) { size_t i; if (opentest->bDetectTCBootLoader && IoStatus.Information >= TC_SECTOR_SIZE_BIOS) { for (i = 0; i < TC_SECTOR_SIZE_BIOS - strlen (TC_APP_NAME); ++i) { if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) { opentest->TCBootLoaderDetected = TRUE; break; } } } if (opentest->DetectFilesystem && IoStatus.Information >= sizeof (int64)) { switch (BE64 (*(uint64 *) readBuffer)) { case 0xEB52904E54465320ULL: // NTFS case 0xEB3C904D53444F53ULL: // FAT16/FAT32 case 0xEB58904D53444F53ULL: // FAT32 case 0xEB76904558464154ULL: // exFAT case 0x0000005265465300ULL: // ReFS case 0xEB58906D6B66732EULL: // FAT32 mkfs.fat case 0xEB58906D6B646F73ULL: // FAT32 mkfs.vfat/mkdosfs case 0xEB3C906D6B66732EULL: // FAT16/FAT12 mkfs.fat case 0xEB3C906D6B646F73ULL: // FAT16/FAT12 mkfs.vfat/mkdosfs opentest->FilesystemDetected = TRUE; break; case 0x0000000000000000ULL: if (IsAllZeroes (readBuffer + 8, TC_VOLUME_HEADER_EFFECTIVE_SIZE - 8)) opentest->FilesystemDetected = TRUE; break; } } } } if (opentest->bComputeVolumeIDs && (!opentest->DetectFilesystem || !opentest->FilesystemDetected)) { int volumeType; for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++) { /* Read the volume header */ switch (volumeType) { case TC_VOLUME_TYPE_NORMAL: offset.QuadPart = TC_VOLUME_HEADER_OFFSET; break; case TC_VOLUME_TYPE_HIDDEN: offset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET; break; } ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &offset, NULL); if (NT_SUCCESS (ntStatus)) { /* compute the ID of this volume: SHA-256 of the effective header */ sha256 (opentest->volumeIDs[volumeType], readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE); opentest->VolumeIDComputed[volumeType] = TRUE; } } } TCfree (readBuffer); } } ZwClose (NtFileHandle); Dump ("Open test on file %ls success.\n", opentest->wszFileName); } else { #if 0 Dump ("Open test on file %ls failed NTSTATUS 0x%08x\n", opentest->wszFileName, ntStatus); #endif } Irp->IoStatus.Information = NT_SUCCESS (ntStatus) ? sizeof (OPEN_TEST_STRUCT) : 0; Irp->IoStatus.Status = ntStatus; } break; case TC_IOCTL_GET_SYSTEM_DRIVE_CONFIG: { GetSystemDriveConfigurationRequest *request = (GetSystemDriveConfigurationRequest *) Irp->AssociatedIrp.SystemBuffer; OBJECT_ATTRIBUTES ObjectAttributes; HANDLE NtFileHandle; UNICODE_STRING FullFileName; IO_STATUS_BLOCK IoStatus; LARGE_INTEGER offset; size_t devicePathLen = 0; if (!ValidateIOBufferSize (Irp, sizeof (GetSystemDriveConfigurationRequest), ValidateInputOutput)) break; // check that request->DevicePath has the expected format "\\Device\\HarddiskXXX\\Partition0" if ( !NT_SUCCESS (RtlUnalignedStringCchLengthW (request->DevicePath, TC_MAX_PATH, &devicePathLen)) || (devicePathLen < 28) // 28 is the length of "\\Device\\Harddisk0\\Partition0" which is the minimum || (devicePathLen > 30) // 30 is the length of "\\Device\\Harddisk255\\Partition0" which is the maximum || (memcmp (request->DevicePath, L"\\Device\\Harddisk", 16 * sizeof (WCHAR))) || (memcmp (&request->DevicePath[devicePathLen - 11], L"\\Partition0", 11 * sizeof (WCHAR))) ) { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; break; } EnsureNullTerminatedString (request->DevicePath, sizeof (request->DevicePath)); RtlInitUnicodeString (&FullFileName, request->DevicePath); InitializeObjectAttributes (&ObjectAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL); ntStatus = ZwCreateFile (&NtFileHandle, SYNCHRONIZE | GENERIC_READ, &ObjectAttributes, &IoStatus, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS, NULL, 0); if (NT_SUCCESS (ntStatus)) { byte *readBuffer = TCalloc (TC_MAX_VOLUME_SECTOR_SIZE); if (!readBuffer) { Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; Irp->IoStatus.Information = 0; } else { // Determine if the first sector contains a portion of the VeraCrypt Boot Loader offset.QuadPart = 0; // MBR ntStatus = ZwReadFile (NtFileHandle, NULL, NULL, NULL, &IoStatus, readBuffer, TC_MAX_VOLUME_SECTOR_SIZE, &offset, NULL); if (NT_SUCCESS (ntStatus)) { // check that we could read all needed data if (IoStatus.Information >= TC_SECTOR_SIZE_BIOS) { size_t i; // Check for dynamic drive request->DriveIsDynamic = FALSE; if (readBuffer[510] == 0x55 && readBuffer[511] == 0xaa) { int i; for (i = 0; i < 4; ++i) { if (readBuffer[446 + i * 16 + 4] == PARTITION_LDM) { request->DriveIsDynamic = TRUE; break; } } } request->BootLoaderVersion = 0; request->Configuration = 0; request->UserConfiguration = 0; request->CustomUserMessage[0] = 0; // Search for the string "VeraCrypt" for (i = 0; i < sizeof (readBuffer) - strlen (TC_APP_NAME); ++i) { if (memcmp (readBuffer + i, TC_APP_NAME, strlen (TC_APP_NAME)) == 0) { request->BootLoaderVersion = BE16 (*(uint16 *) (readBuffer + TC_BOOT_SECTOR_VERSION_OFFSET)); request->Configuration = readBuffer[TC_BOOT_SECTOR_CONFIG_OFFSET]; if (request->BootLoaderVersion != 0 && request->BootLoaderVersion <= VERSION_NUM) { request->UserConfiguration = readBuffer[TC_BOOT_SECTOR_USER_CONFIG_OFFSET]; memcpy (request->CustomUserMessage, readBuffer + TC_BOOT_SECTOR_USER_MESSAGE_OFFSET, TC_BOOT_SECTOR_USER_MESSAGE_MAX_LENGTH); } break; } } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*request); } else { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; } } else { Irp->IoStatus.Status = ntStatus; Irp->IoStatus.Information = 0; } TCfree (readBuffer); } ZwClose (NtFileHandle); } else { Irp->IoStatus.Status = ntStatus; Irp->IoStatus.Information = 0; } } break; case TC_IOCTL_WIPE_PASSWORD_CACHE: WipeCache (); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: Irp->IoStatus.Status = cacheEmpty ? STATUS_PIPE_EMPTY : STATUS_SUCCESS; Irp->IoStatus.Information = 0; break; case TC_IOCTL_SET_PORTABLE_MODE_STATUS: if (!UserCanAccessDriveDevice()) { Irp->IoStatus.Status = STATUS_ACCESS_DENIED; Irp->IoStatus.Information = 0; } else { PortableMode = TRUE; Dump ("Setting portable mode\n"); } break; case TC_IOCTL_GET_PORTABLE_MODE_STATUS: Irp->IoStatus.Status = PortableMode ? STATUS_SUCCESS : STATUS_PIPE_EMPTY; Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_MOUNTED_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (MOUNT_LIST_STRUCT), ValidateOutput)) { MOUNT_LIST_STRUCT *list = (MOUNT_LIST_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice; int drive; list->ulMountedDrives = 0; for (drive = MIN_MOUNTED_VOLUME_DRIVE_NUMBER; drive <= MAX_MOUNTED_VOLUME_DRIVE_NUMBER; ++drive) { PEXTENSION ListExtension; ListDevice = GetVirtualVolumeDeviceObject (drive); if (!ListDevice) continue; ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) { list->ulMountedDrives |= (1 << ListExtension->nDosDriveNo); RtlStringCbCopyW (list->wszVolume[ListExtension->nDosDriveNo], sizeof(list->wszVolume[ListExtension->nDosDriveNo]),ListExtension->wszVolume); RtlStringCbCopyW (list->wszLabel[ListExtension->nDosDriveNo], sizeof(list->wszLabel[ListExtension->nDosDriveNo]),ListExtension->wszLabel); memcpy (list->volumeID[ListExtension->nDosDriveNo], ListExtension->volumeID, VOLUME_ID_SIZE); list->diskLength[ListExtension->nDosDriveNo] = ListExtension->DiskLength; list->ea[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->ea; if (ListExtension->cryptoInfo->hiddenVolume) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_HIDDEN; // Hidden volume else if (ListExtension->cryptoInfo->bHiddenVolProtectionAction) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER_VOL_WRITE_PREVENTED; // Normal/outer volume (hidden volume protected AND write already prevented) else if (ListExtension->cryptoInfo->bProtectHiddenVolume) list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_OUTER; // Normal/outer volume (hidden volume protected) else list->volumeType[ListExtension->nDosDriveNo] = PROP_VOL_TYPE_NORMAL; // Normal volume list->truecryptMode[ListExtension->nDosDriveNo] = ListExtension->cryptoInfo->bTrueCryptMode; } } Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (MOUNT_LIST_STRUCT); } break; case TC_IOCTL_LEGACY_GET_MOUNTED_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (uint32), ValidateOutput)) { memset (Irp->AssociatedIrp.SystemBuffer, 0, irpSp->Parameters.DeviceIoControl.OutputBufferLength); *(uint32 *) Irp->AssociatedIrp.SystemBuffer = 0xffffFFFF; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = irpSp->Parameters.DeviceIoControl.OutputBufferLength; } break; case TC_IOCTL_GET_VOLUME_PROPERTIES: if (ValidateIOBufferSize (Irp, sizeof (VOLUME_PROPERTIES_STRUCT), ValidateInputOutput)) { VOLUME_PROPERTIES_STRUCT *prop = (VOLUME_PROPERTIES_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (prop->driveNo); Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; if (ListDevice) { PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) { prop->uniqueId = ListExtension->UniqueVolumeId; RtlStringCbCopyW (prop->wszVolume, sizeof(prop->wszVolume),ListExtension->wszVolume); RtlStringCbCopyW (prop->wszLabel, sizeof(prop->wszLabel),ListExtension->wszLabel); memcpy (prop->volumeID, ListExtension->volumeID, VOLUME_ID_SIZE); prop->bDriverSetLabel = ListExtension->bDriverSetLabel; prop->diskLength = ListExtension->DiskLength; prop->ea = ListExtension->cryptoInfo->ea; prop->mode = ListExtension->cryptoInfo->mode; prop->pkcs5 = ListExtension->cryptoInfo->pkcs5; prop->pkcs5Iterations = ListExtension->cryptoInfo->noIterations; prop->volumePim = ListExtension->cryptoInfo->volumePim; #if 0 prop->volumeCreationTime = ListExtension->cryptoInfo->volume_creation_time; prop->headerCreationTime = ListExtension->cryptoInfo->header_creation_time; #endif prop->volumeHeaderFlags = ListExtension->cryptoInfo->HeaderFlags; prop->readOnly = ListExtension->bReadOnly; prop->removable = ListExtension->bRemovable; prop->partitionInInactiveSysEncScope = ListExtension->PartitionInInactiveSysEncScope; prop->hiddenVolume = ListExtension->cryptoInfo->hiddenVolume; if (ListExtension->cryptoInfo->bProtectHiddenVolume) prop->hiddenVolProtection = ListExtension->cryptoInfo->bHiddenVolProtectionAction ? HIDVOL_PROT_STATUS_ACTION_TAKEN : HIDVOL_PROT_STATUS_ACTIVE; else prop->hiddenVolProtection = HIDVOL_PROT_STATUS_NONE; prop->totalBytesRead = ListExtension->Queue.TotalBytesRead; prop->totalBytesWritten = ListExtension->Queue.TotalBytesWritten; prop->volFormatVersion = ListExtension->cryptoInfo->LegacyVolume ? TC_VOLUME_FORMAT_VERSION_PRE_6_0 : TC_VOLUME_FORMAT_VERSION; Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (VOLUME_PROPERTIES_STRUCT); } } } break; case TC_IOCTL_GET_RESOLVED_SYMLINK: if (ValidateIOBufferSize (Irp, sizeof (RESOLVE_SYMLINK_STRUCT), ValidateInputOutput)) { RESOLVE_SYMLINK_STRUCT *resolve = (RESOLVE_SYMLINK_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; EnsureNullTerminatedString (resolve->symLinkName, sizeof (resolve->symLinkName)); ntStatus = SymbolicLinkToTarget (resolve->symLinkName, resolve->targetName, sizeof (resolve->targetName)); Irp->IoStatus.Information = sizeof (RESOLVE_SYMLINK_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case TC_IOCTL_GET_DRIVE_PARTITION_INFO: if (ValidateIOBufferSize (Irp, sizeof (DISK_PARTITION_INFO_STRUCT), ValidateInputOutput)) { DISK_PARTITION_INFO_STRUCT *info = (DISK_PARTITION_INFO_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { PARTITION_INFORMATION_EX pi; NTSTATUS ntStatus; EnsureNullTerminatedString (info->deviceName, sizeof (info->deviceName)); ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &pi, sizeof (pi)); if (NT_SUCCESS(ntStatus)) { memset (&info->partInfo, 0, sizeof (info->partInfo)); info->partInfo.PartitionLength = pi.PartitionLength; info->partInfo.PartitionNumber = pi.PartitionNumber; info->partInfo.StartingOffset = pi.StartingOffset; if (pi.PartitionStyle == PARTITION_STYLE_MBR) { info->partInfo.PartitionType = pi.Mbr.PartitionType; info->partInfo.BootIndicator = pi.Mbr.BootIndicator; } info->IsGPT = pi.PartitionStyle == PARTITION_STYLE_GPT; } else { ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &info->partInfo, sizeof (info->partInfo)); info->IsGPT = FALSE; } if (!NT_SUCCESS (ntStatus)) { GET_LENGTH_INFORMATION lengthInfo; ntStatus = TCDeviceIoControl (info->deviceName, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof (lengthInfo)); if (NT_SUCCESS (ntStatus)) { memset (&info->partInfo, 0, sizeof (info->partInfo)); info->partInfo.PartitionLength = lengthInfo.Length; } } info->IsDynamic = FALSE; if (NT_SUCCESS (ntStatus) && OsMajorVersion >= 6) { # define IOCTL_VOLUME_IS_DYNAMIC CTL_CODE(IOCTL_VOLUME_BASE, 18, METHOD_BUFFERED, FILE_ANY_ACCESS) if (!NT_SUCCESS (TCDeviceIoControl (info->deviceName, IOCTL_VOLUME_IS_DYNAMIC, NULL, 0, &info->IsDynamic, sizeof (info->IsDynamic)))) info->IsDynamic = FALSE; } Irp->IoStatus.Information = sizeof (DISK_PARTITION_INFO_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case TC_IOCTL_GET_DRIVE_GEOMETRY: if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_STRUCT), ValidateInputOutput)) { DISK_GEOMETRY_STRUCT *g = (DISK_GEOMETRY_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &g->diskGeometry, sizeof (g->diskGeometry)); Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_STRUCT); Irp->IoStatus.Status = ntStatus; } } break; case VC_IOCTL_GET_DRIVE_GEOMETRY_EX: if (ValidateIOBufferSize (Irp, sizeof (DISK_GEOMETRY_EX_STRUCT), ValidateInputOutput)) { DISK_GEOMETRY_EX_STRUCT *g = (DISK_GEOMETRY_EX_STRUCT *) Irp->AssociatedIrp.SystemBuffer; { NTSTATUS ntStatus; PVOID buffer = TCalloc (256); // enough for DISK_GEOMETRY_EX and padded data if (buffer) { EnsureNullTerminatedString (g->deviceName, sizeof (g->deviceName)); Dump ("Calling IOCTL_DISK_GET_DRIVE_GEOMETRY_EX on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, NULL, 0, buffer, 256); if (NT_SUCCESS(ntStatus)) { PDISK_GEOMETRY_EX pGeo = (PDISK_GEOMETRY_EX) buffer; memcpy (&g->diskGeometry, &pGeo->Geometry, sizeof (DISK_GEOMETRY)); g->DiskSize.QuadPart = pGeo->DiskSize.QuadPart; } else { DISK_GEOMETRY dg = {0}; Dump ("Failed. Calling IOCTL_DISK_GET_DRIVE_GEOMETRY on %ls\n", g->deviceName); ntStatus = TCDeviceIoControl (g->deviceName, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &dg, sizeof (dg)); if (NT_SUCCESS(ntStatus)) { memcpy (&g->diskGeometry, &dg, sizeof (DISK_GEOMETRY)); g->DiskSize.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector; if (OsMajorVersion >= 6) { STORAGE_READ_CAPACITY storage = {0}; NTSTATUS lStatus; storage.Version = sizeof (STORAGE_READ_CAPACITY); Dump ("Calling IOCTL_STORAGE_READ_CAPACITY on %ls\n", g->deviceName); lStatus = TCDeviceIoControl (g->deviceName, IOCTL_STORAGE_READ_CAPACITY, NULL, 0, &storage, sizeof (STORAGE_READ_CAPACITY)); if ( NT_SUCCESS(lStatus) && (storage.Size == sizeof (STORAGE_READ_CAPACITY)) ) { g->DiskSize.QuadPart = storage.DiskLength.QuadPart; } } } } TCfree (buffer); Irp->IoStatus.Information = sizeof (DISK_GEOMETRY_EX_STRUCT); Irp->IoStatus.Status = ntStatus; } else { Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES; Irp->IoStatus.Information = 0; } } } break; case TC_IOCTL_PROBE_REAL_DRIVE_SIZE: if (ValidateIOBufferSize (Irp, sizeof (ProbeRealDriveSizeRequest), ValidateInputOutput)) { ProbeRealDriveSizeRequest *request = (ProbeRealDriveSizeRequest *) Irp->AssociatedIrp.SystemBuffer; NTSTATUS status; UNICODE_STRING name; PFILE_OBJECT fileObject; PDEVICE_OBJECT deviceObject; EnsureNullTerminatedString (request->DeviceName, sizeof (request->DeviceName)); RtlInitUnicodeString (&name, request->DeviceName); status = IoGetDeviceObjectPointer (&name, FILE_READ_ATTRIBUTES, &fileObject, &deviceObject); if (!NT_SUCCESS (status)) { Irp->IoStatus.Information = 0; Irp->IoStatus.Status = status; break; } status = ProbeRealDriveSize (deviceObject, &request->RealDriveSize); ObDereferenceObject (fileObject); if (status == STATUS_TIMEOUT) { request->TimeOut = TRUE; Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); Irp->IoStatus.Status = STATUS_SUCCESS; } else if (!NT_SUCCESS (status)) { Irp->IoStatus.Information = 0; Irp->IoStatus.Status = status; } else { request->TimeOut = FALSE; Irp->IoStatus.Information = sizeof (ProbeRealDriveSizeRequest); Irp->IoStatus.Status = status; } } break; case TC_IOCTL_MOUNT_VOLUME: if (ValidateIOBufferSize (Irp, sizeof (MOUNT_STRUCT), ValidateInputOutput)) { MOUNT_STRUCT *mount = (MOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; if (mount->VolumePassword.Length > MAX_PASSWORD || mount->ProtectedHidVolPassword.Length > MAX_PASSWORD || mount->pkcs5_prf < 0 || mount->pkcs5_prf > LAST_PRF_ID || mount->VolumePim < -1 || mount->VolumePim == INT_MAX || mount->ProtectedHidVolPkcs5Prf < 0 || mount->ProtectedHidVolPkcs5Prf > LAST_PRF_ID || (mount->bTrueCryptMode != FALSE && mount->bTrueCryptMode != TRUE) ) { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; break; } EnsureNullTerminatedString (mount->wszVolume, sizeof (mount->wszVolume)); EnsureNullTerminatedString (mount->wszLabel, sizeof (mount->wszLabel)); Irp->IoStatus.Information = sizeof (MOUNT_STRUCT); Irp->IoStatus.Status = MountDevice (DeviceObject, mount); burn (&mount->VolumePassword, sizeof (mount->VolumePassword)); burn (&mount->ProtectedHidVolPassword, sizeof (mount->ProtectedHidVolPassword)); burn (&mount->pkcs5_prf, sizeof (mount->pkcs5_prf)); burn (&mount->VolumePim, sizeof (mount->VolumePim)); burn (&mount->bTrueCryptMode, sizeof (mount->bTrueCryptMode)); burn (&mount->ProtectedHidVolPkcs5Prf, sizeof (mount->ProtectedHidVolPkcs5Prf)); burn (&mount->ProtectedHidVolPim, sizeof (mount->ProtectedHidVolPim)); } break; case TC_IOCTL_DISMOUNT_VOLUME: if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; PDEVICE_OBJECT ListDevice = GetVirtualVolumeDeviceObject (unmount->nDosDriveNo); unmount->nReturnCode = ERR_DRIVE_NOT_FOUND; if (ListDevice) { PEXTENSION ListExtension = (PEXTENSION) ListDevice->DeviceExtension; if (IsVolumeAccessibleByCurrentUser (ListExtension)) unmount->nReturnCode = UnmountDevice (unmount, ListDevice, unmount->ignoreOpenFiles); } Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_DISMOUNT_ALL_VOLUMES: if (ValidateIOBufferSize (Irp, sizeof (UNMOUNT_STRUCT), ValidateInputOutput)) { UNMOUNT_STRUCT *unmount = (UNMOUNT_STRUCT *) Irp->AssociatedIrp.SystemBuffer; unmount->nReturnCode = UnmountAllDevices (unmount, unmount->ignoreOpenFiles); Irp->IoStatus.Information = sizeof (UNMOUNT_STRUCT); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_BOOT_ENCRYPTION_SETUP: Irp->IoStatus.Status = StartBootEncryptionSetup (DeviceObject, Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_ABORT_BOOT_ENCRYPTION_SETUP: Irp->IoStatus.Status = AbortBootEncryptionSetup(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: GetBootEncryptionStatus (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_ENCRYPTION_SETUP_RESULT: Irp->IoStatus.Information = 0; Irp->IoStatus.Status = GetSetupResult(); break; case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: GetBootDriveVolumeProperties (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_LOADER_VERSION: GetBootLoaderVersion (Irp, irpSp); break; case TC_IOCTL_REOPEN_BOOT_VOLUME_HEADER: ReopenBootVolumeHeader (Irp, irpSp); break; case VC_IOCTL_GET_BOOT_LOADER_FINGERPRINT: GetBootLoaderFingerprint (Irp, irpSp); break; case TC_IOCTL_GET_BOOT_ENCRYPTION_ALGORITHM_NAME: GetBootEncryptionAlgorithmName (Irp, irpSp); break; case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: if (ValidateIOBufferSize (Irp, sizeof (int), ValidateOutput)) { *(int *) Irp->AssociatedIrp.SystemBuffer = IsHiddenSystemRunning() ? 1 : 0; Irp->IoStatus.Information = sizeof (int); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_START_DECOY_SYSTEM_WIPE: Irp->IoStatus.Status = StartDecoySystemWipe (DeviceObject, Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_ABORT_DECOY_SYSTEM_WIPE: Irp->IoStatus.Status = AbortDecoySystemWipe(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_RESULT: Irp->IoStatus.Status = GetDecoySystemWipeResult(); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_DECOY_SYSTEM_WIPE_STATUS: GetDecoySystemWipeStatus (Irp, irpSp); break; case TC_IOCTL_WRITE_BOOT_DRIVE_SECTOR: Irp->IoStatus.Status = WriteBootDriveSector (Irp, irpSp); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_WARNING_FLAGS: if (ValidateIOBufferSize (Irp, sizeof (GetWarningFlagsRequest), ValidateOutput)) { GetWarningFlagsRequest *flags = (GetWarningFlagsRequest *) Irp->AssociatedIrp.SystemBuffer; flags->PagingFileCreationPrevented = PagingFileCreationPrevented; PagingFileCreationPrevented = FALSE; flags->SystemFavoriteVolumeDirty = SystemFavoriteVolumeDirty; SystemFavoriteVolumeDirty = FALSE; Irp->IoStatus.Information = sizeof (GetWarningFlagsRequest); Irp->IoStatus.Status = STATUS_SUCCESS; } break; case TC_IOCTL_SET_SYSTEM_FAVORITE_VOLUME_DIRTY: if (UserCanAccessDriveDevice()) { SystemFavoriteVolumeDirty = TRUE; Irp->IoStatus.Status = STATUS_SUCCESS; } else Irp->IoStatus.Status = STATUS_ACCESS_DENIED; Irp->IoStatus.Information = 0; break; case TC_IOCTL_REREAD_DRIVER_CONFIG: Irp->IoStatus.Status = ReadRegistryConfigFlags (FALSE); Irp->IoStatus.Information = 0; break; case TC_IOCTL_GET_SYSTEM_DRIVE_DUMP_CONFIG: if ( (ValidateIOBufferSize (Irp, sizeof (GetSystemDriveDumpConfigRequest), ValidateOutput)) && (Irp->RequestorMode == KernelMode) ) { GetSystemDriveDumpConfigRequest *request = (GetSystemDriveDumpConfigRequest *) Irp->AssociatedIrp.SystemBuffer; request->BootDriveFilterExtension = GetBootDriveFilterExtension(); if (IsBootDriveMounted() && request->BootDriveFilterExtension) { request->HwEncryptionEnabled = IsHwEncryptionEnabled(); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = sizeof (*request); } else { Irp->IoStatus.Status = STATUS_INVALID_PARAMETER; Irp->IoStatus.Information = 0; } } break; default: return TCCompleteIrp (Irp, STATUS_INVALID_DEVICE_REQUEST, 0); } #if defined(DEBUG) || defined(DEBUG_TRACE) if (!NT_SUCCESS (Irp->IoStatus.Status)) { switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case TC_IOCTL_GET_MOUNTED_VOLUMES: case TC_IOCTL_GET_PASSWORD_CACHE_STATUS: case TC_IOCTL_GET_PORTABLE_MODE_STATUS: case TC_IOCTL_SET_PORTABLE_MODE_STATUS: case TC_IOCTL_OPEN_TEST: case TC_IOCTL_GET_RESOLVED_SYMLINK: case TC_IOCTL_GET_DRIVE_PARTITION_INFO: case TC_IOCTL_GET_BOOT_DRIVE_VOLUME_PROPERTIES: case TC_IOCTL_GET_BOOT_ENCRYPTION_STATUS: case TC_IOCTL_IS_HIDDEN_SYSTEM_RUNNING: break; default: Dump ("IOCTL error 0x%08x\n", Irp->IoStatus.Status); } } #endif return TCCompleteIrp (Irp, Irp->IoStatus.Status, Irp->IoStatus.Information); }
169,481
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void suffix_object( cJSON *prev, cJSON *item ) { prev->next = item; item->prev = prev; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
static void suffix_object( cJSON *prev, cJSON *item )
167,313
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: I18NCustomBindings::I18NCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetL10nMessage", base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this))); RouteFunction("GetL10nUILanguage", base::Bind(&I18NCustomBindings::GetL10nUILanguage, base::Unretained(this))); RouteFunction("DetectTextLanguage", base::Bind(&I18NCustomBindings::DetectTextLanguage, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
I18NCustomBindings::I18NCustomBindings(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetL10nMessage", "i18n", base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this))); RouteFunction("GetL10nUILanguage", "i18n", base::Bind(&I18NCustomBindings::GetL10nUILanguage, base::Unretained(this))); RouteFunction("DetectTextLanguage", "i18n", base::Bind(&I18NCustomBindings::DetectTextLanguage, base::Unretained(this))); }
172,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static long vfio_pci_ioctl(void *device_data, unsigned int cmd, unsigned long arg) { struct vfio_pci_device *vdev = device_data; unsigned long minsz; if (cmd == VFIO_DEVICE_GET_INFO) { struct vfio_device_info info; minsz = offsetofend(struct vfio_device_info, num_irqs); if (copy_from_user(&info, (void __user *)arg, minsz)) return -EFAULT; if (info.argsz < minsz) return -EINVAL; info.flags = VFIO_DEVICE_FLAGS_PCI; if (vdev->reset_works) info.flags |= VFIO_DEVICE_FLAGS_RESET; info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions; info.num_irqs = VFIO_PCI_NUM_IRQS; return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0; } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) { struct pci_dev *pdev = vdev->pdev; struct vfio_region_info info; struct vfio_info_cap caps = { .buf = NULL, .size = 0 }; int i, ret; minsz = offsetofend(struct vfio_region_info, offset); if (copy_from_user(&info, (void __user *)arg, minsz)) return -EFAULT; if (info.argsz < minsz) return -EINVAL; switch (info.index) { case VFIO_PCI_CONFIG_REGION_INDEX: info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = pdev->cfg_size; info.flags = VFIO_REGION_INFO_FLAG_READ | VFIO_REGION_INFO_FLAG_WRITE; break; case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX: info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = pci_resource_len(pdev, info.index); if (!info.size) { info.flags = 0; break; } info.flags = VFIO_REGION_INFO_FLAG_READ | VFIO_REGION_INFO_FLAG_WRITE; if (vdev->bar_mmap_supported[info.index]) { info.flags |= VFIO_REGION_INFO_FLAG_MMAP; if (info.index == vdev->msix_bar) { ret = msix_sparse_mmap_cap(vdev, &caps); if (ret) return ret; } } break; case VFIO_PCI_ROM_REGION_INDEX: { void __iomem *io; size_t size; info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.flags = 0; /* Report the BAR size, not the ROM size */ info.size = pci_resource_len(pdev, info.index); if (!info.size) { /* Shadow ROMs appear as PCI option ROMs */ if (pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW) info.size = 0x20000; else break; } /* Is it really there? */ io = pci_map_rom(pdev, &size); if (!io || !size) { info.size = 0; break; } pci_unmap_rom(pdev, io); info.flags = VFIO_REGION_INFO_FLAG_READ; break; } case VFIO_PCI_VGA_REGION_INDEX: if (!vdev->has_vga) return -EINVAL; info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = 0xc0000; info.flags = VFIO_REGION_INFO_FLAG_READ | VFIO_REGION_INFO_FLAG_WRITE; break; default: if (info.index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions) return -EINVAL; i = info.index - VFIO_PCI_NUM_REGIONS; info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = vdev->region[i].size; info.flags = vdev->region[i].flags; ret = region_type_cap(vdev, &caps, vdev->region[i].type, vdev->region[i].subtype); if (ret) return ret; } if (caps.size) { info.flags |= VFIO_REGION_INFO_FLAG_CAPS; if (info.argsz < sizeof(info) + caps.size) { info.argsz = sizeof(info) + caps.size; info.cap_offset = 0; } else { vfio_info_cap_shift(&caps, sizeof(info)); if (copy_to_user((void __user *)arg + sizeof(info), caps.buf, caps.size)) { kfree(caps.buf); return -EFAULT; } info.cap_offset = sizeof(info); } kfree(caps.buf); } return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0; } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) { struct vfio_irq_info info; minsz = offsetofend(struct vfio_irq_info, count); if (copy_from_user(&info, (void __user *)arg, minsz)) return -EFAULT; if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS) return -EINVAL; switch (info.index) { case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX: case VFIO_PCI_REQ_IRQ_INDEX: break; case VFIO_PCI_ERR_IRQ_INDEX: if (pci_is_pcie(vdev->pdev)) break; /* pass thru to return error */ default: return -EINVAL; } info.flags = VFIO_IRQ_INFO_EVENTFD; info.count = vfio_pci_get_irq_count(vdev, info.index); if (info.index == VFIO_PCI_INTX_IRQ_INDEX) info.flags |= (VFIO_IRQ_INFO_MASKABLE | VFIO_IRQ_INFO_AUTOMASKED); else info.flags |= VFIO_IRQ_INFO_NORESIZE; return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0; } else if (cmd == VFIO_DEVICE_SET_IRQS) { struct vfio_irq_set hdr; u8 *data = NULL; int ret = 0; minsz = offsetofend(struct vfio_irq_set, count); if (copy_from_user(&hdr, (void __user *)arg, minsz)) return -EFAULT; if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS || hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK | VFIO_IRQ_SET_ACTION_TYPE_MASK)) return -EINVAL; if (!(hdr.flags & VFIO_IRQ_SET_DATA_NONE)) { size_t size; int max = vfio_pci_get_irq_count(vdev, hdr.index); if (hdr.flags & VFIO_IRQ_SET_DATA_BOOL) size = sizeof(uint8_t); else if (hdr.flags & VFIO_IRQ_SET_DATA_EVENTFD) size = sizeof(int32_t); else return -EINVAL; if (hdr.argsz - minsz < hdr.count * size || hdr.start >= max || hdr.start + hdr.count > max) return -EINVAL; data = memdup_user((void __user *)(arg + minsz), hdr.count * size); if (IS_ERR(data)) return PTR_ERR(data); } mutex_lock(&vdev->igate); ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index, hdr.start, hdr.count, data); mutex_unlock(&vdev->igate); kfree(data); return ret; } else if (cmd == VFIO_DEVICE_RESET) { return vdev->reset_works ? pci_try_reset_function(vdev->pdev) : -EINVAL; } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) { struct vfio_pci_hot_reset_info hdr; struct vfio_pci_fill_info fill = { 0 }; struct vfio_pci_dependent_device *devices = NULL; bool slot = false; int ret = 0; minsz = offsetofend(struct vfio_pci_hot_reset_info, count); if (copy_from_user(&hdr, (void __user *)arg, minsz)) return -EFAULT; if (hdr.argsz < minsz) return -EINVAL; hdr.flags = 0; /* Can we do a slot or bus reset or neither? */ if (!pci_probe_reset_slot(vdev->pdev->slot)) slot = true; else if (pci_probe_reset_bus(vdev->pdev->bus)) return -ENODEV; /* How many devices are affected? */ ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs, &fill.max, slot); if (ret) return ret; WARN_ON(!fill.max); /* Should always be at least one */ /* * If there's enough space, fill it now, otherwise return * -ENOSPC and the number of devices affected. */ if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) { ret = -ENOSPC; hdr.count = fill.max; goto reset_info_exit; } devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL); if (!devices) return -ENOMEM; fill.devices = devices; ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_fill_devs, &fill, slot); /* * If a device was removed between counting and filling, * we may come up short of fill.max. If a device was * added, we'll have a return of -EAGAIN above. */ if (!ret) hdr.count = fill.cur; reset_info_exit: if (copy_to_user((void __user *)arg, &hdr, minsz)) ret = -EFAULT; if (!ret) { if (copy_to_user((void __user *)(arg + minsz), devices, hdr.count * sizeof(*devices))) ret = -EFAULT; } kfree(devices); return ret; } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) { struct vfio_pci_hot_reset hdr; int32_t *group_fds; struct vfio_pci_group_entry *groups; struct vfio_pci_group_info info; bool slot = false; int i, count = 0, ret = 0; minsz = offsetofend(struct vfio_pci_hot_reset, count); if (copy_from_user(&hdr, (void __user *)arg, minsz)) return -EFAULT; if (hdr.argsz < minsz || hdr.flags) return -EINVAL; /* Can we do a slot or bus reset or neither? */ if (!pci_probe_reset_slot(vdev->pdev->slot)) slot = true; else if (pci_probe_reset_bus(vdev->pdev->bus)) return -ENODEV; /* * We can't let userspace give us an arbitrarily large * buffer to copy, so verify how many we think there * could be. Note groups can have multiple devices so * one group per device is the max. */ ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs, &count, slot); if (ret) return ret; /* Somewhere between 1 and count is OK */ if (!hdr.count || hdr.count > count) return -EINVAL; group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL); groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL); if (!group_fds || !groups) { kfree(group_fds); kfree(groups); return -ENOMEM; } if (copy_from_user(group_fds, (void __user *)(arg + minsz), hdr.count * sizeof(*group_fds))) { kfree(group_fds); kfree(groups); return -EFAULT; } /* * For each group_fd, get the group through the vfio external * user interface and store the group and iommu ID. This * ensures the group is held across the reset. */ for (i = 0; i < hdr.count; i++) { struct vfio_group *group; struct fd f = fdget(group_fds[i]); if (!f.file) { ret = -EBADF; break; } group = vfio_group_get_external_user(f.file); fdput(f); if (IS_ERR(group)) { ret = PTR_ERR(group); break; } groups[i].group = group; groups[i].id = vfio_external_user_iommu_id(group); } kfree(group_fds); /* release reference to groups on error */ if (ret) goto hot_reset_release; info.count = hdr.count; info.groups = groups; /* * Test whether all the affected devices are contained * by the set of groups provided by the user. */ ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_validate_devs, &info, slot); if (!ret) /* User has access, do the reset */ ret = slot ? pci_try_reset_slot(vdev->pdev->slot) : pci_try_reset_bus(vdev->pdev->bus); hot_reset_release: for (i--; i >= 0; i--) vfio_group_put_external_user(groups[i].group); kfree(groups); return ret; } return -ENOTTY; } Commit Message: vfio/pci: Fix integer overflows, bitmask check The VFIO_DEVICE_SET_IRQS ioctl did not sufficiently sanitize user-supplied integers, potentially allowing memory corruption. This patch adds appropriate integer overflow checks, checks the range bounds for VFIO_IRQ_SET_DATA_NONE, and also verifies that only single element in the VFIO_IRQ_SET_DATA_TYPE_MASK bitmask is set. VFIO_IRQ_SET_ACTION_TYPE_MASK is already correctly checked later in vfio_pci_set_irqs_ioctl(). Furthermore, a kzalloc is changed to a kcalloc because the use of a kzalloc with an integer multiplication allowed an integer overflow condition to be reached without this patch. kcalloc checks for overflow and should prevent a similar occurrence. Signed-off-by: Vlad Tsyrklevich <[email protected]> Signed-off-by: Alex Williamson <[email protected]> CWE ID: CWE-190
static long vfio_pci_ioctl(void *device_data, unsigned int cmd, unsigned long arg) { struct vfio_pci_device *vdev = device_data; unsigned long minsz; if (cmd == VFIO_DEVICE_GET_INFO) { struct vfio_device_info info; minsz = offsetofend(struct vfio_device_info, num_irqs); if (copy_from_user(&info, (void __user *)arg, minsz)) return -EFAULT; if (info.argsz < minsz) return -EINVAL; info.flags = VFIO_DEVICE_FLAGS_PCI; if (vdev->reset_works) info.flags |= VFIO_DEVICE_FLAGS_RESET; info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions; info.num_irqs = VFIO_PCI_NUM_IRQS; return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0; } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) { struct pci_dev *pdev = vdev->pdev; struct vfio_region_info info; struct vfio_info_cap caps = { .buf = NULL, .size = 0 }; int i, ret; minsz = offsetofend(struct vfio_region_info, offset); if (copy_from_user(&info, (void __user *)arg, minsz)) return -EFAULT; if (info.argsz < minsz) return -EINVAL; switch (info.index) { case VFIO_PCI_CONFIG_REGION_INDEX: info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = pdev->cfg_size; info.flags = VFIO_REGION_INFO_FLAG_READ | VFIO_REGION_INFO_FLAG_WRITE; break; case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX: info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = pci_resource_len(pdev, info.index); if (!info.size) { info.flags = 0; break; } info.flags = VFIO_REGION_INFO_FLAG_READ | VFIO_REGION_INFO_FLAG_WRITE; if (vdev->bar_mmap_supported[info.index]) { info.flags |= VFIO_REGION_INFO_FLAG_MMAP; if (info.index == vdev->msix_bar) { ret = msix_sparse_mmap_cap(vdev, &caps); if (ret) return ret; } } break; case VFIO_PCI_ROM_REGION_INDEX: { void __iomem *io; size_t size; info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.flags = 0; /* Report the BAR size, not the ROM size */ info.size = pci_resource_len(pdev, info.index); if (!info.size) { /* Shadow ROMs appear as PCI option ROMs */ if (pdev->resource[PCI_ROM_RESOURCE].flags & IORESOURCE_ROM_SHADOW) info.size = 0x20000; else break; } /* Is it really there? */ io = pci_map_rom(pdev, &size); if (!io || !size) { info.size = 0; break; } pci_unmap_rom(pdev, io); info.flags = VFIO_REGION_INFO_FLAG_READ; break; } case VFIO_PCI_VGA_REGION_INDEX: if (!vdev->has_vga) return -EINVAL; info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = 0xc0000; info.flags = VFIO_REGION_INFO_FLAG_READ | VFIO_REGION_INFO_FLAG_WRITE; break; default: if (info.index >= VFIO_PCI_NUM_REGIONS + vdev->num_regions) return -EINVAL; i = info.index - VFIO_PCI_NUM_REGIONS; info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); info.size = vdev->region[i].size; info.flags = vdev->region[i].flags; ret = region_type_cap(vdev, &caps, vdev->region[i].type, vdev->region[i].subtype); if (ret) return ret; } if (caps.size) { info.flags |= VFIO_REGION_INFO_FLAG_CAPS; if (info.argsz < sizeof(info) + caps.size) { info.argsz = sizeof(info) + caps.size; info.cap_offset = 0; } else { vfio_info_cap_shift(&caps, sizeof(info)); if (copy_to_user((void __user *)arg + sizeof(info), caps.buf, caps.size)) { kfree(caps.buf); return -EFAULT; } info.cap_offset = sizeof(info); } kfree(caps.buf); } return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0; } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) { struct vfio_irq_info info; minsz = offsetofend(struct vfio_irq_info, count); if (copy_from_user(&info, (void __user *)arg, minsz)) return -EFAULT; if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS) return -EINVAL; switch (info.index) { case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX: case VFIO_PCI_REQ_IRQ_INDEX: break; case VFIO_PCI_ERR_IRQ_INDEX: if (pci_is_pcie(vdev->pdev)) break; /* pass thru to return error */ default: return -EINVAL; } info.flags = VFIO_IRQ_INFO_EVENTFD; info.count = vfio_pci_get_irq_count(vdev, info.index); if (info.index == VFIO_PCI_INTX_IRQ_INDEX) info.flags |= (VFIO_IRQ_INFO_MASKABLE | VFIO_IRQ_INFO_AUTOMASKED); else info.flags |= VFIO_IRQ_INFO_NORESIZE; return copy_to_user((void __user *)arg, &info, minsz) ? -EFAULT : 0; } else if (cmd == VFIO_DEVICE_SET_IRQS) { struct vfio_irq_set hdr; size_t size; u8 *data = NULL; int max, ret = 0; minsz = offsetofend(struct vfio_irq_set, count); if (copy_from_user(&hdr, (void __user *)arg, minsz)) return -EFAULT; if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS || hdr.count >= (U32_MAX - hdr.start) || hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK | VFIO_IRQ_SET_ACTION_TYPE_MASK)) return -EINVAL; max = vfio_pci_get_irq_count(vdev, hdr.index); if (hdr.start >= max || hdr.start + hdr.count > max) return -EINVAL; switch (hdr.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) { case VFIO_IRQ_SET_DATA_NONE: size = 0; break; case VFIO_IRQ_SET_DATA_BOOL: size = sizeof(uint8_t); break; case VFIO_IRQ_SET_DATA_EVENTFD: size = sizeof(int32_t); break; default: return -EINVAL; } if (size) { if (hdr.argsz - minsz < hdr.count * size) return -EINVAL; data = memdup_user((void __user *)(arg + minsz), hdr.count * size); if (IS_ERR(data)) return PTR_ERR(data); } mutex_lock(&vdev->igate); ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index, hdr.start, hdr.count, data); mutex_unlock(&vdev->igate); kfree(data); return ret; } else if (cmd == VFIO_DEVICE_RESET) { return vdev->reset_works ? pci_try_reset_function(vdev->pdev) : -EINVAL; } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) { struct vfio_pci_hot_reset_info hdr; struct vfio_pci_fill_info fill = { 0 }; struct vfio_pci_dependent_device *devices = NULL; bool slot = false; int ret = 0; minsz = offsetofend(struct vfio_pci_hot_reset_info, count); if (copy_from_user(&hdr, (void __user *)arg, minsz)) return -EFAULT; if (hdr.argsz < minsz) return -EINVAL; hdr.flags = 0; /* Can we do a slot or bus reset or neither? */ if (!pci_probe_reset_slot(vdev->pdev->slot)) slot = true; else if (pci_probe_reset_bus(vdev->pdev->bus)) return -ENODEV; /* How many devices are affected? */ ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs, &fill.max, slot); if (ret) return ret; WARN_ON(!fill.max); /* Should always be at least one */ /* * If there's enough space, fill it now, otherwise return * -ENOSPC and the number of devices affected. */ if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) { ret = -ENOSPC; hdr.count = fill.max; goto reset_info_exit; } devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL); if (!devices) return -ENOMEM; fill.devices = devices; ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_fill_devs, &fill, slot); /* * If a device was removed between counting and filling, * we may come up short of fill.max. If a device was * added, we'll have a return of -EAGAIN above. */ if (!ret) hdr.count = fill.cur; reset_info_exit: if (copy_to_user((void __user *)arg, &hdr, minsz)) ret = -EFAULT; if (!ret) { if (copy_to_user((void __user *)(arg + minsz), devices, hdr.count * sizeof(*devices))) ret = -EFAULT; } kfree(devices); return ret; } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) { struct vfio_pci_hot_reset hdr; int32_t *group_fds; struct vfio_pci_group_entry *groups; struct vfio_pci_group_info info; bool slot = false; int i, count = 0, ret = 0; minsz = offsetofend(struct vfio_pci_hot_reset, count); if (copy_from_user(&hdr, (void __user *)arg, minsz)) return -EFAULT; if (hdr.argsz < minsz || hdr.flags) return -EINVAL; /* Can we do a slot or bus reset or neither? */ if (!pci_probe_reset_slot(vdev->pdev->slot)) slot = true; else if (pci_probe_reset_bus(vdev->pdev->bus)) return -ENODEV; /* * We can't let userspace give us an arbitrarily large * buffer to copy, so verify how many we think there * could be. Note groups can have multiple devices so * one group per device is the max. */ ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_count_devs, &count, slot); if (ret) return ret; /* Somewhere between 1 and count is OK */ if (!hdr.count || hdr.count > count) return -EINVAL; group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL); groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL); if (!group_fds || !groups) { kfree(group_fds); kfree(groups); return -ENOMEM; } if (copy_from_user(group_fds, (void __user *)(arg + minsz), hdr.count * sizeof(*group_fds))) { kfree(group_fds); kfree(groups); return -EFAULT; } /* * For each group_fd, get the group through the vfio external * user interface and store the group and iommu ID. This * ensures the group is held across the reset. */ for (i = 0; i < hdr.count; i++) { struct vfio_group *group; struct fd f = fdget(group_fds[i]); if (!f.file) { ret = -EBADF; break; } group = vfio_group_get_external_user(f.file); fdput(f); if (IS_ERR(group)) { ret = PTR_ERR(group); break; } groups[i].group = group; groups[i].id = vfio_external_user_iommu_id(group); } kfree(group_fds); /* release reference to groups on error */ if (ret) goto hot_reset_release; info.count = hdr.count; info.groups = groups; /* * Test whether all the affected devices are contained * by the set of groups provided by the user. */ ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, vfio_pci_validate_devs, &info, slot); if (!ret) /* User has access, do the reset */ ret = slot ? pci_try_reset_slot(vdev->pdev->slot) : pci_try_reset_bus(vdev->pdev->bus); hot_reset_release: for (i--; i >= 0; i--) vfio_group_put_external_user(groups[i].group); kfree(groups); return ret; } return -ENOTTY; }
166,900
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: _dopr(char **sbuffer, char **buffer, size_t *maxlen, size_t *retlen, int *truncated, const char *format, va_list args) { char ch; LLONG value; LDOUBLE fvalue; char *strvalue; int min; int max; int state; int flags; int cflags; size_t currlen; state = DP_S_DEFAULT; flags = currlen = cflags = min = 0; max = -1; ch = *format++; while (state != DP_S_DONE) { if (ch == '\0' || (buffer == NULL && currlen >= *maxlen)) state = DP_S_DONE; switch (state) { case DP_S_DEFAULT: if (ch == '%') state = DP_S_FLAGS; else doapr_outch(sbuffer, buffer, &currlen, maxlen, ch); ch = *format++; break; case DP_S_FLAGS: case '-': flags |= DP_F_MINUS; ch = *format++; break; case '+': flags |= DP_F_PLUS; ch = *format++; break; case ' ': flags |= DP_F_SPACE; ch = *format++; break; case '#': flags |= DP_F_NUM; ch = *format++; break; case '0': flags |= DP_F_ZERO; ch = *format++; break; default: state = DP_S_MIN; break; } break; case DP_S_MIN: if (isdigit((unsigned char)ch)) { min = 10 * min + char_to_int(ch); ch = *format++; } else if (ch == '*') { min = va_arg(args, int); ch = *format++; state = DP_S_DOT; } else state = DP_S_DOT; break; case DP_S_DOT: if (ch == '.') { state = DP_S_MAX; ch = *format++; } else state = DP_S_MOD; break; case DP_S_MAX: if (isdigit((unsigned char)ch)) { if (max < 0) max = 0; max = 10 * max + char_to_int(ch); ch = *format++; } else if (ch == '*') { max = va_arg(args, int); ch = *format++; state = DP_S_MOD; } else state = DP_S_MOD; break; case DP_S_MOD: switch (ch) { case 'h': cflags = DP_C_SHORT; ch = *format++; break; case 'l': if (*format == 'l') { cflags = DP_C_LLONG; format++; } else cflags = DP_C_LONG; ch = *format++; break; case 'q': cflags = DP_C_LLONG; ch = *format++; break; case 'L': cflags = DP_C_LDOUBLE; ch = *format++; break; default: break; } state = DP_S_CONV; break; case DP_S_CONV: switch (ch) { case 'd': case 'i': switch (cflags) { case DP_C_SHORT: value = (short int)va_arg(args, int); break; case DP_C_LONG: value = va_arg(args, long int); break; case DP_C_LLONG: value = va_arg(args, LLONG); break; default: value = va_arg(args, int); value = va_arg(args, int); break; } fmtint(sbuffer, buffer, &currlen, maxlen, value, 10, min, max, flags); break; case 'X': flags |= DP_F_UP; case 'o': case 'u': flags |= DP_F_UNSIGNED; switch (cflags) { case DP_C_SHORT: value = (unsigned short int)va_arg(args, unsigned int); break; case DP_C_LONG: value = (LLONG) va_arg(args, unsigned long int); break; case DP_C_LLONG: value = va_arg(args, unsigned LLONG); break; default: value = (LLONG) va_arg(args, unsigned int); break; value = (LLONG) va_arg(args, unsigned int); break; } fmtint(sbuffer, buffer, &currlen, maxlen, value, ch == 'o' ? 8 : (ch == 'u' ? 10 : 16), min, max, flags); break; case 'f': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); fmtfp(sbuffer, buffer, &currlen, maxlen, fvalue, min, max, flags); break; case 'E': flags |= DP_F_UP; fvalue = va_arg(args, double); break; case 'G': flags |= DP_F_UP; case 'g': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); break; case 'c': doapr_outch(sbuffer, buffer, &currlen, maxlen, fvalue = va_arg(args, double); break; case 'c': doapr_outch(sbuffer, buffer, &currlen, maxlen, va_arg(args, int)); break; case 's': strvalue = va_arg(args, char *); } fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue, flags, min, max); else max = *maxlen; } fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue, flags, min, max); break; case 'p': value = (long)va_arg(args, void *); fmtint(sbuffer, buffer, &currlen, maxlen, value, 16, min, max, flags | DP_F_NUM); break; case 'n': /* XXX */ if (cflags == DP_C_SHORT) { } else if (cflags == DP_C_LLONG) { /* XXX */ LLONG *num; num = va_arg(args, LLONG *); *num = (LLONG) currlen; } else { int *num; num = va_arg(args, int *); *num = currlen; } break; case '%': doapr_outch(sbuffer, buffer, &currlen, maxlen, ch); break; case 'w': /* not supported yet, treat as next char */ } Commit Message: CWE ID: CWE-119
_dopr(char **sbuffer, char **buffer, size_t *maxlen, size_t *retlen, int *truncated, const char *format, va_list args) { char ch; LLONG value; LDOUBLE fvalue; char *strvalue; int min; int max; int state; int flags; int cflags; size_t currlen; state = DP_S_DEFAULT; flags = currlen = cflags = min = 0; max = -1; ch = *format++; while (state != DP_S_DONE) { if (ch == '\0' || (buffer == NULL && currlen >= *maxlen)) state = DP_S_DONE; switch (state) { case DP_S_DEFAULT: if (ch == '%') state = DP_S_FLAGS; else if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, ch)) return 0; ch = *format++; break; case DP_S_FLAGS: case '-': flags |= DP_F_MINUS; ch = *format++; break; case '+': flags |= DP_F_PLUS; ch = *format++; break; case ' ': flags |= DP_F_SPACE; ch = *format++; break; case '#': flags |= DP_F_NUM; ch = *format++; break; case '0': flags |= DP_F_ZERO; ch = *format++; break; default: state = DP_S_MIN; break; } break; case DP_S_MIN: if (isdigit((unsigned char)ch)) { min = 10 * min + char_to_int(ch); ch = *format++; } else if (ch == '*') { min = va_arg(args, int); ch = *format++; state = DP_S_DOT; } else state = DP_S_DOT; break; case DP_S_DOT: if (ch == '.') { state = DP_S_MAX; ch = *format++; } else state = DP_S_MOD; break; case DP_S_MAX: if (isdigit((unsigned char)ch)) { if (max < 0) max = 0; max = 10 * max + char_to_int(ch); ch = *format++; } else if (ch == '*') { max = va_arg(args, int); ch = *format++; state = DP_S_MOD; } else state = DP_S_MOD; break; case DP_S_MOD: switch (ch) { case 'h': cflags = DP_C_SHORT; ch = *format++; break; case 'l': if (*format == 'l') { cflags = DP_C_LLONG; format++; } else cflags = DP_C_LONG; ch = *format++; break; case 'q': cflags = DP_C_LLONG; ch = *format++; break; case 'L': cflags = DP_C_LDOUBLE; ch = *format++; break; default: break; } state = DP_S_CONV; break; case DP_S_CONV: switch (ch) { case 'd': case 'i': switch (cflags) { case DP_C_SHORT: value = (short int)va_arg(args, int); break; case DP_C_LONG: value = va_arg(args, long int); break; case DP_C_LLONG: value = va_arg(args, LLONG); break; default: value = va_arg(args, int); value = va_arg(args, int); break; } if (!fmtint(sbuffer, buffer, &currlen, maxlen, value, 10, min, max, flags)) return 0; break; case 'X': flags |= DP_F_UP; case 'o': case 'u': flags |= DP_F_UNSIGNED; switch (cflags) { case DP_C_SHORT: value = (unsigned short int)va_arg(args, unsigned int); break; case DP_C_LONG: value = (LLONG) va_arg(args, unsigned long int); break; case DP_C_LLONG: value = va_arg(args, unsigned LLONG); break; default: value = (LLONG) va_arg(args, unsigned int); break; value = (LLONG) va_arg(args, unsigned int); break; } if (!fmtint(sbuffer, buffer, &currlen, maxlen, value, ch == 'o' ? 8 : (ch == 'u' ? 10 : 16), min, max, flags)) return 0; break; case 'f': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); if (!fmtfp(sbuffer, buffer, &currlen, maxlen, fvalue, min, max, flags)) return 0; break; case 'E': flags |= DP_F_UP; fvalue = va_arg(args, double); break; case 'G': flags |= DP_F_UP; case 'g': if (cflags == DP_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); break; case 'c': doapr_outch(sbuffer, buffer, &currlen, maxlen, fvalue = va_arg(args, double); break; case 'c': if(!doapr_outch(sbuffer, buffer, &currlen, maxlen, va_arg(args, int))) return 0; break; case 's': strvalue = va_arg(args, char *); } fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue, flags, min, max); else max = *maxlen; } if (!fmtstr(sbuffer, buffer, &currlen, maxlen, strvalue, flags, min, max)) return 0; break; case 'p': value = (long)va_arg(args, void *); if (!fmtint(sbuffer, buffer, &currlen, maxlen, value, 16, min, max, flags | DP_F_NUM)) return 0; break; case 'n': /* XXX */ if (cflags == DP_C_SHORT) { } else if (cflags == DP_C_LLONG) { /* XXX */ LLONG *num; num = va_arg(args, LLONG *); *num = (LLONG) currlen; } else { int *num; num = va_arg(args, int *); *num = currlen; } break; case '%': doapr_outch(sbuffer, buffer, &currlen, maxlen, ch); break; case 'w': /* not supported yet, treat as next char */ }
165,183
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck * continually regenerating the same prime values. */ if (bits < 16) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; bitsp = (bits + 1) / 2; bitsq = bits - bitsp; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL)) goto err; if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL)) goto err; if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL)) goto err; if (BN_copy(rsa->e, e_value) == NULL) goto err; BN_set_flags(r2, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 0)) goto err; for (;;) { do { if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb)) goto err; } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate n */ if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ { BIGNUM *pr0 = BN_new(); if (pr0 == NULL) goto err; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) { BN_free(pr0); goto err; /* d */ } /* We MUST free pr0 before any further use of r0 */ BN_free(pr0); } { BIGNUM *d = BN_new(); if (d == NULL) goto err; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); if ( /* calculate d mod (p-1) */ !BN_mod(rsa->dmp1, d, r1, ctx) /* calculate d mod (q-1) */ || !BN_mod(rsa->dmq1, d, r2, ctx)) { BN_free(d); goto err; } /* We MUST free d before any further use of rsa->d */ BN_free(d); } { BIGNUM *p = BN_new(); if (p == NULL) goto err; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); /* calculate inverse of q mod p */ if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) { BN_free(p); goto err; } /* We MUST free p before any further use of rsa->p */ BN_free(p); } ok = 1; err: if (ok == -1) { RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN); ok = 0; } if (ctx != NULL) BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; } Commit Message: CWE ID: CWE-327
static int rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp; int bitsp, bitsq, ok = -1, n = 0; BN_CTX *ctx = NULL; unsigned long error = 0; /* * When generating ridiculously small keys, we can get stuck * continually regenerating the same prime values. */ if (bits < 16) { ok = 0; /* we set our own err */ RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, RSA_R_KEY_SIZE_TOO_SMALL); goto err; } ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); r0 = BN_CTX_get(ctx); r1 = BN_CTX_get(ctx); r2 = BN_CTX_get(ctx); r3 = BN_CTX_get(ctx); if (r3 == NULL) goto err; bitsp = (bits + 1) / 2; bitsq = bits - bitsp; /* We need the RSA components non-NULL */ if (!rsa->n && ((rsa->n = BN_new()) == NULL)) goto err; if (!rsa->d && ((rsa->d = BN_secure_new()) == NULL)) goto err; if (!rsa->e && ((rsa->e = BN_new()) == NULL)) goto err; if (!rsa->p && ((rsa->p = BN_secure_new()) == NULL)) goto err; if (!rsa->q && ((rsa->q = BN_secure_new()) == NULL)) goto err; if (!rsa->dmp1 && ((rsa->dmp1 = BN_secure_new()) == NULL)) goto err; if (!rsa->dmq1 && ((rsa->dmq1 = BN_secure_new()) == NULL)) goto err; if (!rsa->iqmp && ((rsa->iqmp = BN_secure_new()) == NULL)) goto err; if (BN_copy(rsa->e, e_value) == NULL) goto err; BN_set_flags(rsa->p, BN_FLG_CONSTTIME); BN_set_flags(rsa->q, BN_FLG_CONSTTIME); BN_set_flags(r2, BN_FLG_CONSTTIME); /* generate p and q */ for (;;) { if (!BN_sub(r2, rsa->p, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 0)) goto err; for (;;) { do { if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, cb)) goto err; } while (BN_cmp(rsa->p, rsa->q) == 0); if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; ERR_set_mark(); if (BN_mod_inverse(r1, r2, rsa->e, ctx) != NULL) { /* GCD == 1 since inverse exists */ break; } error = ERR_peek_last_error(); if (ERR_GET_LIB(error) == ERR_LIB_BN && ERR_GET_REASON(error) == BN_R_NO_INVERSE) { /* GCD != 1 */ ERR_pop_to_mark(); } else { goto err; } if (!BN_GENCB_call(cb, 2, n++)) goto err; } if (!BN_GENCB_call(cb, 3, 1)) goto err; if (BN_cmp(rsa->p, rsa->q) < 0) { tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } /* calculate n */ if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) goto err; /* calculate d */ if (!BN_sub(r1, rsa->p, BN_value_one())) goto err; /* p-1 */ if (!BN_sub(r2, rsa->q, BN_value_one())) goto err; /* q-1 */ if (!BN_mul(r0, r1, r2, ctx)) goto err; /* (p-1)(q-1) */ { BIGNUM *pr0 = BN_new(); if (pr0 == NULL) goto err; BN_with_flags(pr0, r0, BN_FLG_CONSTTIME); if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) { BN_free(pr0); goto err; /* d */ } /* We MUST free pr0 before any further use of r0 */ BN_free(pr0); } { BIGNUM *d = BN_new(); if (d == NULL) goto err; BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME); if ( /* calculate d mod (p-1) */ !BN_mod(rsa->dmp1, d, r1, ctx) /* calculate d mod (q-1) */ || !BN_mod(rsa->dmq1, d, r2, ctx)) { BN_free(d); goto err; } /* We MUST free d before any further use of rsa->d */ BN_free(d); } { BIGNUM *p = BN_new(); if (p == NULL) goto err; BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME); /* calculate inverse of q mod p */ if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) { BN_free(p); goto err; } /* We MUST free p before any further use of rsa->p */ BN_free(p); } ok = 1; err: if (ok == -1) { RSAerr(RSA_F_RSA_BUILTIN_KEYGEN, ERR_LIB_BN); ok = 0; } if (ctx != NULL) BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; }
165,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_gray_to_rgb(pp); this->next->set(this->next, that, pp, pi); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this, image_transform_png_set_gray_to_rgb_set(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { png_set_gray_to_rgb(pp); /* NOTE: this doesn't result in tRNS expansion. */ this->next->set(this->next, that, pp, pi); }
173,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: kadm5_create_principal_3(void *server_handle, kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_policy_ent_rec polent; krb5_boolean have_polent = FALSE; krb5_int32 now; krb5_tl_data *tl_data_tail; unsigned int ret; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); /* * Argument sanity checking, and opening up the DB */ if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || (mask & KADM5_FAIL_AUTH_COUNT)) return KADM5_BAD_MASK; if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; if (entry == NULL) return EINVAL; /* * Check to see if the principal exists */ ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); switch(ret) { case KADM5_UNK_PRINC: break; case 0: kdb_free_entry(handle, kdb, &adb); return KADM5_DUP; default: return ret; } kdb = krb5_db_alloc(handle->context, NULL, sizeof(*kdb)); if (kdb == NULL) return ENOMEM; memset(kdb, 0, sizeof(*kdb)); memset(&adb, 0, sizeof(osa_princ_ent_rec)); /* * If a policy was specified, load it. * If we can not find the one specified return an error */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &polent, &have_polent); if (ret) goto cleanup; } if (password) { ret = passwd_check(handle, password, have_polent ? &polent : NULL, entry->principal); if (ret) goto cleanup; } /* * Start populating the various DB fields, using the * "defaults" for fields that were not specified by the * mask. */ if ((ret = krb5_timeofday(handle->context, &now))) goto cleanup; kdb->magic = KRB5_KDB_MAGIC_NUMBER; kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; else kdb->attributes = handle->params.flags; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; else kdb->max_life = handle->params.max_life; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; else kdb->max_renewable_life = handle->params.max_rlife; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; else kdb->expiration = handle->params.expiration; kdb->pw_expiration = 0; if (have_polent) { if(polent.pw_max_life) kdb->pw_expiration = now + polent.pw_max_life; else kdb->pw_expiration = 0; } if ((mask & KADM5_PW_EXPIRATION)) kdb->pw_expiration = entry->pw_expiration; kdb->last_success = 0; kdb->last_failed = 0; kdb->fail_auth_count = 0; /* this is kind of gross, but in order to free the tl data, I need to free the entire kdb entry, and that will try to free the principal. */ if ((ret = kadm5_copy_principal(handle->context, entry->principal, &(kdb->princ)))) goto cleanup; if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto cleanup; if (mask & KADM5_TL_DATA) { /* splice entry->tl_data onto the front of kdb->tl_data */ for (tl_data_tail = entry->tl_data; tl_data_tail; tl_data_tail = tl_data_tail->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); if( ret ) goto cleanup; } } /* * We need to have setup the TL data, so we have strings, so we can * check enctype policy, which is why we check/initialize ks_tuple * this late. */ ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto cleanup; /* initialize the keys */ ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto cleanup; if (mask & KADM5_KEY_DATA) { /* The client requested no keys for this principal. */ assert(entry->n_key_data == 0); } else if (password) { ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, (mask & KADM5_KVNO)?entry->kvno:1, FALSE, kdb); } else { /* Null password means create with random key (new in 1.8). */ ret = krb5_dbe_crk(handle->context, &master_keyblock, new_ks_tuple, new_n_ks_tuple, FALSE, kdb); } if (ret) goto cleanup; /* Record the master key VNO used to encrypt this entry's keys */ ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto cleanup; ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto cleanup; /* populate the admin-server-specific fields. In the OV server, this used to be in a separate database. Since there's already marshalling code for the admin fields, to keep things simple, I'm going to keep it, and make all the admin stuff occupy a single tl_data record, */ adb.admin_history_kvno = INITIAL_HIST_KVNO; if (mask & KADM5_POLICY) { adb.aux_attributes = KADM5_POLICY; /* this does *not* need to be strdup'ed, because adb is xdr */ /* encoded in osa_adb_create_princ, and not ever freed */ adb.policy = entry->policy; } /* In all cases key and the principal data is set, let the database provider know */ kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; /* store the new db entry */ ret = kdb_put_entry(handle, kdb, &adb); (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); cleanup: free(new_ks_tuple); krb5_db_free_principal(handle->context, kdb); if (have_polent) (void) kadm5_free_policy_ent(handle->lhandle, &polent); return ret; } Commit Message: Check for null kadm5 policy name [CVE-2015-8630] In kadm5_create_principal_3() and kadm5_modify_principal(), check for entry->policy being null when KADM5_POLICY is included in the mask. CVE-2015-8630: In MIT krb5 1.12 and later, an authenticated attacker with permission to modify a principal entry can cause kadmind to dereference a null pointer by supplying a null policy value but including KADM5_POLICY in the mask. CVSSv2 Vector: AV:N/AC:H/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8342 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID:
kadm5_create_principal_3(void *server_handle, kadm5_principal_ent_t entry, long mask, int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, char *password) { krb5_db_entry *kdb; osa_princ_ent_rec adb; kadm5_policy_ent_rec polent; krb5_boolean have_polent = FALSE; krb5_int32 now; krb5_tl_data *tl_data_tail; unsigned int ret; kadm5_server_handle_t handle = server_handle; krb5_keyblock *act_mkey; krb5_kvno act_kvno; int new_n_ks_tuple = 0; krb5_key_salt_tuple *new_ks_tuple = NULL; CHECK_HANDLE(server_handle); krb5_clear_error_message(handle->context); check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); /* * Argument sanity checking, and opening up the DB */ if (entry == NULL) return EINVAL; if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || (mask & KADM5_FAIL_AUTH_COUNT)) return KADM5_BAD_MASK; if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && entry->policy == NULL) return KADM5_BAD_MASK; if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) return KADM5_BAD_MASK; if((mask & ~ALL_PRINC_MASK)) return KADM5_BAD_MASK; /* * Check to see if the principal exists */ ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); switch(ret) { case KADM5_UNK_PRINC: break; case 0: kdb_free_entry(handle, kdb, &adb); return KADM5_DUP; default: return ret; } kdb = krb5_db_alloc(handle->context, NULL, sizeof(*kdb)); if (kdb == NULL) return ENOMEM; memset(kdb, 0, sizeof(*kdb)); memset(&adb, 0, sizeof(osa_princ_ent_rec)); /* * If a policy was specified, load it. * If we can not find the one specified return an error */ if ((mask & KADM5_POLICY)) { ret = get_policy(handle, entry->policy, &polent, &have_polent); if (ret) goto cleanup; } if (password) { ret = passwd_check(handle, password, have_polent ? &polent : NULL, entry->principal); if (ret) goto cleanup; } /* * Start populating the various DB fields, using the * "defaults" for fields that were not specified by the * mask. */ if ((ret = krb5_timeofday(handle->context, &now))) goto cleanup; kdb->magic = KRB5_KDB_MAGIC_NUMBER; kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ if ((mask & KADM5_ATTRIBUTES)) kdb->attributes = entry->attributes; else kdb->attributes = handle->params.flags; if ((mask & KADM5_MAX_LIFE)) kdb->max_life = entry->max_life; else kdb->max_life = handle->params.max_life; if (mask & KADM5_MAX_RLIFE) kdb->max_renewable_life = entry->max_renewable_life; else kdb->max_renewable_life = handle->params.max_rlife; if ((mask & KADM5_PRINC_EXPIRE_TIME)) kdb->expiration = entry->princ_expire_time; else kdb->expiration = handle->params.expiration; kdb->pw_expiration = 0; if (have_polent) { if(polent.pw_max_life) kdb->pw_expiration = now + polent.pw_max_life; else kdb->pw_expiration = 0; } if ((mask & KADM5_PW_EXPIRATION)) kdb->pw_expiration = entry->pw_expiration; kdb->last_success = 0; kdb->last_failed = 0; kdb->fail_auth_count = 0; /* this is kind of gross, but in order to free the tl data, I need to free the entire kdb entry, and that will try to free the principal. */ if ((ret = kadm5_copy_principal(handle->context, entry->principal, &(kdb->princ)))) goto cleanup; if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) goto cleanup; if (mask & KADM5_TL_DATA) { /* splice entry->tl_data onto the front of kdb->tl_data */ for (tl_data_tail = entry->tl_data; tl_data_tail; tl_data_tail = tl_data_tail->tl_data_next) { ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); if( ret ) goto cleanup; } } /* * We need to have setup the TL data, so we have strings, so we can * check enctype policy, which is why we check/initialize ks_tuple * this late. */ ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, &new_n_ks_tuple, &new_ks_tuple); if (ret) goto cleanup; /* initialize the keys */ ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); if (ret) goto cleanup; if (mask & KADM5_KEY_DATA) { /* The client requested no keys for this principal. */ assert(entry->n_key_data == 0); } else if (password) { ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, new_n_ks_tuple, password, (mask & KADM5_KVNO)?entry->kvno:1, FALSE, kdb); } else { /* Null password means create with random key (new in 1.8). */ ret = krb5_dbe_crk(handle->context, &master_keyblock, new_ks_tuple, new_n_ks_tuple, FALSE, kdb); } if (ret) goto cleanup; /* Record the master key VNO used to encrypt this entry's keys */ ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); if (ret) goto cleanup; ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); if (ret) goto cleanup; /* populate the admin-server-specific fields. In the OV server, this used to be in a separate database. Since there's already marshalling code for the admin fields, to keep things simple, I'm going to keep it, and make all the admin stuff occupy a single tl_data record, */ adb.admin_history_kvno = INITIAL_HIST_KVNO; if (mask & KADM5_POLICY) { adb.aux_attributes = KADM5_POLICY; /* this does *not* need to be strdup'ed, because adb is xdr */ /* encoded in osa_adb_create_princ, and not ever freed */ adb.policy = entry->policy; } /* In all cases key and the principal data is set, let the database provider know */ kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; /* store the new db entry */ ret = kdb_put_entry(handle, kdb, &adb); (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, new_n_ks_tuple, new_ks_tuple, password); cleanup: free(new_ks_tuple); krb5_db_free_principal(handle->context, kdb); if (have_polent) (void) kadm5_free_policy_ent(handle->lhandle, &polent); return ret; }
167,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int crypto_rng_init_tfm(struct crypto_tfm *tfm) { struct crypto_rng *rng = __crypto_rng_cast(tfm); struct rng_alg *alg = crypto_rng_alg(rng); struct old_rng_alg *oalg = crypto_old_rng_alg(rng); if (oalg->rng_make_random) { rng->generate = generate; rng->seed = rngapi_reset; rng->seedsize = oalg->seedsize; return 0; } rng->generate = alg->generate; rng->seed = alg->seed; rng->seedsize = alg->seedsize; return 0; } Commit Message: crypto: rng - Remove old low-level rng interface Now that all rng implementations have switched over to the new interface, we can remove the old low-level interface. Signed-off-by: Herbert Xu <[email protected]> CWE ID: CWE-476
static int crypto_rng_init_tfm(struct crypto_tfm *tfm) { return 0; }
167,731
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: png_set_filter_heuristics(png_structp png_ptr, int heuristic_method, int num_weights, png_doublep filter_weights, png_doublep filter_costs) { int i; png_debug(1, "in png_set_filter_heuristics"); if (png_ptr == NULL) return; if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST) { png_warning(png_ptr, "Unknown filter heuristic method"); return; } if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT) { heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED; } if (num_weights < 0 || filter_weights == NULL || heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED) { num_weights = 0; } png_ptr->num_prev_filters = (png_byte)num_weights; png_ptr->heuristic_method = (png_byte)heuristic_method; if (num_weights > 0) { if (png_ptr->prev_filters == NULL) { png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_byte) * num_weights)); /* To make sure that the weighting starts out fairly */ for (i = 0; i < num_weights; i++) { png_ptr->prev_filters[i] = 255; } } if (png_ptr->filter_weights == NULL) { png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * num_weights)); for (i = 0; i < num_weights; i++) { png_ptr->inv_filter_weights[i] = png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; } } for (i = 0; i < num_weights; i++) { if (filter_weights[i] < 0.0) { png_ptr->inv_filter_weights[i] = png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR; } else { png_ptr->inv_filter_weights[i] = (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5); png_ptr->filter_weights[i] = (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5); } } } /* If, in the future, there are other filter methods, this would * need to be based on png_ptr->filter. */ if (png_ptr->filter_costs == NULL) { png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr, (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST)); for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) { png_ptr->inv_filter_costs[i] = png_ptr->filter_costs[i] = PNG_COST_FACTOR; } } /* Here is where we set the relative costs of the different filters. We * should take the desired compression level into account when setting * the costs, so that Paeth, for instance, has a high relative cost at low * compression levels, while it has a lower relative cost at higher * compression settings. The filter types are in order of increasing * relative cost, so it would be possible to do this with an algorithm. */ for (i = 0; i < PNG_FILTER_VALUE_LAST; i++) { if (filter_costs == NULL || filter_costs[i] < 0.0) { png_ptr->inv_filter_costs[i] = png_ptr->filter_costs[i] = PNG_COST_FACTOR; } else if (filter_costs[i] >= 1.0) { png_ptr->inv_filter_costs[i] = (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5); png_ptr->filter_costs[i] = (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5); } } } Commit Message: third_party/libpng: update to 1.2.54 [email protected] BUG=560291 Review URL: https://codereview.chromium.org/1467263003 Cr-Commit-Position: refs/heads/master@{#362298} CWE ID: CWE-119
png_set_filter_heuristics(png_structp png_ptr, int heuristic_method, int num_weights, png_doublep filter_weights, png_doublep filter_costs) { PNG_UNUSED(png_ptr) PNG_UNUSED(heuristic_method) PNG_UNUSED(num_weights) PNG_UNUSED(filter_weights) PNG_UNUSED(filter_costs) }
172,188
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (1) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } } Commit Message: CWE ID: CWE-399
static void mcf_fec_do_tx(mcf_fec_state *s) { uint32_t addr; uint32_t addr; mcf_fec_bd bd; int frame_size; int len, descnt = 0; uint8_t frame[FEC_MAX_FRAME_SIZE]; uint8_t *ptr; ptr = frame; ptr = frame; frame_size = 0; addr = s->tx_descriptor; while (descnt++ < FEC_MAX_DESC) { mcf_fec_read_bd(&bd, addr); DPRINTF("tx_bd %x flags %04x len %d data %08x\n", addr, bd.flags, bd.length, bd.data); /* Run out of descriptors to transmit. */ break; } len = bd.length; if (frame_size + len > FEC_MAX_FRAME_SIZE) { len = FEC_MAX_FRAME_SIZE - frame_size; s->eir |= FEC_INT_BABT; } cpu_physical_memory_read(bd.data, ptr, len); ptr += len; frame_size += len; if (bd.flags & FEC_BD_L) { /* Last buffer in frame. */ DPRINTF("Sending packet\n"); qemu_send_packet(qemu_get_queue(s->nic), frame, len); ptr = frame; frame_size = 0; s->eir |= FEC_INT_TXF; } s->eir |= FEC_INT_TXB; bd.flags &= ~FEC_BD_R; /* Write back the modified descriptor. */ mcf_fec_write_bd(&bd, addr); /* Advance to the next descriptor. */ if ((bd.flags & FEC_BD_W) != 0) { addr = s->etdsr; } else { addr += 8; } }
164,925