instruction
stringclasses
1 value
input
stringlengths
90
9.3k
output
stringlengths
16
15.4k
__index_level_0__
int64
165k
175k
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) { unsigned short type, size, len; /* If resumed session or no custom extensions nothing to do */ if (s->hit || s->cert->srv_ext.meths_count == 0) return 1; if (data >= limit - 2) return 1; n2s(data, len); if (data > limit - len) return 1; while (data <= limit - 4) { n2s(data, type); n2s(data, size); if (data + size > limit) return 1; if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) return 0; data += size; } return 1; } Commit Message: CWE ID: CWE-190
static int ssl_scan_clienthello_custom_tlsext(SSL *s, const unsigned char *data, const unsigned char *limit, int *al) { unsigned short type, size, len; /* If resumed session or no custom extensions nothing to do */ if (s->hit || s->cert->srv_ext.meths_count == 0) return 1; if (limit - data <= 2) return 1; n2s(data, len); if (limit - data < len) return 1; while (limit - data >= 4) { n2s(data, type); n2s(data, size); if (limit - data < size) return 1; if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) return 0; data += size; } return 1; }
165,203
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DataReductionProxySettings::MaybeActivateDataReductionProxy( bool at_startup) { DCHECK(thread_checker_.CalledOnValidThread()); PrefService* prefs = GetOriginalProfilePrefs(); if (!prefs) return; if (spdy_proxy_auth_enabled_.GetValue() && at_startup) { int64_t last_enabled_time = prefs->GetInt64(prefs::kDataReductionProxyLastEnabledTime); if (last_enabled_time != 0) { RecordDaysSinceEnabledMetric( (clock_->Now() - base::Time::FromInternalValue(last_enabled_time)) .InDays()); } int64_t last_savings_cleared_time = prefs->GetInt64( prefs::kDataReductionProxySavingsClearedNegativeSystemClock); if (last_savings_cleared_time != 0) { int32_t days_since_savings_cleared = (clock_->Now() - base::Time::FromInternalValue(last_savings_cleared_time)) .InDays(); if (days_since_savings_cleared == 0) days_since_savings_cleared = 1; UMA_HISTOGRAM_CUSTOM_COUNTS( "DataReductionProxy.DaysSinceSavingsCleared.NegativeSystemClock", days_since_savings_cleared, 1, 365, 50); } } if (spdy_proxy_auth_enabled_.GetValue() && !prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) { prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true); ResetDataReductionStatistics(); } if (!at_startup) { if (IsDataReductionProxyEnabled()) { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON); prefs->SetInt64(prefs::kDataReductionProxyLastEnabledTime, clock_->Now().ToInternalValue()); RecordDaysSinceEnabledMetric(0); } else { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF); } } if (at_startup && !data_reduction_proxy_service_->Initialized()) deferred_initialization_ = true; else UpdateIOData(at_startup); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Reviewed-by: Tarun Bansal <tbansal@chromium.org> Commit-Queue: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
void DataReductionProxySettings::MaybeActivateDataReductionProxy( bool at_startup) { DCHECK(thread_checker_.CalledOnValidThread()); PrefService* prefs = GetOriginalProfilePrefs(); if (!prefs) return; bool enabled = IsDataSaverEnabledByUser(prefs); if (enabled && at_startup) { int64_t last_enabled_time = prefs->GetInt64(prefs::kDataReductionProxyLastEnabledTime); if (last_enabled_time != 0) { RecordDaysSinceEnabledMetric( (clock_->Now() - base::Time::FromInternalValue(last_enabled_time)) .InDays()); } int64_t last_savings_cleared_time = prefs->GetInt64( prefs::kDataReductionProxySavingsClearedNegativeSystemClock); if (last_savings_cleared_time != 0) { int32_t days_since_savings_cleared = (clock_->Now() - base::Time::FromInternalValue(last_savings_cleared_time)) .InDays(); if (days_since_savings_cleared == 0) days_since_savings_cleared = 1; UMA_HISTOGRAM_CUSTOM_COUNTS( "DataReductionProxy.DaysSinceSavingsCleared.NegativeSystemClock", days_since_savings_cleared, 1, 365, 50); } } if (enabled && !prefs->GetBoolean(prefs::kDataReductionProxyWasEnabledBefore)) { prefs->SetBoolean(prefs::kDataReductionProxyWasEnabledBefore, true); ResetDataReductionStatistics(); } if (!at_startup) { if (IsDataReductionProxyEnabled()) { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_OFF_TO_ON); prefs->SetInt64(prefs::kDataReductionProxyLastEnabledTime, clock_->Now().ToInternalValue()); RecordDaysSinceEnabledMetric(0); } else { RecordSettingsEnabledState(DATA_REDUCTION_SETTINGS_ACTION_ON_TO_OFF); } } if (at_startup && !data_reduction_proxy_service_->Initialized()) deferred_initialization_ = true; else UpdateIOData(at_startup); }
172,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: krb5_gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size) OM_uint32 *minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; OM_uint32 req_output_size; OM_uint32 *max_input_size; { krb5_gss_ctx_id_rec *ctx; OM_uint32 data_size, conflen; OM_uint32 ohlen; int overhead; /* only default qop is allowed */ if (qop_req != GSS_C_QOP_DEFAULT) { *minor_status = (OM_uint32) G_UNKNOWN_QOP; return(GSS_S_FAILURE); } ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } if (ctx->proto == 1) { /* No pseudo-ASN.1 wrapper overhead, so no sequence length and OID. */ OM_uint32 sz = req_output_size; /* Token header: 16 octets. */ if (conf_req_flag) { krb5_key key; krb5_enctype enctype; key = ctx->have_acceptor_subkey ? ctx->acceptor_subkey : ctx->subkey; enctype = key->keyblock.enctype; while (sz > 0 && krb5_encrypt_size(sz, enctype) + 16 > req_output_size) sz--; /* Allow for encrypted copy of header. */ if (sz > 16) sz -= 16; else sz = 0; #ifdef CFX_EXERCISE /* Allow for EC padding. In the MIT implementation, only added while testing. */ if (sz > 65535) sz -= 65535; else sz = 0; #endif } else { krb5_cksumtype cksumtype; krb5_error_code err; size_t cksumsize; cksumtype = ctx->have_acceptor_subkey ? ctx->acceptor_subkey_cksumtype : ctx->cksumtype; err = krb5_c_checksum_length(ctx->k5_context, cksumtype, &cksumsize); if (err) { *minor_status = err; return GSS_S_FAILURE; } /* Allow for token header and checksum. */ if (sz < 16 + cksumsize) sz = 0; else sz -= (16 + cksumsize); } *max_input_size = sz; *minor_status = 0; return GSS_S_COMPLETE; } /* Calculate the token size and subtract that from the output size */ overhead = 7 + ctx->mech_used->length; data_size = req_output_size; conflen = kg_confounder_size(ctx->k5_context, ctx->enc->keyblock.enctype); data_size = (conflen + data_size + 8) & (~(OM_uint32)7); ohlen = g_token_size(ctx->mech_used, (unsigned int) (data_size + ctx->cksum_size + 14)) - req_output_size; if (ohlen+overhead < req_output_size) /* * Cannot have trailer length that will cause us to pad over our * length. */ *max_input_size = (req_output_size - ohlen - overhead) & (~(OM_uint32)7); else *max_input_size = 0; *minor_status = 0; return(GSS_S_COMPLETE); } Commit Message: Fix gss_process_context_token() [CVE-2014-5352] [MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not actually delete the context; that leaves the caller with a dangling pointer and no way to know that it is invalid. Instead, mark the context as terminated, and check for terminated contexts in the GSS functions which expect established contexts. Also add checks in export_sec_context and pseudo_random, and adjust t_prf.c for the pseudo_random check. ticket: 8055 (new) target_version: 1.13.1 tags: pullup CWE ID:
krb5_gss_wrap_size_limit(minor_status, context_handle, conf_req_flag, qop_req, req_output_size, max_input_size) OM_uint32 *minor_status; gss_ctx_id_t context_handle; int conf_req_flag; gss_qop_t qop_req; OM_uint32 req_output_size; OM_uint32 *max_input_size; { krb5_gss_ctx_id_rec *ctx; OM_uint32 data_size, conflen; OM_uint32 ohlen; int overhead; /* only default qop is allowed */ if (qop_req != GSS_C_QOP_DEFAULT) { *minor_status = (OM_uint32) G_UNKNOWN_QOP; return(GSS_S_FAILURE); } ctx = (krb5_gss_ctx_id_rec *) context_handle; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } if (ctx->proto == 1) { /* No pseudo-ASN.1 wrapper overhead, so no sequence length and OID. */ OM_uint32 sz = req_output_size; /* Token header: 16 octets. */ if (conf_req_flag) { krb5_key key; krb5_enctype enctype; key = ctx->have_acceptor_subkey ? ctx->acceptor_subkey : ctx->subkey; enctype = key->keyblock.enctype; while (sz > 0 && krb5_encrypt_size(sz, enctype) + 16 > req_output_size) sz--; /* Allow for encrypted copy of header. */ if (sz > 16) sz -= 16; else sz = 0; #ifdef CFX_EXERCISE /* Allow for EC padding. In the MIT implementation, only added while testing. */ if (sz > 65535) sz -= 65535; else sz = 0; #endif } else { krb5_cksumtype cksumtype; krb5_error_code err; size_t cksumsize; cksumtype = ctx->have_acceptor_subkey ? ctx->acceptor_subkey_cksumtype : ctx->cksumtype; err = krb5_c_checksum_length(ctx->k5_context, cksumtype, &cksumsize); if (err) { *minor_status = err; return GSS_S_FAILURE; } /* Allow for token header and checksum. */ if (sz < 16 + cksumsize) sz = 0; else sz -= (16 + cksumsize); } *max_input_size = sz; *minor_status = 0; return GSS_S_COMPLETE; } /* Calculate the token size and subtract that from the output size */ overhead = 7 + ctx->mech_used->length; data_size = req_output_size; conflen = kg_confounder_size(ctx->k5_context, ctx->enc->keyblock.enctype); data_size = (conflen + data_size + 8) & (~(OM_uint32)7); ohlen = g_token_size(ctx->mech_used, (unsigned int) (data_size + ctx->cksum_size + 14)) - req_output_size; if (ohlen+overhead < req_output_size) /* * Cannot have trailer length that will cause us to pad over our * length. */ *max_input_size = (req_output_size - ohlen - overhead) & (~(OM_uint32)7); else *max_input_size = 0; *minor_status = 0; return(GSS_S_COMPLETE); }
166,824
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: usage(const char *prog) { fprintf(stderr, "Usage: %s [OPTION...]\n", prog); fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n"); #if defined _WITH_VRRP_ && defined _WITH_LVS_ fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n"); fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n"); #endif fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n"); fprintf(stderr, " -l, --log-console Log messages to local console\n"); fprintf(stderr, " -D, --log-detail Detailed log messages\n"); fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n"); fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n"); fprintf(stderr, " --flush-log-file Flush log file on write\n"); fprintf(stderr, " -G, --no-syslog Don't log via syslog\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n"); fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n"); #endif fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n"); fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n"); fprintf(stderr, " -d, --dump-conf Dump the configuration data\n"); fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n"); fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n"); #endif #ifdef _WITH_SNMP_ fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n"); fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n"); #endif #if HAVE_DECL_CLONE_NEWNET fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n"); #endif fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n"); fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n"); #ifdef _MEM_CHECK_LOG_ fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n"); #endif fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n" " or any lines beginning @^ that do match.\n" " The config-id defaults to the node name if option not used\n"); fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS" #ifdef _WITH_JSON_ ", JSON" #endif "\n"); fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n" " stderr by default\n"); #ifdef _WITH_PERF_ fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n"); #endif #ifdef WITH_DEBUG_OPTIONS fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n"); #ifdef _TIMER_CHECK_ fprintf(stderr, " T - timer debug\n"); #endif #ifdef _SMTP_ALERT_DEBUG_ fprintf(stderr, " M - email alert debug\n"); #endif #ifdef _EPOLL_DEBUG_ fprintf(stderr, " E - epoll debug\n"); #endif #ifdef _EPOLL_THREAD_DUMP_ fprintf(stderr, " D - epoll thread dump debug\n"); #endif #ifdef _VRRP_FD_DEBUG fprintf(stderr, " F - vrrp fd dump debug\n"); #endif #ifdef _REGEX_DEBUG_ fprintf(stderr, " R - regex debug\n"); #endif #ifdef _WITH_REGEX_TIMERS_ fprintf(stderr, " X - regex timers\n"); #endif #ifdef _TSM_DEBUG_ fprintf(stderr, " S - TSM debug\n"); #endif #ifdef _NETLINK_TIMERS_ fprintf(stderr, " N - netlink timer debug\n"); #endif fprintf(stderr, " Example --debug=TpMEvcp\n"); #endif fprintf(stderr, " -v, --version Display the version number\n"); fprintf(stderr, " -h, --help Display this help message\n"); } 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 <quentin@armitage.org.uk> CWE ID: CWE-200
usage(const char *prog) { fprintf(stderr, "Usage: %s [OPTION...]\n", prog); fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n"); #if defined _WITH_VRRP_ && defined _WITH_LVS_ fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n"); fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n"); #endif fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n"); fprintf(stderr, " -l, --log-console Log messages to local console\n"); fprintf(stderr, " -D, --log-detail Detailed log messages\n"); fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n"); fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n"); fprintf(stderr, " --flush-log-file Flush log file on write\n"); fprintf(stderr, " -G, --no-syslog Don't log via syslog\n"); fprintf(stderr, " -u, --umask=MASK umask for file creation (in numeric form)\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n"); fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n"); #endif fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n"); fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n"); fprintf(stderr, " -d, --dump-conf Dump the configuration data\n"); fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n"); fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n"); #endif #ifdef _WITH_SNMP_ fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n"); fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n"); #endif #if HAVE_DECL_CLONE_NEWNET fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n"); #endif fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n"); fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n"); #ifdef _MEM_CHECK_LOG_ fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n"); #endif fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n" " or any lines beginning @^ that do match.\n" " The config-id defaults to the node name if option not used\n"); fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS" #ifdef _WITH_JSON_ ", JSON" #endif "\n"); fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n" " stderr by default\n"); #ifdef _WITH_PERF_ fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n"); #endif #ifdef WITH_DEBUG_OPTIONS fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n"); #ifdef _TIMER_CHECK_ fprintf(stderr, " T - timer debug\n"); #endif #ifdef _SMTP_ALERT_DEBUG_ fprintf(stderr, " M - email alert debug\n"); #endif #ifdef _EPOLL_DEBUG_ fprintf(stderr, " E - epoll debug\n"); #endif #ifdef _EPOLL_THREAD_DUMP_ fprintf(stderr, " D - epoll thread dump debug\n"); #endif #ifdef _VRRP_FD_DEBUG fprintf(stderr, " F - vrrp fd dump debug\n"); #endif #ifdef _REGEX_DEBUG_ fprintf(stderr, " R - regex debug\n"); #endif #ifdef _WITH_REGEX_TIMERS_ fprintf(stderr, " X - regex timers\n"); #endif #ifdef _TSM_DEBUG_ fprintf(stderr, " S - TSM debug\n"); #endif #ifdef _NETLINK_TIMERS_ fprintf(stderr, " N - netlink timer debug\n"); #endif fprintf(stderr, " Example --debug=TpMEvcp\n"); #endif fprintf(stderr, " -v, --version Display the version number\n"); fprintf(stderr, " -h, --help Display this help message\n"); }
168,984
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InternalWebIntentsDispatcherTest() { replied_ = 0; } Commit Message: Fix uninitialized member in ctor. TBR=darin@chromium.org R=jhawkins@chromium.org BUG=none TEST=none Review URL: https://chromiumcodereview.appspot.com/10377180 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137606 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
InternalWebIntentsDispatcherTest() { InternalWebIntentsDispatcherTest() : replied_(0), notified_reply_type_(webkit_glue::WEB_INTENT_REPLY_INVALID) { }
170,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig, siginfo_t __user *, uinfo) { siginfo_t info; if (copy_from_user(&info, uinfo, sizeof(siginfo_t))) return -EFAULT; /* Not even root can pretend to send signals from the kernel. Nor can they impersonate a kill(), which adds source info. */ if (info.si_code >= 0) return -EPERM; info.si_signo = sig; /* POSIX.1b doesn't mention process groups. */ return kill_proc_info(sig, &info, pid); } Commit Message: Prevent rt_sigqueueinfo and rt_tgsigqueueinfo from spoofing the signal code Userland should be able to trust the pid and uid of the sender of a signal if the si_code is SI_TKILL. Unfortunately, the kernel has historically allowed sigqueueinfo() to send any si_code at all (as long as it was negative - to distinguish it from kernel-generated signals like SIGILL etc), so it could spoof a SI_TKILL with incorrect siginfo values. Happily, it looks like glibc has always set si_code to the appropriate SI_QUEUE, so there are probably no actual user code that ever uses anything but the appropriate SI_QUEUE flag. So just tighten the check for si_code (we used to allow any negative value), and add a (one-time) warning in case there are binaries out there that might depend on using other si_code values. Signed-off-by: Julien Tinnes <jln@google.com> Acked-by: Oleg Nesterov <oleg@redhat.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> CWE ID:
SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig, siginfo_t __user *, uinfo) { siginfo_t info; if (copy_from_user(&info, uinfo, sizeof(siginfo_t))) return -EFAULT; /* Not even root can pretend to send signals from the kernel. * Nor can they impersonate a kill()/tgkill(), which adds source info. */ if (info.si_code != SI_QUEUE) { /* We used to allow any < 0 si_code */ WARN_ON_ONCE(info.si_code < 0); return -EPERM; } info.si_signo = sig; /* POSIX.1b doesn't mention process groups. */ return kill_proc_info(sig, &info, pid); }
166,231
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static size_t ZSTD_encodeSequences( void* dst, size_t dstCapacity, FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2) { #if DYNAMIC_BMI2 if (bmi2) { return ZSTD_encodeSequences_bmi2(dst, dstCapacity, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets); } #endif (void)bmi2; return ZSTD_encodeSequences_default(dst, dstCapacity, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets); } Commit Message: fixed T36302429 CWE ID: CWE-362
static size_t ZSTD_encodeSequences( void* dst, size_t dstCapacity, FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2) { DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity); #if DYNAMIC_BMI2 if (bmi2) { return ZSTD_encodeSequences_bmi2(dst, dstCapacity, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets); } #endif (void)bmi2; return ZSTD_encodeSequences_default(dst, dstCapacity, CTable_MatchLength, mlCodeTable, CTable_OffsetBits, ofCodeTable, CTable_LitLength, llCodeTable, sequences, nbSeq, longOffsets); }
169,673
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, void *hba_private) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); SCSIRequest *req; SCSIDiskReq *r; req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private); r = DO_UPCAST(SCSIDiskReq, req, req); r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE); return req; } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Kevin Wolf <kwolf@redhat.com> CWE ID: CWE-119
static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag, uint32_t lun, void *hba_private) { SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d); SCSIRequest *req; req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private); return req; }
166,555
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltFreeTemplateHashes(xsltStylesheetPtr style) { if (style->templatesHash != NULL) xmlHashFree((xmlHashTablePtr) style->templatesHash, (xmlHashDeallocator) xsltFreeCompMatchList); if (style->rootMatch != NULL) xsltFreeCompMatchList(style->rootMatch); if (style->keyMatch != NULL) xsltFreeCompMatchList(style->keyMatch); if (style->elemMatch != NULL) xsltFreeCompMatchList(style->elemMatch); if (style->attrMatch != NULL) xsltFreeCompMatchList(style->attrMatch); if (style->parentMatch != NULL) xsltFreeCompMatchList(style->parentMatch); if (style->textMatch != NULL) xsltFreeCompMatchList(style->textMatch); if (style->piMatch != NULL) xsltFreeCompMatchList(style->piMatch); if (style->commentMatch != NULL) xsltFreeCompMatchList(style->commentMatch); } 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
xsltFreeTemplateHashes(xsltStylesheetPtr style) { if (style->templatesHash != NULL) xmlHashFree((xmlHashTablePtr) style->templatesHash, (xmlHashDeallocator) xsltFreeCompMatchList); if (style->rootMatch != NULL) xsltFreeCompMatchList(style->rootMatch); if (style->keyMatch != NULL) xsltFreeCompMatchList(style->keyMatch); if (style->elemMatch != NULL) xsltFreeCompMatchList(style->elemMatch); if (style->attrMatch != NULL) xsltFreeCompMatchList(style->attrMatch); if (style->parentMatch != NULL) xsltFreeCompMatchList(style->parentMatch); if (style->textMatch != NULL) xsltFreeCompMatchList(style->textMatch); if (style->piMatch != NULL) xsltFreeCompMatchList(style->piMatch); if (style->commentMatch != NULL) xsltFreeCompMatchList(style->commentMatch); if (style->namedTemplates != NULL) xmlHashFree(style->namedTemplates, NULL); }
173,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rdpsnddbg_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = (char *) xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, rdpsnddbg_line_handler, NULL); xfree(buf); } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
rdpsnddbg_process(STREAM s) { unsigned int pkglen; static char *rest = NULL; char *buf; if (!s_check(s)) { rdp_protocol_error("rdpsnddbg_process(), stream is in unstable state", s); } pkglen = s->end - s->p; /* str_handle_lines requires null terminated strings */ buf = (char *) xmalloc(pkglen + 1); STRNCPY(buf, (char *) s->p, pkglen + 1); str_handle_lines(buf, &rest, rdpsnddbg_line_handler, NULL); xfree(buf); }
169,807
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), #if defined(OS_WIN) accessible_parent_(NULL), #endif frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), is_loading_(false), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), displayed_insecure_content_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), is_being_destroyed_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), render_view_message_source_(NULL), render_frame_message_source_(NULL), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), virtual_keyboard_requested_(false), page_scale_factor_is_one_(true), loading_weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); wake_lock_service_context_.reset(new WakeLockServiceContext(this)); } Commit Message: Don't call WebContents::DownloadImage() callback if the WebContents were deleted BUG=583718 Review URL: https://codereview.chromium.org/1685343004 Cr-Commit-Position: refs/heads/master@{#375700} CWE ID:
WebContentsImpl::WebContentsImpl(BrowserContext* browser_context) : delegate_(NULL), controller_(this, browser_context), render_view_host_delegate_view_(NULL), created_with_opener_(false), #if defined(OS_WIN) accessible_parent_(NULL), #endif frame_tree_(new NavigatorImpl(&controller_, this), this, this, this, this), is_loading_(false), is_load_to_different_document_(false), crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING), crashed_error_code_(0), waiting_for_response_(false), load_state_(net::LOAD_STATE_IDLE, base::string16()), upload_size_(0), upload_position_(0), is_resume_pending_(false), displayed_insecure_content_(false), has_accessed_initial_document_(false), theme_color_(SK_ColorTRANSPARENT), last_sent_theme_color_(SK_ColorTRANSPARENT), did_first_visually_non_empty_paint_(false), capturer_count_(0), should_normally_be_visible_(true), is_being_destroyed_(false), notify_disconnection_(false), dialog_manager_(NULL), is_showing_before_unload_dialog_(false), last_active_time_(base::TimeTicks::Now()), closed_by_user_gesture_(false), minimum_zoom_percent_(static_cast<int>(kMinimumZoomFactor * 100)), maximum_zoom_percent_(static_cast<int>(kMaximumZoomFactor * 100)), zoom_scroll_remainder_(0), render_view_message_source_(NULL), render_frame_message_source_(NULL), fullscreen_widget_routing_id_(MSG_ROUTING_NONE), fullscreen_widget_had_focus_at_shutdown_(false), is_subframe_(false), force_disable_overscroll_content_(false), last_dialog_suppressed_(false), geolocation_service_context_(new GeolocationServiceContext()), accessibility_mode_( BrowserAccessibilityStateImpl::GetInstance()->accessibility_mode()), audio_stream_monitor_(this), virtual_keyboard_requested_(false), page_scale_factor_is_one_(true), loading_weak_factory_(this), weak_factory_(this) { frame_tree_.SetFrameRemoveListener( base::Bind(&WebContentsImpl::OnFrameRemoved, base::Unretained(this))); #if defined(OS_ANDROID) media_web_contents_observer_.reset(new MediaWebContentsObserverAndroid(this)); #else media_web_contents_observer_.reset(new MediaWebContentsObserver(this)); #endif loader_io_thread_notifier_.reset(new LoaderIOThreadNotifier(this)); wake_lock_service_context_.reset(new WakeLockServiceContext(this)); }
172,211
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool InputMethodController::FinishComposingText( ConfirmCompositionBehavior confirm_behavior) { if (!HasComposition()) return false; const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition()); const String& composing = ComposingText(); if (confirm_behavior == kKeepSelection) { const bool is_handle_visible = GetFrame().Selection().IsHandleVisible(); const PlainTextRange& old_offsets = GetSelectionOffsets(); Editor::RevealSelectionScope reveal_selection_scope(&GetEditor()); if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); DispatchCompositionEndEvent(GetFrame(), composing); } GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& old_selection_range = EphemeralRangeForOffsets(old_offsets); if (old_selection_range.IsNull()) return false; const SelectionInDOMTree& selection = SelectionInDOMTree::Builder() .SetBaseAndExtent(old_selection_range) .SetIsHandleVisible(is_handle_visible) .Build(); GetFrame().Selection().SetSelection( selection, SetSelectionData::Builder().SetShouldCloseTyping(true).Build()); return true; } Element* root_editable_element = GetFrame() .Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .RootEditableElement(); if (!root_editable_element) return false; PlainTextRange composition_range = PlainTextRange::Create(*root_editable_element, *composition_range_); if (composition_range.IsNull()) return false; if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); } if (!MoveCaret(composition_range.End())) return false; DispatchCompositionEndEvent(GetFrame(), composing); return true; } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <yosin@chromium.org> Reviewed-by: Xiaocheng Hu <xiaochengh@chromium.org> Reviewed-by: Kent Tamura <tkent@chromium.org> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
bool InputMethodController::FinishComposingText( ConfirmCompositionBehavior confirm_behavior) { if (!HasComposition()) return false; const bool is_too_long = IsTextTooLongAt(composition_range_->StartPosition()); const String& composing = ComposingText(); if (confirm_behavior == kKeepSelection) { const bool is_handle_visible = GetFrame().Selection().IsHandleVisible(); const PlainTextRange& old_offsets = GetSelectionOffsets(); Editor::RevealSelectionScope reveal_selection_scope(&GetEditor()); if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); DispatchCompositionEndEvent(GetFrame(), composing); } GetDocument().UpdateStyleAndLayoutIgnorePendingStylesheets(); const EphemeralRange& old_selection_range = EphemeralRangeForOffsets(old_offsets); if (old_selection_range.IsNull()) return false; const SelectionInDOMTree& selection = SelectionInDOMTree::Builder() .SetBaseAndExtent(old_selection_range) .Build(); GetFrame().Selection().SetSelection( selection, SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldShowHandle(is_handle_visible) .Build()); return true; } Element* root_editable_element = GetFrame() .Selection() .ComputeVisibleSelectionInDOMTreeDeprecated() .RootEditableElement(); if (!root_editable_element) return false; PlainTextRange composition_range = PlainTextRange::Create(*root_editable_element, *composition_range_); if (composition_range.IsNull()) return false; if (is_too_long) { ReplaceComposition(ComposingText()); } else { Clear(); } if (!MoveCaret(composition_range.End())) return false; DispatchCompositionEndEvent(GetFrame(), composing); return true; }
171,761
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ExtensionOptionsGuest::DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { if (attached()) { auto guest_zoom_controller = ui_zoom::ZoomController::FromWebContents(web_contents()); guest_zoom_controller->SetZoomMode( ui_zoom::ZoomController::ZOOM_MODE_ISOLATED); SetGuestZoomLevelToMatchEmbedder(); if (params.url.GetOrigin() != options_page_.GetOrigin()) { bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(), bad_message::EOG_BAD_ORIGIN); } } } Commit Message: Make extensions use a correct same-origin check. GURL::GetOrigin does not do the right thing for all types of URLs. BUG=573317 Review URL: https://codereview.chromium.org/1658913002 Cr-Commit-Position: refs/heads/master@{#373381} CWE ID: CWE-284
void ExtensionOptionsGuest::DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { if (attached()) { auto guest_zoom_controller = ui_zoom::ZoomController::FromWebContents(web_contents()); guest_zoom_controller->SetZoomMode( ui_zoom::ZoomController::ZOOM_MODE_ISOLATED); SetGuestZoomLevelToMatchEmbedder(); if (!url::IsSameOriginWith(params.url, options_page_)) { bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(), bad_message::EOG_BAD_ORIGIN); } } }
172,282
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int svc_rdma_init(void) { dprintk("SVCRDMA Module Init, register RPC RDMA transport\n"); dprintk("\tsvcrdma_ord : %d\n", svcrdma_ord); dprintk("\tmax_requests : %u\n", svcrdma_max_requests); dprintk("\tsq_depth : %u\n", svcrdma_max_requests * RPCRDMA_SQ_DEPTH_MULT); dprintk("\tmax_bc_requests : %u\n", svcrdma_max_bc_requests); dprintk("\tmax_inline : %d\n", svcrdma_max_req_size); svc_rdma_wq = alloc_workqueue("svc_rdma", 0, 0); if (!svc_rdma_wq) return -ENOMEM; if (!svcrdma_table_header) svcrdma_table_header = register_sysctl_table(svcrdma_root_table); /* Register RDMA with the SVC transport switch */ svc_reg_xprt_class(&svc_rdma_class); #if defined(CONFIG_SUNRPC_BACKCHANNEL) svc_reg_xprt_class(&svc_rdma_bc_class); #endif return 0; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
int svc_rdma_init(void) { dprintk("SVCRDMA Module Init, register RPC RDMA transport\n"); dprintk("\tsvcrdma_ord : %d\n", svcrdma_ord); dprintk("\tmax_requests : %u\n", svcrdma_max_requests); dprintk("\tmax_bc_requests : %u\n", svcrdma_max_bc_requests); dprintk("\tmax_inline : %d\n", svcrdma_max_req_size); svc_rdma_wq = alloc_workqueue("svc_rdma", 0, 0); if (!svc_rdma_wq) return -ENOMEM; if (!svcrdma_table_header) svcrdma_table_header = register_sysctl_table(svcrdma_root_table); /* Register RDMA with the SVC transport switch */ svc_reg_xprt_class(&svc_rdma_class); #if defined(CONFIG_SUNRPC_BACKCHANNEL) svc_reg_xprt_class(&svc_rdma_bc_class); #endif return 0; }
168,156
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } }
167,032
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC) { int i; enum entity_charset charset = cs_utf_8; int len = 0; const zend_encoding *zenc; /* Default is now UTF-8 */ if (charset_hint == NULL) return cs_utf_8; if ((len = strlen(charset_hint)) != 0) { goto det_charset; } zenc = zend_multibyte_get_internal_encoding(TSRMLS_C); if (zenc != NULL) { charset_hint = (char *)zend_multibyte_get_encoding_name(zenc); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { if ((len == 4) /* sizeof (none|auto|pass) */ && (!memcmp("pass", charset_hint, 4) || !memcmp("auto", charset_hint, 4) || !memcmp("auto", charset_hint, 4))) { charset_hint = NULL; len = 0; } else { goto det_charset; } } } charset_hint = SG(default_charset); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } /* try to detect the charset for the locale */ #if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET) charset_hint = nl_langinfo(CODESET); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } #endif #if HAVE_LOCALE_H /* try to figure out the charset from the locale */ { char *localename; char *dot, *at; /* lang[_territory][.codeset][@modifier] */ localename = setlocale(LC_CTYPE, NULL); dot = strchr(localename, '.'); if (dot) { dot++; /* locale specifies a codeset */ at = strchr(dot, '@'); if (at) len = at - dot; else len = strlen(dot); charset_hint = dot; } else { /* no explicit name; see if the name itself * is the charset */ charset_hint = localename; len = strlen(charset_hint); } } #endif det_charset: if (charset_hint) { int found = 0; /* now walk the charset map and look for the codeset */ for (i = 0; charset_map[i].codeset; i++) { if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) { charset = charset_map[i].charset; found = 1; break; } } if (!found) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8", charset_hint); } } return charset; } Commit Message: Fix bug #72135 - don't create strings with lengths outside int range CWE ID: CWE-190
static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC) { int i; enum entity_charset charset = cs_utf_8; int len = 0; const zend_encoding *zenc; /* Default is now UTF-8 */ if (charset_hint == NULL) return cs_utf_8; if ((len = strlen(charset_hint)) != 0) { goto det_charset; } zenc = zend_multibyte_get_internal_encoding(TSRMLS_C); if (zenc != NULL) { charset_hint = (char *)zend_multibyte_get_encoding_name(zenc); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { if ((len == 4) /* sizeof (none|auto|pass) */ && (!memcmp("pass", charset_hint, 4) || !memcmp("auto", charset_hint, 4) || !memcmp("auto", charset_hint, 4))) { charset_hint = NULL; len = 0; } else { goto det_charset; } } } charset_hint = SG(default_charset); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } /* try to detect the charset for the locale */ #if HAVE_NL_LANGINFO && HAVE_LOCALE_H && defined(CODESET) charset_hint = nl_langinfo(CODESET); if (charset_hint != NULL && (len=strlen(charset_hint)) != 0) { goto det_charset; } #endif #if HAVE_LOCALE_H /* try to figure out the charset from the locale */ { char *localename; char *dot, *at; /* lang[_territory][.codeset][@modifier] */ localename = setlocale(LC_CTYPE, NULL); dot = strchr(localename, '.'); if (dot) { dot++; /* locale specifies a codeset */ at = strchr(dot, '@'); if (at) len = at - dot; else len = strlen(dot); charset_hint = dot; } else { /* no explicit name; see if the name itself * is the charset */ charset_hint = localename; len = strlen(charset_hint); } } #endif det_charset: if (charset_hint) { int found = 0; /* now walk the charset map and look for the codeset */ for (i = 0; charset_map[i].codeset; i++) { if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) { charset = charset_map[i].charset; found = 1; break; } } if (!found) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "charset `%s' not supported, assuming utf-8", charset_hint); } } return charset; }
167,169
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CrosLibrary::TestApi::SetLoginLibrary( LoginLibrary* library, bool own) { library_->login_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetLoginLibrary(
170,640
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ztype(i_ctx_t *i_ctx_p) { os_ptr op = osp; ref tnref; int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref); if (code < 0) return code; if (!r_has_type(&tnref, t_name)) { /* Must be either a stack underflow or a t_[a]struct. */ check_op(2); { /* Get the type name from the structure. */ if (op[-1].value.pstruct != 0x00) { const char *sname = gs_struct_type_name_string(gs_object_type(imemory, op[-1].value.pstruct)); int code = name_ref(imemory, (const byte *)sname, strlen(sname), (ref *) (op - 1), 0); if (code < 0) return code; } else return_error(gs_error_stackunderflow); } r_set_attrs(op - 1, a_executable); } else { ref_assign(op - 1, &tnref); } pop(1); return 0; } Commit Message: CWE ID: CWE-704
ztype(i_ctx_t *i_ctx_p) { os_ptr op = osp; ref tnref; int code = array_get(imemory, op, (long)r_btype(op - 1), &tnref); if (code < 0) return code; if (!r_has_type(&tnref, t_name)) { /* Must be either a stack underflow or a t_[a]struct. */ check_op(2); { /* Get the type name from the structure. */ if ((r_has_type(&op[-1], t_struct) || r_has_type(&op[-1], t_astruct)) && op[-1].value.pstruct != 0x00) { const char *sname = gs_struct_type_name_string(gs_object_type(imemory, op[-1].value.pstruct)); int code = name_ref(imemory, (const byte *)sname, strlen(sname), (ref *) (op - 1), 0); if (code < 0) return code; } else return_error(gs_error_stackunderflow); } r_set_attrs(op - 1, a_executable); } else { ref_assign(op - 1, &tnref); } pop(1); return 0; }
164,698
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { switch (hdev->product) { case USB_DEVICE_ID_KYE_ERGO_525V: /* the fixups that need to be done: * - change led usage page to button for extra buttons * - report size 8 count 1 must be size 1 count 8 for button * bitfield * - change the button usage range to 4-7 for the extra * buttons */ if (*rsize >= 74 && rdesc[61] == 0x05 && rdesc[62] == 0x08 && rdesc[63] == 0x19 && rdesc[64] == 0x08 && rdesc[65] == 0x29 && rdesc[66] == 0x0f && rdesc[71] == 0x75 && rdesc[72] == 0x08 && rdesc[73] == 0x95 && rdesc[74] == 0x01) { hid_info(hdev, "fixing up Kye/Genius Ergo Mouse " "report descriptor\n"); rdesc[62] = 0x09; rdesc[64] = 0x04; rdesc[66] = 0x07; rdesc[72] = 0x01; rdesc[74] = 0x08; } break; case USB_DEVICE_ID_KYE_EASYPEN_I405X: if (*rsize == EASYPEN_I405X_RDESC_ORIG_SIZE) { rdesc = easypen_i405x_rdesc_fixed; *rsize = sizeof(easypen_i405x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_MOUSEPEN_I608X: if (*rsize == MOUSEPEN_I608X_RDESC_ORIG_SIZE) { rdesc = mousepen_i608x_rdesc_fixed; *rsize = sizeof(mousepen_i608x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_EASYPEN_M610X: if (*rsize == EASYPEN_M610X_RDESC_ORIG_SIZE) { rdesc = easypen_m610x_rdesc_fixed; *rsize = sizeof(easypen_m610x_rdesc_fixed); } break; case USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Gila Gaming Mouse"); break; case USB_DEVICE_ID_GENIUS_GX_IMPERATOR: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 83, "Genius Gx Imperator Keyboard"); break; case USB_DEVICE_ID_GENIUS_MANTICORE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Manticore Keyboard"); break; } return rdesc; } Commit Message: HID: fix a couple of off-by-ones There are a few very theoretical off-by-one bugs in report descriptor size checking when performing a pre-parsing fixup. Fix those. Cc: stable@vger.kernel.org Reported-by: Ben Hawkes <hawkes@google.com> Reviewed-by: Benjamin Tissoires <benjamin.tissoires@redhat.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz> CWE ID: CWE-119
static __u8 *kye_report_fixup(struct hid_device *hdev, __u8 *rdesc, unsigned int *rsize) { switch (hdev->product) { case USB_DEVICE_ID_KYE_ERGO_525V: /* the fixups that need to be done: * - change led usage page to button for extra buttons * - report size 8 count 1 must be size 1 count 8 for button * bitfield * - change the button usage range to 4-7 for the extra * buttons */ if (*rsize >= 75 && rdesc[61] == 0x05 && rdesc[62] == 0x08 && rdesc[63] == 0x19 && rdesc[64] == 0x08 && rdesc[65] == 0x29 && rdesc[66] == 0x0f && rdesc[71] == 0x75 && rdesc[72] == 0x08 && rdesc[73] == 0x95 && rdesc[74] == 0x01) { hid_info(hdev, "fixing up Kye/Genius Ergo Mouse " "report descriptor\n"); rdesc[62] = 0x09; rdesc[64] = 0x04; rdesc[66] = 0x07; rdesc[72] = 0x01; rdesc[74] = 0x08; } break; case USB_DEVICE_ID_KYE_EASYPEN_I405X: if (*rsize == EASYPEN_I405X_RDESC_ORIG_SIZE) { rdesc = easypen_i405x_rdesc_fixed; *rsize = sizeof(easypen_i405x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_MOUSEPEN_I608X: if (*rsize == MOUSEPEN_I608X_RDESC_ORIG_SIZE) { rdesc = mousepen_i608x_rdesc_fixed; *rsize = sizeof(mousepen_i608x_rdesc_fixed); } break; case USB_DEVICE_ID_KYE_EASYPEN_M610X: if (*rsize == EASYPEN_M610X_RDESC_ORIG_SIZE) { rdesc = easypen_m610x_rdesc_fixed; *rsize = sizeof(easypen_m610x_rdesc_fixed); } break; case USB_DEVICE_ID_GENIUS_GILA_GAMING_MOUSE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Gila Gaming Mouse"); break; case USB_DEVICE_ID_GENIUS_GX_IMPERATOR: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 83, "Genius Gx Imperator Keyboard"); break; case USB_DEVICE_ID_GENIUS_MANTICORE: rdesc = kye_consumer_control_fixup(hdev, rdesc, rsize, 104, "Genius Manticore Keyboard"); break; } return rdesc; }
166,371
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DecoderTest::RunLoop(CompressedVideoSource *video) { vpx_codec_dec_cfg_t dec_cfg = {0}; Decoder* const decoder = codec_->CreateDecoder(dec_cfg, 0); ASSERT_TRUE(decoder != NULL); for (video->Begin(); video->cxdata(); video->Next()) { PreDecodeFrameHook(*video, decoder); vpx_codec_err_t res_dec = decoder->DecodeFrame(video->cxdata(), video->frame_size()); ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError(); DxDataIterator dec_iter = decoder->GetDxData(); const vpx_image_t *img = NULL; while ((img = dec_iter.Next())) DecompressedFrameHook(*img, video->frame_number()); } delete decoder; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void DecoderTest::RunLoop(CompressedVideoSource *video) { bool Decoder::IsVP8() const { const char *codec_name = GetDecoderName(); return strncmp(kVP8Name, codec_name, sizeof(kVP8Name) - 1) == 0; } void DecoderTest::HandlePeekResult(Decoder *const decoder, CompressedVideoSource *video, const vpx_codec_err_t res_peek) { const bool is_vp8 = decoder->IsVP8(); if (is_vp8) { /* Vp8's implementation of PeekStream returns an error if the frame you * pass it is not a keyframe, so we only expect VPX_CODEC_OK on the first * frame, which must be a keyframe. */ if (video->frame_number() == 0) ASSERT_EQ(VPX_CODEC_OK, res_peek) << "Peek return failed: " << vpx_codec_err_to_string(res_peek); } else { /* The Vp9 implementation of PeekStream returns an error only if the * data passed to it isn't a valid Vp9 chunk. */ ASSERT_EQ(VPX_CODEC_OK, res_peek) << "Peek return failed: " << vpx_codec_err_to_string(res_peek); } } void DecoderTest::RunLoop(CompressedVideoSource *video, const vpx_codec_dec_cfg_t &dec_cfg) { Decoder* const decoder = codec_->CreateDecoder(dec_cfg, flags_, 0); ASSERT_TRUE(decoder != NULL); bool end_of_file = false; for (video->Begin(); !::testing::Test::HasFailure() && !end_of_file; video->Next()) { PreDecodeFrameHook(*video, decoder); vpx_codec_stream_info_t stream_info; stream_info.sz = sizeof(stream_info); if (video->cxdata() != NULL) { const vpx_codec_err_t res_peek = decoder->PeekStream(video->cxdata(), video->frame_size(), &stream_info); HandlePeekResult(decoder, video, res_peek); ASSERT_FALSE(::testing::Test::HasFailure()); vpx_codec_err_t res_dec = decoder->DecodeFrame(video->cxdata(), video->frame_size()); if (!HandleDecodeResult(res_dec, *video, decoder)) break; } else { // Signal end of the file to the decoder. const vpx_codec_err_t res_dec = decoder->DecodeFrame(NULL, 0); ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError(); end_of_file = true; } DxDataIterator dec_iter = decoder->GetDxData(); const vpx_image_t *img = NULL; while ((img = dec_iter.Next())) DecompressedFrameHook(*img, video->frame_number()); } delete decoder; }
174,535
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ssh_packet_set_postauth(struct ssh *ssh) { struct sshcomp *comp; int r, mode; debug("%s: called", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; for (mode = 0; mode < MODE_MAX; mode++) { if (ssh->state->newkeys[mode] == NULL) continue; comp = &ssh->state->newkeys[mode]->comp; if (comp && comp->enabled && (r = ssh_packet_init_compression(ssh)) != 0) return r; } return 0; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
ssh_packet_set_postauth(struct ssh *ssh) { int r; debug("%s: called", __func__); /* This was set in net child, but is not visible in user child */ ssh->state->after_authentication = 1; ssh->state->rekeying = 0; if ((r = ssh_packet_enable_delayed_compress(ssh)) != 0) return r; return 0; }
168,655
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DatabaseMessageFilter::OnHandleSqliteError( const string16& origin_identifier, const string16& database_name, int error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); db_tracker_->HandleSqliteError(origin_identifier, database_name, error); } Commit Message: WebDatabase: check path traversal in origin_identifier BUG=172264 Review URL: https://chromiumcodereview.appspot.com/12212091 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@183141 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-22
void DatabaseMessageFilter::OnHandleSqliteError( const string16& origin_identifier, const string16& database_name, int error) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!DatabaseUtil::IsValidOriginIdentifier(origin_identifier)) { RecordAction(UserMetricsAction("BadMessageTerminate_DBMF")); BadMessageReceived(); return; } db_tracker_->HandleSqliteError(origin_identifier, database_name, error); }
171,478
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void IBusBusGlobalEngineChangedCallback( IBusBus* bus, const gchar* engine_name, gpointer user_data) { DCHECK(engine_name); DLOG(INFO) << "Global engine is changed to " << engine_name; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->UpdateUI(engine_name); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void IBusBusGlobalEngineChangedCallback( void IBusBusGlobalEngineChanged(IBusBus* bus, const gchar* engine_name) { DCHECK(engine_name); VLOG(1) << "Global engine is changed to " << engine_name; UpdateUI(engine_name); }
170,538
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) { if (external_popup_menu_ == NULL) return; blink::WebScopedUserGesture gesture(frame_); external_popup_menu_->DidSelectItem(selected_index); external_popup_menu_.reset(); } Commit Message: Fix crashes in RenderFrameImpl::OnSelectPopupMenuItem(s) ExternalPopupMenu::DidSelectItem(s) can delete the RenderFrameImpl. We need to reset external_popup_menu_ before calling it. Bug: 912211 Change-Id: Ia9a628e144464a2ebb14ab77d3a693fd5cead6fc Reviewed-on: https://chromium-review.googlesource.com/c/1381325 Commit-Queue: Kent Tamura <tkent@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#618026} CWE ID: CWE-416
void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) { if (external_popup_menu_ == NULL) return; blink::WebScopedUserGesture gesture(frame_); // We need to reset |external_popup_menu_| before calling DidSelectItem(), // which might delete |this|. // See ExternalPopupMenuRemoveTest.RemoveFrameOnChange std::unique_ptr<ExternalPopupMenu> popup; popup.swap(external_popup_menu_); popup->DidSelectItem(selected_index); }
173,072
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ManifestChangeNotifier::DidChangeManifest() { if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); } Commit Message: Fail the web app manifest fetch if the document is sandboxed. This ensures that sandboxed pages are regarded as non-PWAs, and that other features in the browser process which trust the web manifest do not receive the manifest at all if the document itself cannot access the manifest. BUG=771709 Change-Id: Ifd4d00c2fccff8cc0e5e8d2457bd55b992b0a8f4 Reviewed-on: https://chromium-review.googlesource.com/866529 Commit-Queue: Dominick Ng <dominickn@chromium.org> Reviewed-by: Mounir Lamouri <mlamouri@chromium.org> Reviewed-by: Mike West <mkwst@chromium.org> Cr-Commit-Position: refs/heads/master@{#531121} CWE ID:
void ManifestChangeNotifier::DidChangeManifest() { // Manifests are not considered when the current page has a unique origin. if (!ManifestManager::CanFetchManifest(render_frame())) return; if (weak_factory_.HasWeakPtrs()) return; if (!render_frame()->GetWebFrame()->IsLoading()) { render_frame() ->GetTaskRunner(blink::TaskType::kUnspecedLoading) ->PostTask(FROM_HERE, base::BindOnce(&ManifestChangeNotifier::ReportManifestChange, weak_factory_.GetWeakPtr())); return; } ReportManifestChange(); }
172,920
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SecureProxyChecker::CheckIfSecureProxyIsAllowed( SecureProxyCheckerCallback fetcher_callback) { net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation( "data_reduction_proxy_secure_proxy_check", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server. Proceeds " "with using a secure connection to the proxy only if the " "response is not blocked or modified by an intermediary." trigger: "A request can be sent whenever the browser is determining how " "to configure its connection to the data reduction proxy. This " "happens on startup and network changes." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop " "it is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = params::GetSecureProxyCheckURL(); resource_request->load_flags = net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_PROXY; resource_request->allow_credentials = false; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE | network::SimpleURLLoader::RETRY_ON_5XX); url_loader_->SetOnRedirectCallback(base::BindRepeating( &SecureProxyChecker::OnURLLoaderRedirect, base::Unretained(this))); fetcher_callback_ = fetcher_callback; secure_proxy_check_start_time_ = base::Time::Now(); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( url_loader_factory_.get(), base::BindOnce(&SecureProxyChecker::OnURLLoadComplete, base::Unretained(this))); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void SecureProxyChecker::CheckIfSecureProxyIsAllowed( SecureProxyCheckerCallback fetcher_callback) { DCHECK(!params::IsIncludedInHoldbackFieldTrial()); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation( "data_reduction_proxy_secure_proxy_check", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server. Proceeds " "with using a secure connection to the proxy only if the " "response is not blocked or modified by an intermediary." trigger: "A request can be sent whenever the browser is determining how " "to configure its connection to the data reduction proxy. This " "happens on startup and network changes." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop " "it is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = params::GetSecureProxyCheckURL(); resource_request->load_flags = net::LOAD_DISABLE_CACHE | net::LOAD_BYPASS_PROXY; resource_request->allow_credentials = false; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE | network::SimpleURLLoader::RETRY_ON_5XX); url_loader_->SetOnRedirectCallback(base::BindRepeating( &SecureProxyChecker::OnURLLoaderRedirect, base::Unretained(this))); fetcher_callback_ = fetcher_callback; secure_proxy_check_start_time_ = base::Time::Now(); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( url_loader_factory_.get(), base::BindOnce(&SecureProxyChecker::OnURLLoadComplete, base::Unretained(this))); }
172,422
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltDateCreateDate (exsltDateType type) { exsltDateValPtr ret; ret = (exsltDateValPtr) xmlMalloc(sizeof(exsltDateVal)); if (ret == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltDateCreateDate: out of memory\n"); return (NULL); } memset (ret, 0, sizeof(exsltDateVal)); if (type != EXSLT_UNKNOWN) ret->type = type; return ret; } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltDateCreateDate (exsltDateType type) { exsltDateValPtr ret; ret = (exsltDateValPtr) xmlMalloc(sizeof(exsltDateVal)); if (ret == NULL) { xsltGenericError(xsltGenericErrorContext, "exsltDateCreateDate: out of memory\n"); return (NULL); } memset (ret, 0, sizeof(exsltDateVal)); if (type != XS_DURATION) { ret->value.date.mon = 1; ret->value.date.day = 1; } if (type != EXSLT_UNKNOWN) ret->type = type; return ret; }
173,291
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageBitmapFactories::Trace(blink::Visitor* visitor) { visitor->Trace(pending_loaders_); Supplement<LocalDOMWindow>::Trace(visitor); Supplement<WorkerGlobalScope>::Trace(visitor); } Commit Message: Fix UAP in ImageBitmapLoader/FileReaderLoader FileReaderLoader stores its client as a raw pointer, so in cases like ImageBitmapLoader where the FileReaderLoaderClient really is garbage collected we have to make sure to destroy the FileReaderLoader when the ExecutionContext that owns it is destroyed. Bug: 913970 Change-Id: I40b02115367cf7bf5bbbbb8e9b57874d2510f861 Reviewed-on: https://chromium-review.googlesource.com/c/1374511 Reviewed-by: Jeremy Roman <jbroman@chromium.org> Commit-Queue: Marijn Kruisselbrink <mek@chromium.org> Cr-Commit-Position: refs/heads/master@{#616342} CWE ID: CWE-416
void ImageBitmapFactories::Trace(blink::Visitor* visitor) { ImageBitmapFactories::ImageBitmapLoader::~ImageBitmapLoader() { DCHECK(!loader_); }
173,070
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { register const xmlChar *cmp = other; register const xmlChar *in; const xmlChar *ret; GROW; in = ctxt->input->cur; while (*in != 0 && *in == *cmp) { ++in; ++cmp; ctxt->input->col++; } if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) { /* success */ ctxt->input->cur = in; return (const xmlChar*) 1; } /* failure (or end of input buffer), check with full function */ ret = xmlParseName (ctxt); /* strings coming from the dictionnary direct compare possible */ if (ret == other) { return (const xmlChar*) 1; } return ret; } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { register const xmlChar *cmp = other; register const xmlChar *in; const xmlChar *ret; GROW; if (ctxt->instate == XML_PARSER_EOF) return(NULL); in = ctxt->input->cur; while (*in != 0 && *in == *cmp) { ++in; ++cmp; ctxt->input->col++; } if (*cmp == 0 && (*in == '>' || IS_BLANK_CH (*in))) { /* success */ ctxt->input->cur = in; return (const xmlChar*) 1; } /* failure (or end of input buffer), check with full function */ ret = xmlParseName (ctxt); /* strings coming from the dictionnary direct compare possible */ if (ret == other) { return (const xmlChar*) 1; } return ret; }
171,296
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: juniper_mlppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLPPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link * best indicator if the cookie looks like a proto */ if (ndo->ndo_eflag && EXTRACT_16BITS(&l2info.cookie) != PPP_OSI && EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL)) ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle)); p+=l2info.header_len; /* first try the LSQ protos */ switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: /* IP traffic going to the RE would not have a cookie * -> this must be incoming IS-IS over PPP */ if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR)) ppp_print(ndo, p, l2info.length); else ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length, l2info.caplen); return l2info.header_len; default: break; } /* zero length cookie ? */ switch (EXTRACT_16BITS(&l2info.cookie)) { case PPP_OSI: ppp_print(ndo, p - 2, l2info.length + 2); break; case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */ default: ppp_print(ndo, p, l2info.length); break; } return l2info.header_len; } Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print(). This fixes a buffer over-read discovered by Kamil Frankowicz. Don't pass the remaining caplen - that's too hard to get right, and we were getting it wrong in at least one case; just use ND_TTEST(). Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
juniper_mlppp_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p) { struct juniper_l2info_t l2info; l2info.pictype = DLT_JUNIPER_MLPPP; if (juniper_parse_header(ndo, p, h, &l2info) == 0) return l2info.header_len; /* suppress Bundle-ID if frame was captured on a child-link * best indicator if the cookie looks like a proto */ if (ndo->ndo_eflag && EXTRACT_16BITS(&l2info.cookie) != PPP_OSI && EXTRACT_16BITS(&l2info.cookie) != (PPP_ADDRESS << 8 | PPP_CONTROL)) ND_PRINT((ndo, "Bundle-ID %u: ", l2info.bundle)); p+=l2info.header_len; /* first try the LSQ protos */ switch(l2info.proto) { case JUNIPER_LSQ_L3_PROTO_IPV4: /* IP traffic going to the RE would not have a cookie * -> this must be incoming IS-IS over PPP */ if (l2info.cookie[4] == (JUNIPER_LSQ_COOKIE_RE|JUNIPER_LSQ_COOKIE_DIR)) ppp_print(ndo, p, l2info.length); else ip_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_IPV6: ip6_print(ndo, p,l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_MPLS: mpls_print(ndo, p, l2info.length); return l2info.header_len; case JUNIPER_LSQ_L3_PROTO_ISO: isoclns_print(ndo, p, l2info.length); return l2info.header_len; default: break; } /* zero length cookie ? */ switch (EXTRACT_16BITS(&l2info.cookie)) { case PPP_OSI: ppp_print(ndo, p - 2, l2info.length + 2); break; case (PPP_ADDRESS << 8 | PPP_CONTROL): /* fall through */ default: ppp_print(ndo, p, l2info.length); break; } return l2info.header_len; }
167,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void QuitMessageLoop() { base::RunLoop::QuitCurrentWhenIdleDeprecated(); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <wez@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
static void QuitMessageLoop() { base::Unretained(this), on_launched)); }
172,054
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree() { ASSERT(element()->shadow()); Document* document = element()->document(); ContainerNode* container = element()->userAgentShadowRoot(); RefPtr<DateTimeEditElement> dateTimeEditElement(DateTimeEditElement::create(document, *this)); m_dateTimeEditElement = dateTimeEditElement.get(); container->appendChild(m_dateTimeEditElement); updateInnerTextValue(); RefPtr<ClearButtonElement> clearButton = ClearButtonElement::create(document, *this); m_clearButton = clearButton.get(); container->appendChild(clearButton); RefPtr<SpinButtonElement> spinButton = SpinButtonElement::create(document, *this); m_spinButtonElement = spinButton.get(); container->appendChild(spinButton); bool shouldAddPickerIndicator = false; if (InputType::themeSupportsDataListUI(this)) shouldAddPickerIndicator = true; RefPtr<RenderTheme> theme = document->page() ? document->page()->theme() : RenderTheme::defaultTheme(); if (theme->supportsCalendarPicker(formControlType())) { shouldAddPickerIndicator = true; m_pickerIndicatorIsAlwaysVisible = true; } if (shouldAddPickerIndicator) { RefPtr<PickerIndicatorElement> pickerElement = PickerIndicatorElement::create(document, *this); m_pickerIndicatorElement = pickerElement.get(); container->appendChild(m_pickerIndicatorElement); m_pickerIndicatorIsVisible = true; updatePickerIndicatorVisibility(); } } Commit Message: Setting input.x-webkit-speech should not cause focus change In r150866, we introduced element()->focus() in destroyShadowSubtree() to retain focus on <input> when its type attribute gets changed. But when x-webkit-speech attribute is changed, the element is detached before calling destroyShadowSubtree() and element()->focus() failed This patch moves detach() after destroyShadowSubtree() to fix the problem. BUG=243818 TEST=fast/forms/input-type-change-focusout.html NOTRY=true Review URL: https://chromiumcodereview.appspot.com/16084005 git-svn-id: svn://svn.chromium.org/blink/trunk@151444 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree() { ASSERT(element()->shadow()); // Element must not be attached here, because if it was attached // DateTimeEditElement::customStyleForRenderer() is called in appendChild() // before the field wrapper element is created. ASSERT(!element()->attached()); Document* document = element()->document(); ContainerNode* container = element()->userAgentShadowRoot(); RefPtr<DateTimeEditElement> dateTimeEditElement(DateTimeEditElement::create(document, *this)); m_dateTimeEditElement = dateTimeEditElement.get(); container->appendChild(m_dateTimeEditElement); updateInnerTextValue(); RefPtr<ClearButtonElement> clearButton = ClearButtonElement::create(document, *this); m_clearButton = clearButton.get(); container->appendChild(clearButton); RefPtr<SpinButtonElement> spinButton = SpinButtonElement::create(document, *this); m_spinButtonElement = spinButton.get(); container->appendChild(spinButton); bool shouldAddPickerIndicator = false; if (InputType::themeSupportsDataListUI(this)) shouldAddPickerIndicator = true; RefPtr<RenderTheme> theme = document->page() ? document->page()->theme() : RenderTheme::defaultTheme(); if (theme->supportsCalendarPicker(formControlType())) { shouldAddPickerIndicator = true; m_pickerIndicatorIsAlwaysVisible = true; } if (shouldAddPickerIndicator) { RefPtr<PickerIndicatorElement> pickerElement = PickerIndicatorElement::create(document, *this); m_pickerIndicatorElement = pickerElement.get(); container->appendChild(m_pickerIndicatorElement); m_pickerIndicatorIsVisible = true; updatePickerIndicatorVisibility(); } }
171,264
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ChromeContentRendererClient::ShouldFork(WebFrame* frame, const GURL& url, bool is_initial_navigation, bool* send_referrer) { DCHECK(!frame->parent()); if (prerender_dispatcher_.get() && prerender_dispatcher_->IsPrerenderURL(url)) return true; const ExtensionSet* extensions = extension_dispatcher_->extensions(); const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension( *extensions, ExtensionURLInfo(url)); bool is_extension_url = !!new_url_extension; if (CrossesExtensionExtents(frame, url, *extensions, is_extension_url, is_initial_navigation)) { *send_referrer = true; const Extension* extension = extension_dispatcher_->extensions()->GetExtensionOrAppByURL( ExtensionURLInfo(url)); if (extension && extension->is_app()) { UMA_HISTOGRAM_ENUMERATION( extension_misc::kAppLaunchHistogram, extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); } return true; } if (frame->top()->document().url() == url) { if (is_extension_url != extension_dispatcher_->is_extension_process()) return true; } if (url.SchemeIs(kChromeUIScheme)) return true; return false; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool ChromeContentRendererClient::ShouldFork(WebFrame* frame, const GURL& url, bool is_initial_navigation, bool* send_referrer) { DCHECK(!frame->parent()); if (prerender_dispatcher_.get() && prerender_dispatcher_->IsPrerenderURL(url)) return true; const ExtensionSet* extensions = extension_dispatcher_->extensions(); const Extension* new_url_extension = extensions::GetNonBookmarkAppExtension( *extensions, ExtensionURLInfo(url)); bool is_extension_url = !!new_url_extension; if (CrossesExtensionExtents(frame, url, *extensions, is_extension_url, is_initial_navigation)) { *send_referrer = true; const Extension* extension = extension_dispatcher_->extensions()->GetExtensionOrAppByURL( ExtensionURLInfo(url)); if (extension && extension->is_app()) { UMA_HISTOGRAM_ENUMERATION( extension_misc::kAppLaunchHistogram, extension_misc::APP_LAUNCH_CONTENT_NAVIGATION, extension_misc::APP_LAUNCH_BUCKET_BOUNDARY); } return true; } if (frame->top()->document().url() == url) { if (is_extension_url != extension_dispatcher_->is_extension_process()) return true; } return false; }
171,009
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if it wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; /* ->current must be initialized; rewind doesn't set it and valid * doesn't check whether it's set */ iterator->current = object; } zval_add_ref(&object); return (zend_object_iterator*)iterator; } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if it wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; /* ->current must be initialized; rewind doesn't set it and valid * doesn't check whether it's set */ iterator->current = object; } zval_add_ref(&object); return (zend_object_iterator*)iterator; }
167,069
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_default_ini(PNG_CONST image_transform *this, transform_display *that) { this->next->ini(this->next, that); } 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_default_ini(PNG_CONST image_transform *this, extern void image_transform_default_ini(const image_transform *this, transform_display *that); /* silence GCC warnings */ void /* private, but almost always needed */ image_transform_default_ini(const image_transform *this, transform_display *that) { this->next->ini(this->next, that); }
173,621
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t len; uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) { return; } } n = r->iov.iov_len / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { len = r->sector_count * 512; if (len > SCSI_DMA_BUF_SIZE) { len = SCSI_DMA_BUF_SIZE; } r->iov.iov_len = len; DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, len); scsi_req_data(&r->req, len); } } Commit Message: scsi-disk: commonize iovec creation between reads and writes Also, consistently use qiov.size instead of iov.iov_len. Signed-off-by: Paolo Bonzini <pbonzini@redhat.com> Signed-off-by: Kevin Wolf <kwolf@redhat.com> CWE ID: CWE-119
static void scsi_write_complete(void * opaque, int ret) { SCSIDiskReq *r = (SCSIDiskReq *)opaque; SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev); uint32_t n; if (r->req.aiocb != NULL) { r->req.aiocb = NULL; bdrv_acct_done(s->bs, &r->acct); } if (ret) { if (scsi_handle_rw_error(r, -ret, SCSI_REQ_STATUS_RETRY_WRITE)) { return; } } n = r->qiov.size / 512; r->sector += n; r->sector_count -= n; if (r->sector_count == 0) { scsi_req_complete(&r->req, GOOD); } else { scsi_init_iovec(r); DPRINTF("Write complete tag=0x%x more=%d\n", r->req.tag, r->qiov.size); scsi_req_data(&r->req, r->qiov.size); } }
169,922
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void perform_gamma_transform_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) { unsigned int i, j; for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j) if (i != j) { gamma_transform_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/, pm->use_input_precision, 0 /*do not scale16*/); if (fail(pm)) return; } } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
static void perform_gamma_transform_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_transform, pm->test_tRNS)) { unsigned int i, j; for (i=0; i<pm->ngamma_tests; ++i) for (j=0; j<pm->ngamma_tests; ++j) if (i != j) { gamma_transform_test(pm, colour_type, bit_depth, palette_number, pm->interlace_type, 1/pm->gammas[i], pm->gammas[j], 0/*sBIT*/, pm->use_input_precision, 0 /*do not scale16*/); if (fail(pm)) return; } } }
173,683
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: struct edid *drm_load_edid_firmware(struct drm_connector *connector) { const char *connector_name = connector->name; char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL; struct edid *edid; if (edid_firmware[0] == '\0') return ERR_PTR(-ENOENT); /* * If there are multiple edid files specified and separated * by commas, search through the list looking for one that * matches the connector. * * If there's one or more that doesn't specify a connector, keep * the last one found one as a fallback. */ fwstr = kstrdup(edid_firmware, GFP_KERNEL); edidstr = fwstr; while ((edidname = strsep(&edidstr, ","))) { if (strncmp(connector_name, edidname, colon - edidname)) continue; edidname = colon + 1; break; } if (*edidname != '\0') /* corner case: multiple ',' */ fallback = edidname; } Commit Message: CWE ID: CWE-476
struct edid *drm_load_edid_firmware(struct drm_connector *connector) { const char *connector_name = connector->name; char *edidname, *last, *colon, *fwstr, *edidstr, *fallback = NULL; struct edid *edid; if (edid_firmware[0] == '\0') return ERR_PTR(-ENOENT); /* * If there are multiple edid files specified and separated * by commas, search through the list looking for one that * matches the connector. * * If there's one or more that doesn't specify a connector, keep * the last one found one as a fallback. */ fwstr = kstrdup(edid_firmware, GFP_KERNEL); if (!fwstr) return ERR_PTR(-ENOMEM); edidstr = fwstr; while ((edidname = strsep(&edidstr, ","))) { if (strncmp(connector_name, edidname, colon - edidname)) continue; edidname = colon + 1; break; } if (*edidname != '\0') /* corner case: multiple ',' */ fallback = edidname; }
164,709
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void QuicTransportHost::Initialize( IceTransportHost* ice_transport_host, quic::Perspective perspective, const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(ice_transport_host); DCHECK(!ice_transport_host_); ice_transport_host_ = ice_transport_host; P2PQuicTransportConfig config( this, ice_transport_host->ConnectConsumer(this)->packet_transport(), certificates); config.is_server = (perspective == quic::Perspective::IS_SERVER); quic_transport_ = quic_transport_factory_->CreateQuicTransport(std::move(config)); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <shampson@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void QuicTransportHost::Initialize( IceTransportHost* ice_transport_host, quic::Perspective perspective, const std::vector<rtc::scoped_refptr<rtc::RTCCertificate>>& certificates) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(ice_transport_host); DCHECK(!ice_transport_host_); ice_transport_host_ = ice_transport_host; // TODO(https://crbug.com/874296): Pass through values for read and write // stream buffer sizes in the P2PQuicTransportConfig. Currently this is just // set to the same size as the QUIC receive window size (24 MB). uint32_t stream_buffer_size = 24 * 1024 * 1024; P2PQuicTransportConfig config( this, ice_transport_host->ConnectConsumer(this)->packet_transport(), certificates, stream_buffer_size); config.is_server = (perspective == quic::Perspective::IS_SERVER); quic_transport_ = quic_transport_factory_->CreateQuicTransport(std::move(config)); }
172,270
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: print_ccp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case CCPOPT_BSDCOMP: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u", p[2] >> 5, p[2] & 0x1f)); break; case CCPOPT_MVRCA: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u", (p[2] & 0xc0) >> 6, (p[2] & 0x20) ? "Enabled" : "Disabled", p[2] & 0x1f, p[3])); break; case CCPOPT_DEFLATE: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK2(*(p + 2), 1); ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u", (p[2] & 0xf0) >> 4, ((p[2] & 0x0f) == 8) ? "zlib" : "unknown", p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); break; /* XXX: to be supported */ #if 0 case CCPOPT_OUI: case CCPOPT_PRED1: case CCPOPT_PRED2: case CCPOPT_PJUMP: case CCPOPT_HPPPC: case CCPOPT_STACLZS: case CCPOPT_MPPC: case CCPOPT_GFZA: case CCPOPT_V42BIS: case CCPOPT_LZSDCP: case CCPOPT_DEC: case CCPOPT_RESV: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ccp]")); return 0; } Commit Message: CVE-2017-13029/PPP: Fix a bounds check, and clean up other bounds checks. For configuration protocol options, use ND_TCHECK() and ND_TCHECK_nBITS() macros, passing them the appropriate pointer argument. This fixes one case where the ND_TCHECK2() call they replace was not checking enough bytes. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. CWE ID: CWE-125
print_ccp_config_options(netdissect_options *ndo, const u_char *p, int length) { int len, opt; if (length < 2) return 0; ND_TCHECK2(*p, 2); len = p[1]; opt = p[0]; if (length < len) return 0; if (len < 2) { ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); return 0; } ND_PRINT((ndo, "\n\t %s Option (0x%02x), length %u", tok2str(ccpconfopts_values, "Unknown", opt), opt, len)); switch (opt) { case CCPOPT_BSDCOMP: if (len < 3) { ND_PRINT((ndo, " (length bogus, should be >= 3)")); return len; } ND_TCHECK(p[2]); ND_PRINT((ndo, ": Version: %u, Dictionary Bits: %u", p[2] >> 5, p[2] & 0x1f)); break; case CCPOPT_MVRCA: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK(p[3]); ND_PRINT((ndo, ": Features: %u, PxP: %s, History: %u, #CTX-ID: %u", (p[2] & 0xc0) >> 6, (p[2] & 0x20) ? "Enabled" : "Disabled", p[2] & 0x1f, p[3])); break; case CCPOPT_DEFLATE: if (len < 4) { ND_PRINT((ndo, " (length bogus, should be >= 4)")); return len; } ND_TCHECK(p[3]); ND_PRINT((ndo, ": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u", (p[2] & 0xf0) >> 4, ((p[2] & 0x0f) == 8) ? "zlib" : "unknown", p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); break; /* XXX: to be supported */ #if 0 case CCPOPT_OUI: case CCPOPT_PRED1: case CCPOPT_PRED2: case CCPOPT_PJUMP: case CCPOPT_HPPPC: case CCPOPT_STACLZS: case CCPOPT_MPPC: case CCPOPT_GFZA: case CCPOPT_V42BIS: case CCPOPT_LZSDCP: case CCPOPT_DEC: case CCPOPT_RESV: break; #endif default: /* * Unknown option; dump it as raw bytes now if we're * not going to do so below. */ if (ndo->ndo_vflag < 2) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); break; } if (ndo->ndo_vflag > 1) print_unknown_data(ndo, &p[2], "\n\t ", len - 2); /* exclude TLV header */ return len; trunc: ND_PRINT((ndo, "[|ccp]")); return 0; }
167,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NetworkThrottleManagerImpl::NetworkThrottleManagerImpl() : lifetime_median_estimate_(PercentileEstimator::kMedianPercentile, kInitialMedianInMs), outstanding_recomputation_timer_( base::MakeUnique<base::Timer>(false /* retain_user_task */, false /* is_repeating */)), tick_clock_(new base::DefaultTickClock()), weak_ptr_factory_(this) {} Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <jbroman@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Bence Béky <bnc@chromium.org> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
NetworkThrottleManagerImpl::NetworkThrottleManagerImpl() : lifetime_median_estimate_(PercentileEstimator::kMedianPercentile, kInitialMedianInMs), outstanding_recomputation_timer_( std::make_unique<base::Timer>(false /* retain_user_task */, false /* is_repeating */)), tick_clock_(new base::DefaultTickClock()), weak_ptr_factory_(this) {}
173,266
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); UParseError parse_error; transliterator_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d; ӏ > l; [кĸκ] > k; п > n;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); } Commit Message: Add a few more confusable map entries 1. Map Malaylam U+0D1F to 's'. 2. Map 'small-cap-like' Cyrillic letters to "look-alike" Latin lowercase letters. The characters in new confusable map entries are replaced by their Latin "look-alike" characters before the skeleton is calculated to compare with top domain names. Bug: 784761,773930 Test: components_unittests --gtest_filter=*IDNToUni* Change-Id: Ib26664e21ac5eb290e4a2993b01cbf0edaade0ee Reviewed-on: https://chromium-review.googlesource.com/805214 Reviewed-by: Peter Kasting <pkasting@chromium.org> Commit-Queue: Jungshik Shin <jshin@chromium.org> Cr-Commit-Position: refs/heads/master@{#521648} CWE ID: CWE-20
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_HIGHLY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb-\\u30fe]"), status); kana_letters_exceptions_.freeze(); combining_diacritics_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u0300-\\u0339]"), status); combining_diacritics_exceptions_.freeze(); cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); lgc_letters_n_ascii_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:][:Greek:][:Cyrillic:][0-9\\u002e_" "\\u002d][\\u0300-\\u0339]]"), status); lgc_letters_n_ascii_.freeze(); // removal; NFC". UParseError parse_error; diacritic_remover_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("DropAcc"), icu::UnicodeString("::NFD; ::[:Nonspacing Mark:] Remove; ::NFC;" " ł > l; ø > o; đ > d;"), UTRANS_FORWARD, parse_error, status)); // Supplement the Unicode confusable list by the following mapping. // - U+04CF (ӏ) => l // - {U+043A (к), U+0138(ĸ), U+03BA(κ)} => k // - U+043F(п) => n // - {U+0185 (ƅ), U+044C (ь)} => b // - U+0432 (в) => b // - U+043C (м) => m // - U+043D (н) => h // - U+0442 (т) => t // - {U+0448 (ш), U+0449 (щ)} => w // - U+0D1F (ട) => s extra_confusable_mapper_.reset(icu::Transliterator::createFromRules( UNICODE_STRING_SIMPLE("ExtraConf"), icu::UnicodeString( "ӏ > l; [кĸκ] > k; п > n; [ƅь] > b; в > b; м > m; н > h; " "т > t; [шщ] > w; ട > s;"), UTRANS_FORWARD, parse_error, status)); DCHECK(U_SUCCESS(status)) << "Spoofchecker initalization failed due to an error: " << u_errorName(status); }
172,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LauncherView::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) { FOR_EACH_OBSERVER(LauncherIconObserver, observers_, OnLauncherIconPositionsChanged()); } 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::OnBoundsAnimatorProgressed(views::BoundsAnimator* animator) { FOR_EACH_OBSERVER(LauncherIconObserver, observers_, OnLauncherIconPositionsChanged()); PreferredSizeChanged(); }
170,893
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN); subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + sizeof(struct isis_subtlv_spb_mcid); len = len - sizeof(struct isis_subtlv_spb_mcid); break; } case ISIS_SUBTLV_SPB_DIGEST: { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN); ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { ND_TCHECK2(*(tptr), stlv_len); while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN); ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); } Commit Message: CVE-2017-13026/IS-IS: Clean up processing of subTLVs. Add bounds checks, do a common check to make sure we captured the entire subTLV, add checks to make sure the subTLV fits within the TLV. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add tests using the capture files supplied by the reporter(s), modified so the capture files won't be rejected as an invalid capture. Update existing tests for changes to IS-IS dissector. CWE ID: CWE-125
isis_print_mt_port_cap_subtlv(netdissect_options *ndo, const uint8_t *tptr, int len) { int stlv_type, stlv_len; const struct isis_subtlv_spb_mcid *subtlv_spb_mcid; int i; while (len > 2) { ND_TCHECK2(*tptr, 2); stlv_type = *(tptr++); stlv_len = *(tptr++); /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u", tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type), stlv_type, stlv_len)); /*len -= TLV_TYPE_LEN_OFFSET;*/ len = len -2; /* Make sure the subTLV fits within the space left */ if (len < stlv_len) goto trunc; /* Make sure the entire subTLV is in the captured data */ ND_TCHECK2(*(tptr), stlv_len); switch (stlv_type) { case ISIS_SUBTLV_SPB_MCID: { if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN) goto trunc; subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr; ND_PRINT((ndo, "\n\t MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ ND_PRINT((ndo, "\n\t AUX-MCID: ")); isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid)); /*tptr += SPB_MCID_MIN_LEN; len -= SPB_MCID_MIN_LEN; */ tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN; len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN; break; } case ISIS_SUBTLV_SPB_DIGEST: { if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN) goto trunc; ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d", (*(tptr) >> 5), (((*tptr)>> 4) & 0x01), ((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03))); tptr++; ND_PRINT((ndo, "\n\t Digest: ")); for(i=1;i<=8; i++) { ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr))); if (i%4 == 0 && i != 8) ND_PRINT((ndo, "\n\t ")); tptr = tptr + 4; } len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN; break; } case ISIS_SUBTLV_SPB_BVID: { while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN) { ND_PRINT((ndo, "\n\t ECT: %08x", EXTRACT_32BITS(tptr))); tptr = tptr+4; ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ", (EXTRACT_16BITS (tptr) >> 4) , (EXTRACT_16BITS (tptr) >> 3) & 0x01, (EXTRACT_16BITS (tptr) >> 2) & 0x01)); tptr = tptr + 2; len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN; } break; } default: break; } tptr += stlv_len; len -= stlv_len; } return 0; trunc: ND_PRINT((ndo, "\n\t\t")); ND_PRINT((ndo, "%s", tstr)); return(1); }
167,865
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { RemoveInterstitialObservers(old_contents); AddInterstitialObservers(new_contents->web_contents()); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void BrowserCommandController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { RemoveInterstitialObservers(old_contents->web_contents()); AddInterstitialObservers(new_contents->web_contents()); }
171,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: allocate(struct file *file, int allocate_idat) { struct control *control = png_voidcast(struct control*, file->alloc_ptr); if (allocate_idat) { assert(file->idat == NULL); IDAT_init(&control->idat, file); } else /* chunk */ { assert(file->chunk == NULL); chunk_init(&control->chunk, file); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
allocate(struct file *file, int allocate_idat) { struct control *control = voidcast(struct control*, file->alloc_ptr); if (allocate_idat) { assert(file->idat == NULL); IDAT_init(&control->idat, file); } else /* chunk */ { assert(file->chunk == NULL); chunk_init(&control->chunk, file); } }
173,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetNotificationImageSizes", base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
NotificationsNativeHandler::NotificationsNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetNotificationImageSizes", "notifications", base::Bind(&NotificationsNativeHandler::GetNotificationImageSizes, base::Unretained(this))); }
173,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IndexedDBDispatcher::~IndexedDBDispatcher() { g_idb_dispatcher_tls.Pointer()->Set(NULL); } Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created. This could happen if there are IDB objects that survive the call to didStopWorkerRunLoop. BUG=121734 TEST= Review URL: http://codereview.chromium.org/9999035 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
IndexedDBDispatcher::~IndexedDBDispatcher() { g_idb_dispatcher_tls.Pointer()->Set(HAS_BEEN_DELETED); }
171,040
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const extensions::Extension* GetExtension(Profile* profile, const std::string& extension_id) { const ExtensionService* service = extensions::ExtensionSystem::Get(profile)->extension_service(); const extensions::Extension* extension = service->GetInstalledExtension(extension_id); return extension; } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID:
const extensions::Extension* GetExtension(Profile* profile, const std::string& extension_id) { const ExtensionRegistry* registry = ExtensionRegistry::Get(profile); const extensions::Extension* extension = registry->GetInstalledExtension(extension_id); return extension; }
171,720
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, int width, int height) { if (width == image->width) { /* check for integer multiplication overflow */ int64_t check = ((int64_t) image->stride) * ((int64_t) height); if (check != (int)check) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize stride(%d)*height(%d)", image->stride, height); return NULL; } /* use the same stride, just change the length */ image->data = jbig2_renew(ctx, image->data, uint8_t, (int)check); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not resize image buffer!"); return NULL; } if (height > image->height) { memset(image->data + image->height * image->stride, 0, (height - image->height) * image->stride); } image->height = height; } else { /* we must allocate a new image buffer and copy */ jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "jbig2_image_resize called with a different width (NYI)"); } return NULL; } Commit Message: CWE ID: CWE-119
jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, int width, int height) jbig2_image_resize(Jbig2Ctx *ctx, Jbig2Image *image, uint32_t width, uint32_t height) { if (width == image->width) { /* check for integer multiplication overflow */ int64_t check = ((int64_t) image->stride) * ((int64_t) height); if (check != (int)check) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "integer multiplication overflow during resize stride(%d)*height(%d)", image->stride, height); return NULL; } /* use the same stride, just change the length */ image->data = jbig2_renew(ctx, image->data, uint8_t, (int)check); if (image->data == NULL) { jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, "could not resize image buffer!"); return NULL; } if (height > image->height) { memset(image->data + image->height * image->stride, 0, (height - image->height) * image->stride); } image->height = height; } else { /* we must allocate a new image buffer and copy */ jbig2_error(ctx, JBIG2_SEVERITY_WARNING, -1, "jbig2_image_resize called with a different width (NYI)"); } return NULL; }
165,492
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } } 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
Chapters::~Chapters() { while (m_editions_count > 0) { Edition& e = m_editions[--m_editions_count]; e.Clear(); } delete[] m_editions; }
173,869
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac) { struct cm_id_private *cm_id_priv; cm_id_priv = container_of(id, struct cm_id_private, id); if (smac != NULL) memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac)); if (alt_smac != NULL) memcpy(cm_id_priv->alt_av.smac, alt_smac, sizeof(cm_id_priv->alt_av.smac)); return 0; } Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler The code that resolves the passive side source MAC within the rdma_cm connection request handler was both redundant and buggy, so remove it. It was redundant since later, when an RC QP is modified to RTR state, the resolution will take place in the ib_core module. It was buggy because this callback also deals with UD SIDR exchange, for which we incorrectly looked at the REQ member of the CM event and dereferenced a random value. Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures") Signed-off-by: Moni Shoua <monis@mellanox.com> Signed-off-by: Or Gerlitz <ogerlitz@mellanox.com> Signed-off-by: Roland Dreier <roland@purestorage.com> CWE ID: CWE-20
int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)
166,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_mod_end(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { PNG_CONST unsigned int scale = (1U<<that->sample_depth)-1; UNUSED(this) UNUSED(pp) UNUSED(display) /* At the end recalculate the digitized red green and blue values according * to the current sample_depth of the pixel. * * The sample value is simply scaled to the maximum, checking for over * and underflow (which can both happen for some image transforms, * including simple size scaling, though libpng doesn't do that at present. */ that->red = sample_scale(that->redf, scale); /* The error value is increased, at the end, according to the lowest sBIT * value seen. Common sense tells us that the intermediate integer * representations are no more accurate than +/- 0.5 in the integral values, * the sBIT allows the implementation to be worse than this. In addition the * PNG specification actually permits any error within the range (-1..+1), * but that is ignored here. Instead the final digitized value is compared, * below to the digitized value of the error limits - this has the net effect * of allowing (almost) +/-1 in the output value. It's difficult to see how * any algorithm that digitizes intermediate results can be more accurate. */ that->rede += 1./(2*((1U<<that->red_sBIT)-1)); if (that->colour_type & PNG_COLOR_MASK_COLOR) { that->green = sample_scale(that->greenf, scale); that->blue = sample_scale(that->bluef, scale); that->greene += 1./(2*((1U<<that->green_sBIT)-1)); that->bluee += 1./(2*((1U<<that->blue_sBIT)-1)); } else { that->blue = that->green = that->red; that->bluef = that->greenf = that->redf; that->bluee = that->greene = that->rede; } if ((that->colour_type & PNG_COLOR_MASK_ALPHA) || that->colour_type == PNG_COLOR_TYPE_PALETTE) { that->alpha = sample_scale(that->alphaf, scale); that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1)); } else { that->alpha = scale; /* opaque */ that->alpha = 1; /* Override this. */ that->alphae = 0; /* It's exact ;-) */ } } 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_mod_end(PNG_CONST image_transform *this, image_pixel *that, image_transform_mod_end(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { const unsigned int scale = (1U<<that->sample_depth)-1; const int sig_bits = that->sig_bits; UNUSED(this) UNUSED(pp) UNUSED(display) /* At the end recalculate the digitized red green and blue values according * to the current sample_depth of the pixel. * * The sample value is simply scaled to the maximum, checking for over * and underflow (which can both happen for some image transforms, * including simple size scaling, though libpng doesn't do that at present. */ that->red = sample_scale(that->redf, scale); /* This is a bit bogus; really the above calculation should use the red_sBIT * value, not sample_depth, but because libpng does png_set_shift by just * shifting the bits we get errors if we don't do it the same way. */ if (sig_bits && that->red_sBIT < that->sample_depth) that->red >>= that->sample_depth - that->red_sBIT; /* The error value is increased, at the end, according to the lowest sBIT * value seen. Common sense tells us that the intermediate integer * representations are no more accurate than +/- 0.5 in the integral values, * the sBIT allows the implementation to be worse than this. In addition the * PNG specification actually permits any error within the range (-1..+1), * but that is ignored here. Instead the final digitized value is compared, * below to the digitized value of the error limits - this has the net effect * of allowing (almost) +/-1 in the output value. It's difficult to see how * any algorithm that digitizes intermediate results can be more accurate. */ that->rede += 1./(2*((1U<<that->red_sBIT)-1)); if (that->colour_type & PNG_COLOR_MASK_COLOR) { that->green = sample_scale(that->greenf, scale); if (sig_bits && that->green_sBIT < that->sample_depth) that->green >>= that->sample_depth - that->green_sBIT; that->blue = sample_scale(that->bluef, scale); if (sig_bits && that->blue_sBIT < that->sample_depth) that->blue >>= that->sample_depth - that->blue_sBIT; that->greene += 1./(2*((1U<<that->green_sBIT)-1)); that->bluee += 1./(2*((1U<<that->blue_sBIT)-1)); } else { that->blue = that->green = that->red; that->bluef = that->greenf = that->redf; that->bluee = that->greene = that->rede; } if ((that->colour_type & PNG_COLOR_MASK_ALPHA) || that->colour_type == PNG_COLOR_TYPE_PALETTE) { that->alpha = sample_scale(that->alphaf, scale); that->alphae += 1./(2*((1U<<that->alpha_sBIT)-1)); } else { that->alpha = scale; /* opaque */ that->alphaf = 1; /* Override this. */ that->alphae = 0; /* It's exact ;-) */ } if (sig_bits && that->alpha_sBIT < that->sample_depth) that->alpha >>= that->sample_depth - that->alpha_sBIT; }
173,623
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1553 CWE ID: CWE-125
ModuleExport size_t RegisterXWDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("XWD","XWD","X Windows system window dump (color)"); #if defined(MAGICKCORE_X11_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadXWDImage; entry->encoder=(EncodeImageHandler *) WriteXWDImage; #endif entry->magick=(IsImageFormatHandler *) IsXWD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); }
169,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DefragTimeoutTest(void) { int i; int ret = 0; /* Setup a small numberr of trackers. */ if (ConfSet("defrag.trackers", "16") != 1) { printf("ConfSet failed: "); goto end; } DefragInit(); /* Load in 16 packets. */ for (i = 0; i < 16; i++) { Packet *p = BuildTestPacket(i, 0, 1, 'A' + i, 16); if (p == NULL) goto end; Packet *tp = Defrag(NULL, NULL, p, NULL); SCFree(p); if (tp != NULL) { SCFree(tp); goto end; } } /* Build a new packet but push the timestamp out by our timeout. * This should force our previous fragments to be timed out. */ Packet *p = BuildTestPacket(99, 0, 1, 'A' + i, 16); if (p == NULL) goto end; p->ts.tv_sec += (defrag_context->timeout + 1); Packet *tp = Defrag(NULL, NULL, p, NULL); if (tp != NULL) { SCFree(tp); goto end; } DefragTracker *tracker = DefragLookupTrackerFromHash(p); if (tracker == NULL) goto end; if (tracker->id != 99) goto end; SCFree(p); ret = 1; end: DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragTimeoutTest(void) { int i; int ret = 0; /* Setup a small numberr of trackers. */ if (ConfSet("defrag.trackers", "16") != 1) { printf("ConfSet failed: "); goto end; } DefragInit(); /* Load in 16 packets. */ for (i = 0; i < 16; i++) { Packet *p = BuildTestPacket(IPPROTO_ICMP,i, 0, 1, 'A' + i, 16); if (p == NULL) goto end; Packet *tp = Defrag(NULL, NULL, p, NULL); SCFree(p); if (tp != NULL) { SCFree(tp); goto end; } } /* Build a new packet but push the timestamp out by our timeout. * This should force our previous fragments to be timed out. */ Packet *p = BuildTestPacket(IPPROTO_ICMP, 99, 0, 1, 'A' + i, 16); if (p == NULL) goto end; p->ts.tv_sec += (defrag_context->timeout + 1); Packet *tp = Defrag(NULL, NULL, p, NULL); if (tp != NULL) { SCFree(tp); goto end; } DefragTracker *tracker = DefragLookupTrackerFromHash(p); if (tracker == NULL) goto end; if (tracker->id != 99) goto end; SCFree(p); ret = 1; end: DefragDestroy(); return ret; }
168,303
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cisco_autorp_print(netdissect_options *ndo, register const u_char *bp, register u_int len) { int type; int numrps; int hold; ND_TCHECK(bp[0]); ND_PRINT((ndo, " auto-rp ")); type = bp[0]; switch (type) { case 0x11: ND_PRINT((ndo, "candidate-advert")); break; case 0x12: ND_PRINT((ndo, "mapping")); break; default: ND_PRINT((ndo, "type-0x%02x", type)); break; } ND_TCHECK(bp[1]); numrps = bp[1]; ND_TCHECK2(bp[2], 2); ND_PRINT((ndo, " Hold ")); hold = EXTRACT_16BITS(&bp[2]); if (hold) unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); else ND_PRINT((ndo, "FOREVER")); /* Next 4 bytes are reserved. */ bp += 8; len -= 8; /*XXX skip unless -v? */ /* * Rest of packet: * numrps entries of the form: * 32 bits: RP * 6 bits: reserved * 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2". * 8 bits: # of entries for this RP * each entry: 7 bits: reserved, 1 bit: negative, * 8 bits: mask 32 bits: source * lather, rinse, repeat. */ while (numrps--) { int nentries; char s; ND_TCHECK2(bp[0], 4); ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp))); ND_TCHECK(bp[4]); switch (bp[4] & 0x3) { case 0: ND_PRINT((ndo, " PIMv?")); break; case 1: ND_PRINT((ndo, " PIMv1")); break; case 2: ND_PRINT((ndo, " PIMv2")); break; case 3: ND_PRINT((ndo, " PIMv1+2")); break; } if (bp[4] & 0xfc) ND_PRINT((ndo, " [rsvd=0x%02x]", bp[4] & 0xfc)); ND_TCHECK(bp[5]); nentries = bp[5]; bp += 6; len -= 6; s = ' '; for (; nentries; nentries--) { ND_TCHECK2(bp[0], 6); ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "", ipaddr_string(ndo, &bp[2]), bp[1])); if (bp[0] & 0x02) { ND_PRINT((ndo, " bidir")); } if (bp[0] & 0xfc) { ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc)); } s = ','; bp += 6; len -= 6; } } return; trunc: ND_PRINT((ndo, "[|autorp]")); return; } Commit Message: CVE-2017-13030/PIM: Redo bounds checks and add length checks. Use ND_TCHECK macros to do bounds checking, and add length checks before the bounds checks. Add a bounds check that the review process found was missing. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s), modified so the capture file won't be rejected as an invalid capture. Update one test output file to reflect the changes. CWE ID: CWE-125
cisco_autorp_print(netdissect_options *ndo, register const u_char *bp, register u_int len) { int type; int numrps; int hold; if (len < 8) goto trunc; ND_TCHECK(bp[0]); ND_PRINT((ndo, " auto-rp ")); type = bp[0]; switch (type) { case 0x11: ND_PRINT((ndo, "candidate-advert")); break; case 0x12: ND_PRINT((ndo, "mapping")); break; default: ND_PRINT((ndo, "type-0x%02x", type)); break; } ND_TCHECK(bp[1]); numrps = bp[1]; ND_TCHECK2(bp[2], 2); ND_PRINT((ndo, " Hold ")); hold = EXTRACT_16BITS(&bp[2]); if (hold) unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); else ND_PRINT((ndo, "FOREVER")); /* Next 4 bytes are reserved. */ bp += 8; len -= 8; /*XXX skip unless -v? */ /* * Rest of packet: * numrps entries of the form: * 32 bits: RP * 6 bits: reserved * 2 bits: PIM version supported, bit 0 is "supports v1", 1 is "v2". * 8 bits: # of entries for this RP * each entry: 7 bits: reserved, 1 bit: negative, * 8 bits: mask 32 bits: source * lather, rinse, repeat. */ while (numrps--) { int nentries; char s; if (len < 4) goto trunc; ND_TCHECK2(bp[0], 4); ND_PRINT((ndo, " RP %s", ipaddr_string(ndo, bp))); bp += 4; len -= 4; if (len < 1) goto trunc; ND_TCHECK(bp[0]); switch (bp[0] & 0x3) { case 0: ND_PRINT((ndo, " PIMv?")); break; case 1: ND_PRINT((ndo, " PIMv1")); break; case 2: ND_PRINT((ndo, " PIMv2")); break; case 3: ND_PRINT((ndo, " PIMv1+2")); break; } if (bp[0] & 0xfc) ND_PRINT((ndo, " [rsvd=0x%02x]", bp[0] & 0xfc)); bp += 1; len -= 1; if (len < 1) goto trunc; ND_TCHECK(bp[0]); nentries = bp[0]; bp += 1; len -= 1; s = ' '; for (; nentries; nentries--) { if (len < 6) goto trunc; ND_TCHECK2(bp[0], 6); ND_PRINT((ndo, "%c%s%s/%d", s, bp[0] & 1 ? "!" : "", ipaddr_string(ndo, &bp[2]), bp[1])); if (bp[0] & 0x02) { ND_PRINT((ndo, " bidir")); } if (bp[0] & 0xfc) { ND_PRINT((ndo, "[rsvd=0x%02x]", bp[0] & 0xfc)); } s = ','; bp += 6; len -= 6; } } return; trunc: ND_PRINT((ndo, "[|autorp]")); return; }
167,853
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static RList *relocs(RBinFile *arch) { struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj; RList *list = r_list_newf ((RListFree)free); int i, len, n_got, amount; if (!list || !obj) { r_list_free (list); return NULL; } if (obj->hdr->flags & FLAT_FLAG_GOTPIC) { n_got = get_ngot_entries (obj); if (n_got) { amount = n_got * sizeof (ut32); if (amount < n_got || amount > UT32_MAX) { goto out_error; } struct reloc_struct_t *got_table = calloc (1, n_got * sizeof (ut32)); if (got_table) { ut32 offset = 0; for (i = 0; i < n_got ; offset += 4, i++) { ut32 got_entry; if (obj->hdr->data_start + offset + 4 > obj->size || obj->hdr->data_start + offset + 4 < offset) { break; } len = r_buf_read_at (obj->b, obj->hdr->data_start + offset, (ut8 *)&got_entry, sizeof (ut32)); if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) { break; } got_table[i].addr_to_patch = got_entry; got_table[i].data_offset = got_entry + BFLT_HDR_SIZE; } obj->n_got = n_got; obj->got_table = got_table; } } } if (obj->hdr->reloc_count > 0) { int n_reloc = obj->hdr->reloc_count; amount = n_reloc * sizeof (struct reloc_struct_t); if (amount < n_reloc || amount > UT32_MAX) { goto out_error; } struct reloc_struct_t *reloc_table = calloc (1, amount + 1); if (!reloc_table) { goto out_error; } amount = n_reloc * sizeof (ut32); if (amount < n_reloc || amount > UT32_MAX) { free (reloc_table); goto out_error; } ut32 *reloc_pointer_table = calloc (1, amount + 1); if (!reloc_pointer_table) { free (reloc_table); goto out_error; } if (obj->hdr->reloc_start + amount > obj->size || obj->hdr->reloc_start + amount < amount) { free (reloc_table); free (reloc_pointer_table); goto out_error; } len = r_buf_read_at (obj->b, obj->hdr->reloc_start, (ut8 *)reloc_pointer_table, amount); if (len != amount) { free (reloc_table); free (reloc_pointer_table); goto out_error; } for (i = 0; i < obj->hdr->reloc_count; i++) { ut32 reloc_offset = r_swap_ut32 (reloc_pointer_table[i]) + BFLT_HDR_SIZE; if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) { ut32 reloc_fixed, reloc_data_offset; if (reloc_offset + sizeof (ut32) > obj->size || reloc_offset + sizeof (ut32) < reloc_offset) { free (reloc_table); free (reloc_pointer_table); goto out_error; } len = r_buf_read_at (obj->b, reloc_offset, (ut8 *)&reloc_fixed, sizeof (ut32)); if (len != sizeof (ut32)) { eprintf ("problem while reading relocation entries\n"); free (reloc_table); free (reloc_pointer_table); goto out_error; } reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE; reloc_table[i].addr_to_patch = reloc_offset; reloc_table[i].data_offset = reloc_data_offset; RBinReloc *reloc = R_NEW0 (RBinReloc); if (reloc) { reloc->type = R_BIN_RELOC_32; reloc->paddr = reloc_table[i].addr_to_patch; reloc->vaddr = reloc->paddr; r_list_append (list, reloc); } } } free (reloc_pointer_table); obj->reloc_table = reloc_table; } return list; out_error: r_list_free (list); return NULL; } Commit Message: Fix #6829 oob write because of using wrong struct CWE ID: CWE-119
static RList *relocs(RBinFile *arch) { struct r_bin_bflt_obj *obj = (struct r_bin_bflt_obj*)arch->o->bin_obj; RList *list = r_list_newf ((RListFree)free); int i, len, n_got, amount; if (!list || !obj) { r_list_free (list); return NULL; } if (obj->hdr->flags & FLAT_FLAG_GOTPIC) { n_got = get_ngot_entries (obj); if (n_got) { amount = n_got * sizeof (ut32); if (amount < n_got || amount > UT32_MAX) { goto out_error; } struct reloc_struct_t *got_table = calloc ( 1, n_got * sizeof (struct reloc_struct_t)); if (got_table) { ut32 offset = 0; for (i = 0; i < n_got ; offset += 4, i++) { ut32 got_entry; if (obj->hdr->data_start + offset + 4 > obj->size || obj->hdr->data_start + offset + 4 < offset) { break; } len = r_buf_read_at (obj->b, obj->hdr->data_start + offset, (ut8 *)&got_entry, sizeof (ut32)); if (!VALID_GOT_ENTRY (got_entry) || len != sizeof (ut32)) { break; } got_table[i].addr_to_patch = got_entry; got_table[i].data_offset = got_entry + BFLT_HDR_SIZE; } obj->n_got = n_got; obj->got_table = got_table; } } } if (obj->hdr->reloc_count > 0) { int n_reloc = obj->hdr->reloc_count; amount = n_reloc * sizeof (struct reloc_struct_t); if (amount < n_reloc || amount > UT32_MAX) { goto out_error; } struct reloc_struct_t *reloc_table = calloc (1, amount + 1); if (!reloc_table) { goto out_error; } amount = n_reloc * sizeof (ut32); if (amount < n_reloc || amount > UT32_MAX) { free (reloc_table); goto out_error; } ut32 *reloc_pointer_table = calloc (1, amount + 1); if (!reloc_pointer_table) { free (reloc_table); goto out_error; } if (obj->hdr->reloc_start + amount > obj->size || obj->hdr->reloc_start + amount < amount) { free (reloc_table); free (reloc_pointer_table); goto out_error; } len = r_buf_read_at (obj->b, obj->hdr->reloc_start, (ut8 *)reloc_pointer_table, amount); if (len != amount) { free (reloc_table); free (reloc_pointer_table); goto out_error; } for (i = 0; i < obj->hdr->reloc_count; i++) { ut32 reloc_offset = r_swap_ut32 (reloc_pointer_table[i]) + BFLT_HDR_SIZE; if (reloc_offset < obj->hdr->bss_end && reloc_offset < obj->size) { ut32 reloc_fixed, reloc_data_offset; if (reloc_offset + sizeof (ut32) > obj->size || reloc_offset + sizeof (ut32) < reloc_offset) { free (reloc_table); free (reloc_pointer_table); goto out_error; } len = r_buf_read_at (obj->b, reloc_offset, (ut8 *)&reloc_fixed, sizeof (ut32)); if (len != sizeof (ut32)) { eprintf ("problem while reading relocation entries\n"); free (reloc_table); free (reloc_pointer_table); goto out_error; } reloc_data_offset = r_swap_ut32 (reloc_fixed) + BFLT_HDR_SIZE; reloc_table[i].addr_to_patch = reloc_offset; reloc_table[i].data_offset = reloc_data_offset; RBinReloc *reloc = R_NEW0 (RBinReloc); if (reloc) { reloc->type = R_BIN_RELOC_32; reloc->paddr = reloc_table[i].addr_to_patch; reloc->vaddr = reloc->paddr; r_list_append (list, reloc); } } } free (reloc_pointer_table); obj->reloc_table = reloc_table; } return list; out_error: r_list_free (list); return NULL; }
168,364
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_venc::component_deinit(OMX_IN OMX_HANDLETYPE hComp) { (void) hComp; OMX_U32 i = 0; DEBUG_PRINT_HIGH("omx_venc(): Inside component_deinit()"); if (OMX_StateLoaded != m_state) { DEBUG_PRINT_ERROR("WARNING:Rxd DeInit,OMX not in LOADED state %d",\ m_state); } if (m_out_mem_ptr) { DEBUG_PRINT_LOW("Freeing the Output Memory"); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++ ) { free_output_buffer (&m_out_mem_ptr[i]); } free(m_out_mem_ptr); m_out_mem_ptr = NULL; } /*Check if the input buffers have to be cleaned up*/ if (m_inp_mem_ptr #ifdef _ANDROID_ICS_ && !meta_mode_enable #endif ) { DEBUG_PRINT_LOW("Freeing the Input Memory"); for (i=0; i<m_sInPortDef.nBufferCountActual; i++ ) { free_input_buffer (&m_inp_mem_ptr[i]); } free(m_inp_mem_ptr); m_inp_mem_ptr = NULL; } m_ftb_q.m_size=0; m_cmd_q.m_size=0; m_etb_q.m_size=0; m_ftb_q.m_read = m_ftb_q.m_write =0; m_cmd_q.m_read = m_cmd_q.m_write =0; m_etb_q.m_read = m_etb_q.m_write =0; #ifdef _ANDROID_ DEBUG_PRINT_HIGH("Calling m_heap_ptr.clear()"); m_heap_ptr.clear(); #endif // _ANDROID_ DEBUG_PRINT_HIGH("Calling venc_close()"); if (handle) { handle->venc_close(); DEBUG_PRINT_HIGH("Deleting HANDLE[%p]", handle); delete (handle); handle = NULL; } DEBUG_PRINT_INFO("Component Deinit"); return OMX_ErrorNone; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add safety checks for freeing buffers Allow only up to 64 buffers on input/output port (since the allocation bitmap is only 64-wide). Add safety checks to free only as many buffers were allocated. Fixes: Heap Overflow and Possible Local Privilege Escalation in MediaServer (libOmxVenc problem) Bug: 27532497 Change-Id: I31e576ef9dc542df73aa6b0ea113d72724b50fc6 CWE ID: CWE-119
OMX_ERRORTYPE omx_venc::component_deinit(OMX_IN OMX_HANDLETYPE hComp) { (void) hComp; OMX_U32 i = 0; DEBUG_PRINT_HIGH("omx_venc(): Inside component_deinit()"); if (OMX_StateLoaded != m_state) { DEBUG_PRINT_ERROR("WARNING:Rxd DeInit,OMX not in LOADED state %d",\ m_state); } if (m_out_mem_ptr) { DEBUG_PRINT_LOW("Freeing the Output Memory"); for (i=0; i< m_sOutPortDef.nBufferCountActual; i++ ) { if (BITMASK_PRESENT(&m_out_bm_count, i)) { BITMASK_CLEAR(&m_out_bm_count, i); free_output_buffer (&m_out_mem_ptr[i]); } if (release_output_done()) { break; } } free(m_out_mem_ptr); m_out_mem_ptr = NULL; } /*Check if the input buffers have to be cleaned up*/ if (m_inp_mem_ptr #ifdef _ANDROID_ICS_ && !meta_mode_enable #endif ) { DEBUG_PRINT_LOW("Freeing the Input Memory"); for (i=0; i<m_sInPortDef.nBufferCountActual; i++ ) { if (BITMASK_PRESENT(&m_inp_bm_count, i)) { BITMASK_CLEAR(&m_inp_bm_count, i); free_input_buffer (&m_inp_mem_ptr[i]); } if (release_input_done()) { break; } } free(m_inp_mem_ptr); m_inp_mem_ptr = NULL; } m_ftb_q.m_size=0; m_cmd_q.m_size=0; m_etb_q.m_size=0; m_ftb_q.m_read = m_ftb_q.m_write =0; m_cmd_q.m_read = m_cmd_q.m_write =0; m_etb_q.m_read = m_etb_q.m_write =0; #ifdef _ANDROID_ DEBUG_PRINT_HIGH("Calling m_heap_ptr.clear()"); m_heap_ptr.clear(); #endif // _ANDROID_ DEBUG_PRINT_HIGH("Calling venc_close()"); if (handle) { handle->venc_close(); DEBUG_PRINT_HIGH("Deleting HANDLE[%p]", handle); delete (handle); handle = NULL; } DEBUG_PRINT_INFO("Component Deinit"); return OMX_ErrorNone; }
173,782
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin( Profile* profile, const url::Origin& origin) { SiteCharacteristicsDataStore* data_store = LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile); EXPECT_TRUE(data_store); std::unique_ptr<SiteCharacteristicsDataReader> reader = data_store->GetReaderForOrigin(origin); internal::LocalSiteCharacteristicsDataImpl* impl = static_cast<LocalSiteCharacteristicsDataReader*>(reader.get()) ->impl_for_testing() .get(); while (!impl->site_characteristics_for_testing().IsInitialized()) base::RunLoop().RunUntilIdle(); return reader; } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
std::unique_ptr<SiteCharacteristicsDataReader> GetReaderForOrigin( Profile* profile, const url::Origin& origin) { SiteCharacteristicsDataStore* data_store = LocalSiteCharacteristicsDataStoreFactory::GetForProfile(profile); EXPECT_TRUE(data_store); std::unique_ptr<SiteCharacteristicsDataReader> reader = data_store->GetReaderForOrigin(origin); const internal::LocalSiteCharacteristicsDataImpl* impl = static_cast<LocalSiteCharacteristicsDataReader*>(reader.get()) ->impl_for_testing(); while (!impl->site_characteristics_for_testing().IsInitialized()) base::RunLoop().RunUntilIdle(); return reader; }
172,215
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: check_mountpoint(const char *progname, char *mountpoint) { int err; struct stat statbuf; /* does mountpoint exist and is it a directory? */ err = stat(mountpoint, &statbuf); if (err) { fprintf(stderr, "%s: failed to stat %s: %s\n", progname, mountpoint, strerror(errno)); return EX_USAGE; } if (!S_ISDIR(statbuf.st_mode)) { fprintf(stderr, "%s: %s is not a directory!", progname, mountpoint); return EX_USAGE; } #if CIFS_LEGACY_SETUID_CHECK /* do extra checks on mountpoint for legacy setuid behavior */ if (!getuid() || geteuid()) return 0; if (statbuf.st_uid != getuid()) { fprintf(stderr, "%s: %s is not owned by user\n", progname, mountpoint); return EX_USAGE; } if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) { fprintf(stderr, "%s: invalid permissions on %s\n", progname, mountpoint); return EX_USAGE; } #endif /* CIFS_LEGACY_SETUID_CHECK */ return 0; } Commit Message: CWE ID: CWE-59
check_mountpoint(const char *progname, char *mountpoint) { int err; struct stat statbuf; /* does mountpoint exist and is it a directory? */ err = stat(".", &statbuf); if (err) { fprintf(stderr, "%s: failed to stat %s: %s\n", progname, mountpoint, strerror(errno)); return EX_USAGE; } if (!S_ISDIR(statbuf.st_mode)) { fprintf(stderr, "%s: %s is not a directory!", progname, mountpoint); return EX_USAGE; } #if CIFS_LEGACY_SETUID_CHECK /* do extra checks on mountpoint for legacy setuid behavior */ if (!getuid() || geteuid()) return 0; if (statbuf.st_uid != getuid()) { fprintf(stderr, "%s: %s is not owned by user\n", progname, mountpoint); return EX_USAGE; } if ((statbuf.st_mode & S_IRWXU) != S_IRWXU) { fprintf(stderr, "%s: invalid permissions on %s\n", progname, mountpoint); return EX_USAGE; } #endif /* CIFS_LEGACY_SETUID_CHECK */ return 0; }
165,168
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; assert(p); delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pSeekHead; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
Segment::~Segment() { const long count = m_clusterCount + m_clusterPreloadCount; Cluster** i = m_clusters; Cluster** j = m_clusters + count; while (i != j) { Cluster* const p = *i++; delete p; } delete[] m_clusters; delete m_pTracks; delete m_pInfo; delete m_pCues; delete m_pChapters; delete m_pTags; delete m_pSeekHead; }
173,870
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_be_int (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 4) { psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_int */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_int (SF_PRIVATE *psf, int x) { psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_int */
170,051
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option) { ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option); Mutex::Autolock lock(mLock); Mutex::Autolock glock(sLock); mThumbnail.clear(); if (mRetriever == NULL) { ALOGE("retriever is not initialized"); return NULL; } VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option); if (frame == NULL) { ALOGE("failed to capture a video frame"); return NULL; } size_t size = sizeof(VideoFrame) + frame->mSize; sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient"); if (heap == NULL) { ALOGE("failed to create MemoryDealer"); delete frame; return NULL; } mThumbnail = new MemoryBase(heap, 0, size); if (mThumbnail == NULL) { ALOGE("not enough memory for VideoFrame size=%u", size); delete frame; return NULL; } VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer()); frameCopy->mWidth = frame->mWidth; frameCopy->mHeight = frame->mHeight; frameCopy->mDisplayWidth = frame->mDisplayWidth; frameCopy->mDisplayHeight = frame->mDisplayHeight; frameCopy->mSize = frame->mSize; frameCopy->mRotationAngle = frame->mRotationAngle; ALOGV("rotation: %d", frameCopy->mRotationAngle); frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame); memcpy(frameCopy->mData, frame->mData, frame->mSize); delete frame; // Fix memory leakage return mThumbnail; } Commit Message: Clear unused pointer field when sending across binder Bug: 28377502 Change-Id: Iad5ebfb0a9ef89f09755bb332579dbd3534f9c98 CWE ID: CWE-20
sp<IMemory> MetadataRetrieverClient::getFrameAtTime(int64_t timeUs, int option) { ALOGV("getFrameAtTime: time(%lld us) option(%d)", timeUs, option); Mutex::Autolock lock(mLock); Mutex::Autolock glock(sLock); mThumbnail.clear(); if (mRetriever == NULL) { ALOGE("retriever is not initialized"); return NULL; } VideoFrame *frame = mRetriever->getFrameAtTime(timeUs, option); if (frame == NULL) { ALOGE("failed to capture a video frame"); return NULL; } size_t size = sizeof(VideoFrame) + frame->mSize; sp<MemoryHeapBase> heap = new MemoryHeapBase(size, 0, "MetadataRetrieverClient"); if (heap == NULL) { ALOGE("failed to create MemoryDealer"); delete frame; return NULL; } mThumbnail = new MemoryBase(heap, 0, size); if (mThumbnail == NULL) { ALOGE("not enough memory for VideoFrame size=%u", size); delete frame; return NULL; } VideoFrame *frameCopy = static_cast<VideoFrame *>(mThumbnail->pointer()); frameCopy->mWidth = frame->mWidth; frameCopy->mHeight = frame->mHeight; frameCopy->mDisplayWidth = frame->mDisplayWidth; frameCopy->mDisplayHeight = frame->mDisplayHeight; frameCopy->mSize = frame->mSize; frameCopy->mRotationAngle = frame->mRotationAngle; ALOGV("rotation: %d", frameCopy->mRotationAngle); frameCopy->mData = (uint8_t *)frameCopy + sizeof(VideoFrame); memcpy(frameCopy->mData, frame->mData, frame->mSize); frameCopy->mData = 0; delete frame; // Fix memory leakage return mThumbnail; }
173,550
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: NetworkLibrary* CrosLibrary::GetNetworkLibrary() { return network_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
170,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PrintPreviewMessageHandler::PrintPreviewMessageHandler( WebContents* web_contents) : content::WebContentsObserver(web_contents) { DCHECK(web_contents); } Commit Message: Use pdf compositor service for printing when OOPIF is enabled When OOPIF is enabled (by site-per-process flag or top-document-isolation feature), use the pdf compositor service for converting PaintRecord to PDF on renderers. In the future, this will make compositing PDF from multiple renderers possible. TBR=jzfeng@chromium.org BUG=455764 Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f Reviewed-on: https://chromium-review.googlesource.com/699765 Commit-Queue: Wei Li <weili@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Reviewed-by: Lei Zhang <thestig@chromium.org> Cr-Commit-Position: refs/heads/master@{#511616} CWE ID: CWE-254
PrintPreviewMessageHandler::PrintPreviewMessageHandler( WebContents* web_contents) : content::WebContentsObserver(web_contents), weak_ptr_factory_(this) { DCHECK(web_contents); }
171,891
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameLoader::StopAllLoaders() { if (frame_->GetDocument()->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; if (in_stop_all_loaders_) return; in_stop_all_loaders_ = true; for (Frame* child = frame_->Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->Loader().StopAllLoaders(); } frame_->GetDocument()->CancelParsing(); if (document_loader_) document_loader_->Fetcher()->StopFetching(); if (!protect_provisional_loader_) DetachDocumentLoader(provisional_document_loader_); frame_->GetNavigationScheduler().Cancel(); if (document_loader_ && !document_loader_->SentDidFinishLoad()) { document_loader_->LoadFailed( ResourceError::CancelledError(document_loader_->Url())); } in_stop_all_loaders_ = false; TakeObjectSnapshot(); } Commit Message: Fix detach with open()ed document leaving parent loading indefinitely Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Bug: 803416 Test: fast/loader/document-open-iframe-then-detach.html Change-Id: I26c2a054b9f1e5eb076acd677e1223058825f6d6 Reviewed-on: https://chromium-review.googlesource.com/887298 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Nate Chapin <japhet@chromium.org> Cr-Commit-Position: refs/heads/master@{#532967} CWE ID: CWE-362
void FrameLoader::StopAllLoaders() { if (frame_->GetDocument()->PageDismissalEventBeingDispatched() != Document::kNoDismissal) return; if (in_stop_all_loaders_) return; AutoReset<bool> in_stop_all_loaders(&in_stop_all_loaders_, true); for (Frame* child = frame_->Tree().FirstChild(); child; child = child->Tree().NextSibling()) { if (child->IsLocalFrame()) ToLocalFrame(child)->Loader().StopAllLoaders(); } frame_->GetDocument()->CancelParsing(); if (document_loader_) document_loader_->StopLoading(); if (!protect_provisional_loader_) DetachDocumentLoader(provisional_document_loader_); frame_->GetNavigationScheduler().Cancel(); DidFinishNavigation(); TakeObjectSnapshot(); }
171,852
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutofillDialogViews::SectionContainer::SetActive(bool active) { bool is_active = active && proxy_button_->visible(); if (is_active == !!background()) return; set_background(is_active ? views::Background::CreateSolidBackground(kShadingColor) : NULL); SchedulePaint(); } Commit Message: Clear out some minor TODOs. BUG=none Review URL: https://codereview.chromium.org/1047063002 Cr-Commit-Position: refs/heads/master@{#322959} CWE ID: CWE-20
void AutofillDialogViews::SectionContainer::SetActive(bool active) { bool is_active = active && proxy_button_->visible(); if (is_active == !!background()) return; set_background( is_active ? views::Background::CreateSolidBackground(kLightShadingColor) : NULL); SchedulePaint(); }
171,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: stf_status ikev2parent_inI2outR2(struct msg_digest *md) { struct state *st = md->st; /* struct connection *c = st->st_connection; */ /* * the initiator sent us an encrypted payload. We need to calculate * our g^xy, and skeyseed values, and then decrypt the payload. */ DBG(DBG_CONTROLMORE, DBG_log( "ikev2 parent inI2outR2: calculating g^{xy} in order to decrypt I2")); /* verify that there is in fact an encrypted payload */ if (!md->chain[ISAKMP_NEXT_v2E]) { libreswan_log("R2 state should receive an encrypted payload"); reset_globals(); return STF_FATAL; } /* now. we need to go calculate the g^xy */ { struct dh_continuation *dh = alloc_thing( struct dh_continuation, "ikev2_inI2outR2 KE"); stf_status e; dh->md = md; set_suspended(st, dh->md); pcrc_init(&dh->dh_pcrc); dh->dh_pcrc.pcrc_func = ikev2_parent_inI2outR2_continue; e = start_dh_v2(&dh->dh_pcrc, st, st->st_import, RESPONDER, st->st_oakley.groupnum); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } reset_globals(); return e; } } Commit Message: SECURITY: Properly handle IKEv2 I1 notification packet without KE payload CWE ID: CWE-20
stf_status ikev2parent_inI2outR2(struct msg_digest *md) { struct state *st = md->st; /* struct connection *c = st->st_connection; */ /* * the initiator sent us an encrypted payload. We need to calculate * our g^xy, and skeyseed values, and then decrypt the payload. */ DBG(DBG_CONTROLMORE, DBG_log( "ikev2 parent inI2outR2: calculating g^{xy} in order to decrypt I2")); /* verify that there is in fact an encrypted payload */ if (!md->chain[ISAKMP_NEXT_v2E]) { libreswan_log("R2 state should receive an encrypted payload"); reset_globals(); /* XXX suspicious - why was this deemed neccessary? */ return STF_FATAL; } /* now. we need to go calculate the g^xy */ { struct dh_continuation *dh = alloc_thing( struct dh_continuation, "ikev2_inI2outR2 KE"); stf_status e; dh->md = md; set_suspended(st, dh->md); pcrc_init(&dh->dh_pcrc); dh->dh_pcrc.pcrc_func = ikev2_parent_inI2outR2_continue; e = start_dh_v2(&dh->dh_pcrc, st, st->st_import, RESPONDER, st->st_oakley.groupnum); if (e != STF_SUSPEND && e != STF_INLINE) { loglog(RC_CRYPTOFAILED, "system too busy"); delete_state(st); } reset_globals(); return e; } }
166,475
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ptaReadStream(FILE *fp) { char typestr[128]; l_int32 i, n, ix, iy, type, version; l_float32 x, y; PTA *pta; PROCNAME("ptaReadStream"); if (!fp) return (PTA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\n Pta Version %d\n", &version) != 1) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (version != PTA_VERSION_NUMBER) return (PTA *)ERROR_PTR("invalid pta version", procName, NULL); if (fscanf(fp, " Number of pts = %d; format = %s\n", &n, typestr) != 2) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (!strcmp(typestr, "float")) type = 0; else /* typestr is "integer" */ type = 1; if ((pta = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = 0; i < n; i++) { if (type == 0) { /* data is float */ if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading floats", procName, NULL); } ptaAddPt(pta, x, y); } else { /* data is integer */ if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading ints", procName, NULL); } ptaAddPt(pta, ix, iy); } } return pta; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
ptaReadStream(FILE *fp) { char typestr[128]; /* hardcoded below in fscanf */ l_int32 i, n, ix, iy, type, version; l_float32 x, y; PTA *pta; PROCNAME("ptaReadStream"); if (!fp) return (PTA *)ERROR_PTR("stream not defined", procName, NULL); if (fscanf(fp, "\n Pta Version %d\n", &version) != 1) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (version != PTA_VERSION_NUMBER) return (PTA *)ERROR_PTR("invalid pta version", procName, NULL); if (fscanf(fp, " Number of pts = %d; format = %127s\n", &n, typestr) != 2) return (PTA *)ERROR_PTR("not a pta file", procName, NULL); if (!strcmp(typestr, "float")) type = 0; else /* typestr is "integer" */ type = 1; if ((pta = ptaCreate(n)) == NULL) return (PTA *)ERROR_PTR("pta not made", procName, NULL); for (i = 0; i < n; i++) { if (type == 0) { /* data is float */ if (fscanf(fp, " (%f, %f)\n", &x, &y) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading floats", procName, NULL); } ptaAddPt(pta, x, y); } else { /* data is integer */ if (fscanf(fp, " (%d, %d)\n", &ix, &iy) != 2) { ptaDestroy(&pta); return (PTA *)ERROR_PTR("error reading ints", procName, NULL); } ptaAddPt(pta, ix, iy); } } return pta; }
169,328
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; if (data_size <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Integer overflow in data size"); RETURN_FALSE; } data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); }
167,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sparse_dump_region (struct tar_sparse_file *file, size_t i) { union block *blk; off_t bytes_left = file->stat_info->sparse_map[i].numbytes; if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset)) return false; while (bytes_left > 0) { size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left; size_t bytes_read; blk = find_next_block (); bytes_read = safe_read (file->fd, blk->buffer, bufsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left), bufsize); return false; } memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read); bytes_left -= bytes_read; { size_t count; size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size; union block *blk = find_next_block (); if (!blk) { ERROR ((0, 0, _("Unexpected EOF in archive"))); return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) { write_error_details (file->stat_info->orig_file_name, count, wrbytes); return false; } } return true; } /* Interface functions */ enum dump_status sparse_dump_file (int fd, struct tar_stat_info *st) { return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) rc = sparse_scan_file (&file); if (rc && file.optab->dump_region) { tar_sparse_dump_header (&file); if (fd >= 0) { size_t i; mv_begin_write (file.stat_info->file_name, file.stat_info->stat.st_size, file.stat_info->archive_file_size - file.dumped_size); for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++) rc = tar_sparse_dump_region (&file, i); } } pad_archive (file.stat_info->archive_file_size - file.dumped_size); return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short; } Commit Message: CWE ID: CWE-835
sparse_dump_region (struct tar_sparse_file *file, size_t i) { union block *blk; off_t bytes_left = file->stat_info->sparse_map[i].numbytes; if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset)) return false; while (bytes_left > 0) { size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left; size_t bytes_read; blk = find_next_block (); bytes_read = safe_read (file->fd, blk->buffer, bufsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left), bufsize); return false; } else if (bytes_read == 0) { char buf[UINTMAX_STRSIZE_BOUND]; struct stat st; size_t n; if (fstat (file->fd, &st) == 0) n = file->stat_info->stat.st_size - st.st_size; else n = file->stat_info->stat.st_size - (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left); WARNOPT (WARN_FILE_SHRANK, (0, 0, ngettext ("%s: File shrank by %s byte; padding with zeros", "%s: File shrank by %s bytes; padding with zeros", n), quotearg_colon (file->stat_info->orig_file_name), STRINGIFY_BIGINT (n, buf))); if (! ignore_failed_read_option) set_exit_status (TAREXIT_DIFFERS); return false; } memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read); bytes_left -= bytes_read; { size_t count; size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size; union block *blk = find_next_block (); if (!blk) { ERROR ((0, 0, _("Unexpected EOF in archive"))); return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) { write_error_details (file->stat_info->orig_file_name, count, wrbytes); return false; } } return true; } /* Interface functions */ enum dump_status sparse_dump_file (int fd, struct tar_stat_info *st) { return false; } set_next_block_after (blk); file->dumped_size += BLOCKSIZE; count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) rc = sparse_scan_file (&file); if (rc && file.optab->dump_region) { tar_sparse_dump_header (&file); if (fd >= 0) { size_t i; mv_begin_write (file.stat_info->file_name, file.stat_info->stat.st_size, file.stat_info->archive_file_size - file.dumped_size); for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++) rc = tar_sparse_dump_region (&file, i); } } pad_archive (file.stat_info->archive_file_size - file.dumped_size); return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short; }
164,596
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ApiTestEnvironment::RegisterModules() { v8_schema_registry_.reset(new V8SchemaRegistry); const std::vector<std::pair<std::string, int> > resources = Dispatcher::GetJsResources(); for (std::vector<std::pair<std::string, int> >::const_iterator resource = resources.begin(); resource != resources.end(); ++resource) { if (resource->first != "test_environment_specific_bindings") env()->RegisterModule(resource->first, resource->second); } Dispatcher::RegisterNativeHandlers(env()->module_system(), env()->context(), NULL, NULL, v8_schema_registry_.get()); env()->module_system()->RegisterNativeHandler( "process", scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler( env()->context(), env()->context()->GetExtensionID(), env()->context()->GetContextTypeDescription(), false, false, 2, false))); env()->RegisterTestFile("test_environment_specific_bindings", "unit_test_environment_specific_bindings.js"); env()->OverrideNativeHandler("activityLogger", "exports.LogAPICall = function() {};"); env()->OverrideNativeHandler( "apiDefinitions", "exports.GetExtensionAPIDefinitionsForTest = function() { return [] };"); env()->OverrideNativeHandler( "event_natives", "exports.AttachEvent = function() {};" "exports.DetachEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.AttachFilteredEvent = function() {};" "exports.MatchAgainstEventFilter = function() { return [] };"); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Core::kModuleName, mojo::js::Core::GetModule(env()->isolate())); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Support::kModuleName, mojo::js::Support::GetModule(env()->isolate())); gin::Handle<TestServiceProvider> service_provider = TestServiceProvider::Create(env()->isolate()); service_provider_ = service_provider.get(); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), "content/public/renderer/service_provider", service_provider.ToV8()); } Commit Message: [Extensions] Don't allow built-in extensions code to be overridden BUG=546677 Review URL: https://codereview.chromium.org/1417513003 Cr-Commit-Position: refs/heads/master@{#356654} CWE ID: CWE-264
void ApiTestEnvironment::RegisterModules() { v8_schema_registry_.reset(new V8SchemaRegistry); const std::vector<std::pair<std::string, int> > resources = Dispatcher::GetJsResources(); for (std::vector<std::pair<std::string, int> >::const_iterator resource = resources.begin(); resource != resources.end(); ++resource) { if (resource->first != "test_environment_specific_bindings") env()->RegisterModule(resource->first, resource->second); } Dispatcher::RegisterNativeHandlers(env()->module_system(), env()->context(), NULL, NULL, v8_schema_registry_.get()); env()->module_system()->RegisterNativeHandler( "process", scoped_ptr<NativeHandler>(new ProcessInfoNativeHandler( env()->context(), env()->context()->GetExtensionID(), env()->context()->GetContextTypeDescription(), false, false, 2, false))); env()->RegisterTestFile("test_environment_specific_bindings", "unit_test_environment_specific_bindings.js"); env()->OverrideNativeHandler("activityLogger", "exports.$set('LogAPICall', function() {});"); env()->OverrideNativeHandler( "apiDefinitions", "exports.$set('GetExtensionAPIDefinitionsForTest'," "function() { return [] });"); env()->OverrideNativeHandler( "event_natives", "exports.$set('AttachEvent', function() {});" "exports.$set('DetachEvent', function() {});" "exports.$set('AttachFilteredEvent', function() {});" "exports.$set('AttachFilteredEvent', function() {});" "exports.$set('MatchAgainstEventFilter', function() { return [] });"); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Core::kModuleName, mojo::js::Core::GetModule(env()->isolate())); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), mojo::js::Support::kModuleName, mojo::js::Support::GetModule(env()->isolate())); gin::Handle<TestServiceProvider> service_provider = TestServiceProvider::Create(env()->isolate()); service_provider_ = service_provider.get(); gin::ModuleRegistry::From(env()->context()->v8_context()) ->AddBuiltinModule(env()->isolate(), "content/public/renderer/service_provider", service_provider.ToV8()); }
172,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) //error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; //consume payload assert(pos <= stop); } return 0; } Commit Message: 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 ContentEncoding::ParseContentEncAESSettingsEntry( long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes) { assert(pReader); assert(aes); long long pos = start; const long long stop = start + size; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == 0x7E8) { aes->cipher_mode = UnserializeUInt(pReader, pos, size); if (aes->cipher_mode != 1) return E_FILE_FORMAT_INVALID; } pos += size; // consume payload assert(pos <= stop); } return 0; }
174,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AriaCurrentState AXNodeObject::ariaCurrentState() const { const AtomicString& attributeValue = getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent); if (attributeValue.isNull()) return AriaCurrentStateUndefined; if (attributeValue.isEmpty() || equalIgnoringCase(attributeValue, "false")) return AriaCurrentStateFalse; if (equalIgnoringCase(attributeValue, "true")) return AriaCurrentStateTrue; if (equalIgnoringCase(attributeValue, "page")) return AriaCurrentStatePage; if (equalIgnoringCase(attributeValue, "step")) return AriaCurrentStateStep; if (equalIgnoringCase(attributeValue, "location")) return AriaCurrentStateLocation; if (equalIgnoringCase(attributeValue, "date")) return AriaCurrentStateDate; if (equalIgnoringCase(attributeValue, "time")) return AriaCurrentStateTime; if (!attributeValue.isEmpty()) return AriaCurrentStateTrue; return AXObject::ariaCurrentState(); } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
AriaCurrentState AXNodeObject::ariaCurrentState() const { const AtomicString& attributeValue = getAOMPropertyOrARIAAttribute(AOMStringProperty::kCurrent); if (attributeValue.isNull()) return AriaCurrentStateUndefined; if (attributeValue.isEmpty() || equalIgnoringASCIICase(attributeValue, "false")) return AriaCurrentStateFalse; if (equalIgnoringASCIICase(attributeValue, "true")) return AriaCurrentStateTrue; if (equalIgnoringASCIICase(attributeValue, "page")) return AriaCurrentStatePage; if (equalIgnoringASCIICase(attributeValue, "step")) return AriaCurrentStateStep; if (equalIgnoringASCIICase(attributeValue, "location")) return AriaCurrentStateLocation; if (equalIgnoringASCIICase(attributeValue, "date")) return AriaCurrentStateDate; if (equalIgnoringASCIICase(attributeValue, "time")) return AriaCurrentStateTime; if (!attributeValue.isEmpty()) return AriaCurrentStateTrue; return AXObject::ariaCurrentState(); }
171,908
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void do_free_upto(BIO *f, BIO *upto) { if (upto) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f != upto); } else BIO_free_all(f); } Commit Message: Canonicalise input in CMS_verify. If content is detached and not binary mode translate the input to CRLF format. Before this change the input was verified verbatim which lead to a discrepancy between sign and verify. CWE ID: CWE-399
static void do_free_upto(BIO *f, BIO *upto) { if (upto) { BIO *tbio; do { tbio = BIO_pop(f); BIO_free(f); f = tbio; } while (f && f != upto); } else BIO_free_all(f); }
166,690
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Chapters::Edition::ShallowCopy(Edition& rhs) const { rhs.m_atoms = m_atoms; rhs.m_atoms_size = m_atoms_size; rhs.m_atoms_count = m_atoms_count; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
void Chapters::Edition::ShallowCopy(Edition& rhs) const rhs.m_displays = m_displays; rhs.m_displays_size = m_displays_size; rhs.m_displays_count = m_displays_count; }
174,441
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void TestBlinkPlatformSupport::cryptographicallyRandomValues( unsigned char* buffer, size_t length) { } Commit Message: Add assertions that the empty Platform::cryptographicallyRandomValues() overrides are not being used. These implementations are not safe and look scary if not accompanied by an assertion. Also one of the comments was incorrect. BUG=552749 Review URL: https://codereview.chromium.org/1419293005 Cr-Commit-Position: refs/heads/master@{#359229} CWE ID: CWE-310
void TestBlinkPlatformSupport::cryptographicallyRandomValues( unsigned char* buffer, size_t length) { base::RandBytes(buffer, length); }
172,238
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi, HB_GPOS_SubTable* st, HB_Buffer buffer, HB_UShort flags, HB_UShort context_length, int nesting_level ) { HB_UShort i, j, mark1_index, mark2_index, property, class; HB_Fixed x_mark1_value, y_mark1_value, x_mark2_value, y_mark2_value; HB_Error error; HB_GPOSHeader* gpos = gpi->gpos; HB_MarkMarkPos* mmp = &st->markmark; HB_MarkArray* ma1; HB_Mark2Array* ma2; HB_Mark2Record* m2r; HB_Anchor* mark1_anchor; HB_Anchor* mark2_anchor; HB_Position o; HB_UNUSED(nesting_level); if ( context_length != 0xFFFF && context_length < 1 ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS ) return HB_Err_Not_Covered; if ( CHECK_Property( gpos->gdef, IN_CURITEM(), flags, &property ) ) return error; error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(), &mark1_index ); if ( error ) return error; /* now we search backwards for a suitable mark glyph until a non-mark glyph */ if ( buffer->in_pos == 0 ) return HB_Err_Not_Covered; i = 1; j = buffer->in_pos - 1; while ( i <= buffer->in_pos ) { error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ), &property ); if ( error ) return error; if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) { if ( property == (flags & 0xFF00) ) break; } else break; i++; j--; } error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ), &mark2_index ); if ( error ) if ( mark1_index >= ma1->MarkCount ) return ERR(HB_Err_Invalid_SubTable); class = ma1->MarkRecord[mark1_index].Class; mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor; if ( class >= mmp->ClassCount ) return ERR(HB_Err_Invalid_SubTable); ma2 = &mmp->Mark2Array; if ( mark2_index >= ma2->Mark2Count ) return ERR(HB_Err_Invalid_SubTable); m2r = &ma2->Mark2Record[mark2_index]; mark2_anchor = &m2r->Mark2Anchor[class]; error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(), &x_mark1_value, &y_mark1_value ); if ( error ) return error; error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ), &x_mark2_value, &y_mark2_value ); if ( error ) return error; /* anchor points are not cumulative */ o = POSITION( buffer->in_pos ); o->x_pos = x_mark2_value - x_mark1_value; o->y_pos = y_mark2_value - y_mark1_value; o->x_advance = 0; o->y_advance = 0; o->back = 1; (buffer->in_pos)++; return HB_Err_Ok; } Commit Message: CWE ID: CWE-119
static HB_Error Lookup_MarkMarkPos( GPOS_Instance* gpi, HB_GPOS_SubTable* st, HB_Buffer buffer, HB_UShort flags, HB_UShort context_length, int nesting_level ) { HB_UShort i, j, mark1_index, mark2_index, property, class; HB_Fixed x_mark1_value, y_mark1_value, x_mark2_value, y_mark2_value; HB_Error error; HB_GPOSHeader* gpos = gpi->gpos; HB_MarkMarkPos* mmp = &st->markmark; HB_MarkArray* ma1; HB_Mark2Array* ma2; HB_Mark2Record* m2r; HB_Anchor* mark1_anchor; HB_Anchor* mark2_anchor; HB_Position o; HB_UNUSED(nesting_level); if ( context_length != 0xFFFF && context_length < 1 ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_MARKS ) return HB_Err_Not_Covered; if ( CHECK_Property( gpos->gdef, IN_CURITEM(), flags, &property ) ) return error; error = _HB_OPEN_Coverage_Index( &mmp->Mark1Coverage, IN_CURGLYPH(), &mark1_index ); if ( error ) return error; /* now we search backwards for a suitable mark glyph until a non-mark glyph */ if ( buffer->in_pos == 0 ) return HB_Err_Not_Covered; i = 1; j = buffer->in_pos - 1; while ( i <= buffer->in_pos ) { error = HB_GDEF_Get_Glyph_Property( gpos->gdef, IN_GLYPH( j ), &property ); if ( error ) return error; if ( !( property == HB_GDEF_MARK || property & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) ) return HB_Err_Not_Covered; if ( flags & HB_LOOKUP_FLAG_IGNORE_SPECIAL_MARKS ) { if ( property == (flags & 0xFF00) ) break; } else break; i++; j--; } if ( i > buffer->in_pos ) return HB_Err_Not_Covered; error = _HB_OPEN_Coverage_Index( &mmp->Mark2Coverage, IN_GLYPH( j ), &mark2_index ); if ( error ) if ( mark1_index >= ma1->MarkCount ) return ERR(HB_Err_Invalid_SubTable); class = ma1->MarkRecord[mark1_index].Class; mark1_anchor = &ma1->MarkRecord[mark1_index].MarkAnchor; if ( class >= mmp->ClassCount ) return ERR(HB_Err_Invalid_SubTable); ma2 = &mmp->Mark2Array; if ( mark2_index >= ma2->Mark2Count ) return ERR(HB_Err_Invalid_SubTable); m2r = &ma2->Mark2Record[mark2_index]; mark2_anchor = &m2r->Mark2Anchor[class]; error = Get_Anchor( gpi, mark1_anchor, IN_CURGLYPH(), &x_mark1_value, &y_mark1_value ); if ( error ) return error; error = Get_Anchor( gpi, mark2_anchor, IN_GLYPH( j ), &x_mark2_value, &y_mark2_value ); if ( error ) return error; /* anchor points are not cumulative */ o = POSITION( buffer->in_pos ); o->x_pos = x_mark2_value - x_mark1_value; o->y_pos = y_mark2_value - y_mark1_value; o->x_advance = 0; o->y_advance = 0; o->back = 1; (buffer->in_pos)++; return HB_Err_Ok; }
165,246
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void fht4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fht4x4_c(in, out, stride, tx_type); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void fht4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { void fht4x4_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vp9_fht4x4_c(in, out, stride, tx_type); }
174,558
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PreconnectRequest::PreconnectRequest( const GURL& origin, int num_sockets, const net::NetworkIsolationKey& network_isolation_key) : origin(origin), num_sockets(num_sockets), network_isolation_key(network_isolation_key) { DCHECK_GE(num_sockets, 0); } Commit Message: Origins should be represented as url::Origin (not as GURL). As pointed out in //docs/security/origin-vs-url.md, origins should be represented as url::Origin (not as GURL). This CL applies this guideline to predictor-related code and changes the type of the following fields from GURL to url::Origin: - OriginRequestSummary::origin - PreconnectedRequestStats::origin - PreconnectRequest::origin The old code did not depend on any non-origin parts of GURL (like path and/or query). Therefore, this CL has no intended behavior change. Bug: 973885 Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167 Commit-Queue: Łukasz Anforowicz <lukasza@chromium.org> Reviewed-by: Alex Ilin <alexilin@chromium.org> Cr-Commit-Position: refs/heads/master@{#716311} CWE ID: CWE-125
PreconnectRequest::PreconnectRequest( const url::Origin& origin, int num_sockets, const net::NetworkIsolationKey& network_isolation_key) : origin(origin), num_sockets(num_sockets), network_isolation_key(network_isolation_key) { DCHECK_GE(num_sockets, 0); }
172,381
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic, const char *s, charset_t src_charset, charset_t dst_charset) { size_t count = 0; #ifdef DEVELOPER switch (dst_charset) { case CH_DOS: case CH_UNIX: smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)"); default: break; } switch (src_charset) { case CH_UTF16LE: case CH_UTF16BE: smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)"); default: break; } #endif if (!s) { return 0; } while (*s && !(((uint8_t)*s) & 0x80)) { s++; count++; } if (!*s) { return count; } while (*s) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(ic, s, src_charset, &c_size); s += c_size; switch (dst_charset) { case CH_UTF16BE: case CH_UTF16MUNGED: if (c < 0x10000) { /* Unicode char fits into 16 bits. */ count += 1; } else { /* Double-width unicode char - 32 bits. */ count += 2; } break; case CH_UTF8: /* * this only checks ranges, and does not * check for invalid codepoints */ if (c < 0x80) { count += 1; } else if (c < 0x800) { count += 2; } else if (c < 0x10000) { count += 3; } else { count += 4; } break; default: /* * non-unicode encoding: * assume that each codepoint fits into * one unit in the destination encoding. */ count += 1; } } return count; } Commit Message: CWE ID: CWE-200
_PUBLIC_ size_t strlen_m_ext_handle(struct smb_iconv_handle *ic, const char *s, charset_t src_charset, charset_t dst_charset) { size_t count = 0; #ifdef DEVELOPER switch (dst_charset) { case CH_DOS: case CH_UNIX: smb_panic("cannot call strlen_m_ext() with a variable dest charset (must be UTF16* or UTF8)"); default: break; } switch (src_charset) { case CH_UTF16LE: case CH_UTF16BE: smb_panic("cannot call strlen_m_ext() with a UTF16 src charset (must be DOS, UNIX, DISPLAY or UTF8)"); default: break; } #endif if (!s) { return 0; } while (*s && !(((uint8_t)*s) & 0x80)) { s++; count++; } if (!*s) { return count; } while (*s) { size_t c_size; codepoint_t c = next_codepoint_handle_ext(ic, s, strnlen(s, 5), src_charset, &c_size); s += c_size; switch (dst_charset) { case CH_UTF16BE: case CH_UTF16MUNGED: if (c < 0x10000) { /* Unicode char fits into 16 bits. */ count += 1; } else { /* Double-width unicode char - 32 bits. */ count += 2; } break; case CH_UTF8: /* * this only checks ranges, and does not * check for invalid codepoints */ if (c < 0x80) { count += 1; } else if (c < 0x800) { count += 2; } else if (c < 0x10000) { count += 3; } else { count += 4; } break; default: /* * non-unicode encoding: * assume that each codepoint fits into * one unit in the destination encoding. */ count += 1; } } return count; }
164,671
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: CURLcode Curl_urldecode(struct SessionHandle *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_ctrl) { size_t alloc = (length?length:strlen(string))+1; char *ns = malloc(alloc); unsigned char in; size_t strindex=0; unsigned long hex; CURLcode res; if(!ns) return CURLE_OUT_OF_MEMORY; while(--alloc > 0) { in = *string; if(('%' == in) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(data, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return res; } string+=2; alloc-=2; } if(reject_ctrl && (in < 0x20)) { free(ns); return CURLE_URL_MALFORMAT; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; if(ostring) /* store output string */ *ostring = ns; return CURLE_OK; } Commit Message: Curl_urldecode: no peeking beyond end of input buffer Security problem: CVE-2013-2174 If a program would give a string like "%FF" to curl_easy_unescape() but ask for it to decode only the first byte, it would still parse and decode the full hex sequence. The function then not only read beyond the allowed buffer but it would also deduct the *unsigned* counter variable for how many more bytes there's left to read in the buffer by two, making the counter wrap. Continuing this, the function would go on reading beyond the buffer and soon writing beyond the allocated target buffer... Bug: http://curl.haxx.se/docs/adv_20130622.html Reported-by: Timo Sirainen CWE ID: CWE-119
CURLcode Curl_urldecode(struct SessionHandle *data, const char *string, size_t length, char **ostring, size_t *olen, bool reject_ctrl) { size_t alloc = (length?length:strlen(string))+1; char *ns = malloc(alloc); unsigned char in; size_t strindex=0; unsigned long hex; CURLcode res; if(!ns) return CURLE_OUT_OF_MEMORY; while(--alloc > 0) { in = *string; if(('%' == in) && (alloc > 2) && ISXDIGIT(string[1]) && ISXDIGIT(string[2])) { /* this is two hexadecimal digits following a '%' */ char hexstr[3]; char *ptr; hexstr[0] = string[1]; hexstr[1] = string[2]; hexstr[2] = 0; hex = strtoul(hexstr, &ptr, 16); in = curlx_ultouc(hex); /* this long is never bigger than 255 anyway */ res = Curl_convert_from_network(data, &in, 1); if(res) { /* Curl_convert_from_network calls failf if unsuccessful */ free(ns); return res; } string+=2; alloc-=2; } if(reject_ctrl && (in < 0x20)) { free(ns); return CURLE_URL_MALFORMAT; } ns[strindex++] = in; string++; } ns[strindex]=0; /* terminate it */ if(olen) /* store output size */ *olen = strindex; if(ostring) /* store output string */ *ostring = ns; return CURLE_OK; }
166,080
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data) { HashAndString *data = (HashAndString*) user_data; gchar *in = (gchar*) val; g_hash_table_insert (data->hash, g_strdup ((gchar*) key), g_strjoin (" ", data->string, in, NULL)); } Commit Message: CWE ID: CWE-264
hash_foreach_prepend_string (gpointer key, gpointer val, gpointer user_data)
165,086
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void Label::SizeToFit(int max_width) { DCHECK(is_multi_line_); std::vector<std::wstring> lines; base::SplitString(UTF16ToWideHack(text_), L'\n', &lines); int label_width = 0; for (std::vector<std::wstring>::const_iterator iter = lines.begin(); iter != lines.end(); ++iter) { label_width = std::max(label_width, font_.GetStringWidth(WideToUTF16Hack(*iter))); } label_width += GetInsets().width(); if (max_width > 0) label_width = std::min(label_width, max_width); SetBounds(x(), y(), label_width, 0); SizeToPreferredSize(); } Commit Message: wstring: remove wstring version of SplitString Retry of r84336. BUG=23581 Review URL: http://codereview.chromium.org/6930047 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@84355 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void Label::SizeToFit(int max_width) { DCHECK(is_multi_line_); std::vector<string16> lines; base::SplitString(text_, '\n', &lines); int label_width = 0; for (std::vector<string16>::const_iterator iter = lines.begin(); iter != lines.end(); ++iter) { label_width = std::max(label_width, font_.GetStringWidth(*iter)); } label_width += GetInsets().width(); if (max_width > 0) label_width = std::min(label_width, max_width); SetBounds(x(), y(), label_width, 0); SizeToPreferredSize(); }
170,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; } Commit Message: CWE ID: CWE-125
static int vrend_decode_create_ve(struct vrend_decode_ctx *ctx, uint32_t handle, uint16_t length) { struct pipe_vertex_element *ve = NULL; int num_elements; int i; int ret; if (length < 1) return EINVAL; if ((length - 1) % 4) return EINVAL; num_elements = (length - 1) / 4; if (num_elements) { ve = calloc(num_elements, sizeof(struct pipe_vertex_element)); if (!ve) return ENOMEM; for (i = 0; i < num_elements; i++) { ve[i].src_offset = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_OFFSET(i)); ve[i].instance_divisor = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_INSTANCE_DIVISOR(i)); ve[i].vertex_buffer_index = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_VERTEX_BUFFER_INDEX(i)); if (ve[i].vertex_buffer_index >= PIPE_MAX_ATTRIBS) return EINVAL; ve[i].src_format = get_buf_entry(ctx, VIRGL_OBJ_VERTEX_ELEMENTS_V0_SRC_FORMAT(i)); } } return ret; }
164,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); } Commit Message: CWE ID: CWE-264
PHP_FUNCTION(move_uploaded_file) { char *path, *new_path; int path_len, new_path_len; zend_bool successful = 0; #ifndef PHP_WIN32 int oldmask; int ret; #endif if (!SG(rfc1867_uploaded_files)) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sp", &path, &path_len, &new_path, &new_path_len) == FAILURE) { return; } if (!zend_hash_exists(SG(rfc1867_uploaded_files), path, path_len + 1)) { RETURN_FALSE; } if (php_check_open_basedir(new_path TSRMLS_CC)) { RETURN_FALSE; } if (VCWD_RENAME(path, new_path) == 0) { successful = 1; #ifndef PHP_WIN32 oldmask = umask(077); umask(oldmask); ret = VCWD_CHMOD(new_path, 0666 & ~oldmask); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); } #endif } else if (php_copy_file_ex(path, new_path, STREAM_DISABLE_OPEN_BASEDIR TSRMLS_CC) == SUCCESS) { VCWD_UNLINK(path); successful = 1; } if (successful) { zend_hash_del(SG(rfc1867_uploaded_files), path, path_len + 1); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to move '%s' to '%s'", path, new_path); } RETURN_BOOL(successful); }
164,751
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static Element* siblingWithAriaRole(String role, Node* node) { Node* parent = node->parentNode(); if (!parent) return 0; for (Element* sibling = ElementTraversal::firstChild(*parent); sibling; sibling = ElementTraversal::nextSibling(*sibling)) { const AtomicString& siblingAriaRole = AccessibleNode::getProperty(sibling, AOMStringProperty::kRole); if (equalIgnoringCase(siblingAriaRole, role)) return sibling; } return 0; } Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility BUG=627682 Review-Url: https://codereview.chromium.org/2793913007 Cr-Commit-Position: refs/heads/master@{#461858} CWE ID: CWE-254
static Element* siblingWithAriaRole(String role, Node* node) { Node* parent = node->parentNode(); if (!parent) return 0; for (Element* sibling = ElementTraversal::firstChild(*parent); sibling; sibling = ElementTraversal::nextSibling(*sibling)) { const AtomicString& siblingAriaRole = AccessibleNode::getProperty(sibling, AOMStringProperty::kRole); if (equalIgnoringASCIICase(siblingAriaRole, role)) return sibling; } return 0; }
171,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, PNG_CONST transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this, image_transform_png_set_expand_16_mod(const image_transform *this, image_pixel *that, png_const_structp pp, const transform_display *display) { /* Expect expand_16 to expand everything to 16 bits as a result of also * causing 'expand' to happen. */ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) image_pixel_convert_PLTE(that); if (that->have_tRNS) image_pixel_add_alpha(that, &display->this, 0/*!for background*/); if (that->bit_depth < 16) that->sample_depth = that->bit_depth = 16; this->next->mod(this->next, that, pp, display); }
173,627
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FileManagerPrivateCustomBindings::FileManagerPrivateCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetFileSystem", base::Bind(&FileManagerPrivateCustomBindings::GetFileSystem, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
FileManagerPrivateCustomBindings::FileManagerPrivateCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction("GetFileSystem", "fileManagerPrivate", base::Bind(&FileManagerPrivateCustomBindings::GetFileSystem, base::Unretained(this))); RouteFunction( "GetExternalFileEntry", "fileManagerPrivate", base::Bind(&FileManagerPrivateCustomBindings::GetExternalFileEntry, base::Unretained(this))); RouteFunction("GetEntryURL", "fileManagerPrivate", base::Bind(&FileManagerPrivateCustomBindings::GetEntryURL, base::Unretained(this))); }
173,274
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } provider_->LockOrientation(request_id, orientation); } Commit Message: Cleanups in ScreenOrientationDispatcherHost. BUG=None Review URL: https://codereview.chromium.org/408213003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@284786 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-362
void ScreenOrientationDispatcherHost::OnLockRequest( RenderFrameHost* render_frame_host, blink::WebScreenOrientationLockType orientation, int request_id) { if (current_lock_) { NotifyLockError(current_lock_->request_id, blink::WebLockOrientationErrorCanceled); } if (!provider_) { NotifyLockError(request_id, blink::WebLockOrientationErrorNotAvailable); return; } current_lock_ = new LockInformation(request_id, render_frame_host->GetProcess()->GetID(), render_frame_host->GetRoutingID()); provider_->LockOrientation(request_id, orientation); }
171,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) { EXPECT_TRUE(fb != NULL); ExternalFrameBuffer *const ext_fb = reinterpret_cast<ExternalFrameBuffer*>(fb->priv); EXPECT_TRUE(ext_fb != NULL); EXPECT_EQ(1, ext_fb->in_use); ext_fb->in_use = 0; return 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
int ReturnFrameBuffer(vpx_codec_frame_buffer_t *fb) { if (fb == NULL) { EXPECT_TRUE(fb != NULL); return -1; } ExternalFrameBuffer *const ext_fb = reinterpret_cast<ExternalFrameBuffer*>(fb->priv); if (ext_fb == NULL) { EXPECT_TRUE(ext_fb != NULL); return -1; } EXPECT_EQ(1, ext_fb->in_use); ext_fb->in_use = 0; return 0; }
174,545
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext) { SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl); info->num_memslots = NUM_MEMSLOTS; info->num_memslots_groups = NUM_MEMSLOTS_GROUPS; info->internal_groupslot_id = 0; info->qxl_ram_size = ssd->bufsize; info->n_surfaces = ssd->num_surfaces; } Commit Message: CWE ID: CWE-200
static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext) { SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl); info->num_memslots = NUM_MEMSLOTS; info->num_memslots_groups = NUM_MEMSLOTS_GROUPS; info->internal_groupslot_id = 0; info->qxl_ram_size = 16 * 1024 * 1024; info->n_surfaces = ssd->num_surfaces; }
165,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_get_iv_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_iv_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_iv_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_iv_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } }
167,105
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EncoderTest::MismatchHook(const vpx_image_t *img1, const vpx_image_t *img2) { ASSERT_TRUE(0) << "Encode/Decode mismatch found"; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void EncoderTest::MismatchHook(const vpx_image_t *img1, void EncoderTest::MismatchHook(const vpx_image_t* /*img1*/, const vpx_image_t* /*img2*/) { ASSERT_TRUE(0) << "Encode/Decode mismatch found"; }
174,539
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
virtual InputMethodDescriptor current_input_method() const { virtual input_method::InputMethodDescriptor current_input_method() const { if (current_input_method_.id.empty()) { return input_method::GetFallbackInputMethodDescriptor(); } return current_input_method_; }
170,512
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian, const unsigned char *buffer) { unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); return((unsigned short) (value & 0xffff)); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); return((unsigned short) (value & 0xffff)); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian, const unsigned char *buffer) { unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; return(value & 0xffff); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; return(value & 0xffff); }
169,957
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ChromeMockRenderThread::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, PrintMsg_PrintPages_Params* settings) { if (print_dialog_user_response_ && printer_.get()) { printer_->ScriptedPrint(params.cookie, params.expected_pages_count, params.has_selection, settings); } } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void ChromeMockRenderThread::OnScriptedPrint( const PrintHostMsg_ScriptedPrint_Params& params, PrintMsg_PrintPages_Params* settings) { if (print_dialog_user_response_) { printer_->ScriptedPrint(params.cookie, params.expected_pages_count, params.has_selection, settings); } }
170,853
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool GLES2DecoderImpl::SimulateAttrib0( const char* function_name, GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; const VertexAttribManager::VertexAttribInfo* info = vertex_attrib_manager_->GetVertexAttribInfo(0); bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL; if (info->enabled() && attrib_0_used) { return true; } typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4; GLuint num_vertices = max_vertex_accessed + 1; GLuint size_needed = 0; if (num_vertices == 0 || !SafeMultiply(num_vertices, static_cast<GLuint>(sizeof(Vec4)), &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } PerformanceWarning( "Attribute 0 is disabled. This has signficant performance penalty"); CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_); bool new_buffer = static_cast<GLsizei>(size_needed) > attrib_0_size_; if (new_buffer) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } } if (new_buffer || (attrib_0_used && (!attrib_0_buffer_matches_value_ || (info->value().v[0] != attrib_0_value_.v[0] || info->value().v[1] != attrib_0_value_.v[1] || info->value().v[2] != attrib_0_value_.v[2] || info->value().v[3] != attrib_0_value_.v[3])))) { std::vector<Vec4> temp(num_vertices, info->value()); glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]); attrib_0_buffer_matches_value_ = true; attrib_0_value_ = info->value(); attrib_0_size_ = size_needed; } glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); if (info->divisor()) glVertexAttribDivisorANGLE(0, 0); *simulated = true; return true; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
bool GLES2DecoderImpl::SimulateAttrib0( const char* function_name, GLuint max_vertex_accessed, bool* simulated) { DCHECK(simulated); *simulated = false; if (gfx::GetGLImplementation() == gfx::kGLImplementationEGLGLES2) return true; const VertexAttribManager::VertexAttribInfo* info = vertex_attrib_manager_->GetVertexAttribInfo(0); bool attrib_0_used = current_program_->GetAttribInfoByLocation(0) != NULL; if (info->enabled() && attrib_0_used) { return true; } typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4; GLuint num_vertices = max_vertex_accessed + 1; uint32 size_needed = 0; if (num_vertices == 0 || !SafeMultiplyUint32(num_vertices, sizeof(Vec4), &size_needed) || size_needed > 0x7FFFFFFFU) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } PerformanceWarning( "Attribute 0 is disabled. This has signficant performance penalty"); CopyRealGLErrorsToWrapper(); glBindBuffer(GL_ARRAY_BUFFER, attrib_0_buffer_id_); bool new_buffer = static_cast<GLsizei>(size_needed) > attrib_0_size_; if (new_buffer) { glBufferData(GL_ARRAY_BUFFER, size_needed, NULL, GL_DYNAMIC_DRAW); GLenum error = glGetError(); if (error != GL_NO_ERROR) { SetGLError(GL_OUT_OF_MEMORY, function_name, "Simulating attrib 0"); return false; } } if (new_buffer || (attrib_0_used && (!attrib_0_buffer_matches_value_ || (info->value().v[0] != attrib_0_value_.v[0] || info->value().v[1] != attrib_0_value_.v[1] || info->value().v[2] != attrib_0_value_.v[2] || info->value().v[3] != attrib_0_value_.v[3])))) { std::vector<Vec4> temp(num_vertices, info->value()); glBufferSubData(GL_ARRAY_BUFFER, 0, size_needed, &temp[0].v[0]); attrib_0_buffer_matches_value_ = true; attrib_0_value_ = info->value(); attrib_0_size_ = size_needed; } glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, NULL); if (info->divisor()) glVertexAttribDivisorANGLE(0, 0); *simulated = true; return true; }
170,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname, int flen) { struct ustr *filename, *unifilename; int len = 0; filename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!filename) return 0; unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!unifilename) goto out1; if (udf_build_ustr_exact(unifilename, sname, flen)) goto out2; if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) { if (!udf_CS0toUTF8(filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) { if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else goto out2; len = udf_translate_to_linux(dname, filename->u_name, filename->u_len, unifilename->u_name, unifilename->u_len); out2: kfree(unifilename); out1: kfree(filename); return len; } Commit Message: udf: Check path length when reading symlink Symlink reading code does not check whether the resulting path fits into the page provided by the generic code. This isn't as easy as just checking the symlink size because of various encoding conversions we perform on path. So we have to check whether there is still enough space in the buffer on the fly. CC: stable@vger.kernel.org Reported-by: Carl Henrik Lunde <chlunde@ping.uio.no> Signed-off-by: Jan Kara <jack@suse.cz> CWE ID: CWE-17
int udf_get_filename(struct super_block *sb, uint8_t *sname, uint8_t *dname, int udf_get_filename(struct super_block *sb, uint8_t *sname, int slen, uint8_t *dname, int dlen) { struct ustr *filename, *unifilename; int len = 0; filename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!filename) return 0; unifilename = kmalloc(sizeof(struct ustr), GFP_NOFS); if (!unifilename) goto out1; if (udf_build_ustr_exact(unifilename, sname, slen)) goto out2; if (UDF_QUERY_FLAG(sb, UDF_FLAG_UTF8)) { if (!udf_CS0toUTF8(filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else if (UDF_QUERY_FLAG(sb, UDF_FLAG_NLS_MAP)) { if (!udf_CS0toNLS(UDF_SB(sb)->s_nls_map, filename, unifilename)) { udf_debug("Failed in udf_get_filename: sname = %s\n", sname); goto out2; } } else goto out2; len = udf_translate_to_linux(dname, dlen, filename->u_name, filename->u_len, unifilename->u_name, unifilename->u_len); out2: kfree(unifilename); out1: kfree(filename); return len; }
166,759
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK(*ext); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev2_auth_print(netdissect_options *ndo, u_char tpay, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct ikev2_auth a; const char *v2_auth[]={ "invalid", "rsasig", "shared-secret", "dsssig" }; const u_char *authdata = (const u_char*)ext + sizeof(a); unsigned int len; ND_TCHECK2(*ext, sizeof(a)); UNALIGNED_MEMCPY(&a, ext, sizeof(a)); ikev2_pay_print(ndo, NPSTR(tpay), a.h.critical); len = ntohs(a.h.len); /* * Our caller has ensured that the length is >= 4. */ ND_PRINT((ndo," len=%u method=%s", len-4, STR_OR_ID(a.auth_method, v2_auth))); if (len > 4) { if (ndo->ndo_vflag > 1) { ND_PRINT((ndo, " authdata=(")); if (!rawprint(ndo, (const uint8_t *)authdata, len - sizeof(a))) goto trunc; ND_PRINT((ndo, ") ")); } else if (ndo->ndo_vflag) { if (!ike_show_somedata(ndo, authdata, ep)) goto trunc; } } return (const u_char *)ext + len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(tpay))); return NULL; }
167,797