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 RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { free (ptr); return ret; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { free (ptr); return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { free (ptr); return ret; } ut32 j = 0; while (i < len && j < ptr->num_elem ) { ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; } Commit Message: Fix crash in fuzzed wasm r2_hoobr_consume_init_expr CWE ID: CWE-125
static RList *r_bin_wasm_get_element_entries (RBinWasmObj *bin, RBinWasmSection *sec) { RList *ret = NULL; RBinWasmElementEntry *ptr = NULL; if (!(ret = r_list_newf ((RListFree)free))) { return NULL; } ut8* buf = bin->buf->buf + (ut32)sec->payload_data; int buflen = bin->buf->length - (ut32)sec->payload_data; ut32 len = sec->payload_len; ut32 count = sec->count; ut32 i = 0, r = 0; while (i < len && len < buflen && r < count) { if (!(ptr = R_NEW0 (RBinWasmElementEntry))) { return ret; } if (!(consume_u32 (buf + i, buf + len, &ptr->index, &i))) { goto beach; } if (!(consume_init_expr (buf + i, buf + len, R_BIN_WASM_END_OF_CODE, NULL, &i))) { goto beach; } if (!(consume_u32 (buf + i, buf + len, &ptr->num_elem, &i))) { goto beach; } ut32 j = 0; while (i < len && j < ptr->num_elem) { ut32 e; if (!(consume_u32 (buf + i, buf + len, &e, &i))) { free (ptr); return ret; } } r_list_append (ret, ptr); r += 1; } return ret; beach: free (ptr); return ret; }
168,252
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: TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { const int shmkey = shmget(IPC_PRIVATE, size, 0666); if (shmkey == -1) { DLOG(ERROR) << "Failed to create SysV shared memory region" << " errno:" << errno; return NULL; } void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */); shmctl(shmkey, IPC_RMID, 0); if (address == kInvalidAddress) return NULL; TransportDIB* dib = new TransportDIB; dib->key_.shmkey = shmkey; dib->address_ = address; dib->size_ = size; return dib; } Commit Message: Make shared memory segments writable only by their rightful owners. BUG=143859 TEST=Chrome's UI still works on Linux and Chrome OS Review URL: https://chromiumcodereview.appspot.com/10854242 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@158289 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
TransportDIB* TransportDIB::Create(size_t size, uint32 sequence_num) { const int shmkey = shmget(IPC_PRIVATE, size, 0600); if (shmkey == -1) { DLOG(ERROR) << "Failed to create SysV shared memory region" << " errno:" << errno; return NULL; } else { VLOG(1) << "Created SysV shared memory region " << shmkey; } void* address = shmat(shmkey, NULL /* desired address */, 0 /* flags */); shmctl(shmkey, IPC_RMID, 0); if (address == kInvalidAddress) return NULL; TransportDIB* dib = new TransportDIB; dib->key_.shmkey = shmkey; dib->address_ = address; dib->size_ = size; return dib; }
171,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: get_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) { char * name = NULL; int rtnVal = FALSE; bool found_cred=false; CredentialWrapper * cred = NULL; char * owner = NULL; const char * user = NULL; void * data = NULL; ReliSock * socket = (ReliSock*)stream; if (!socket->triedAuthentication()) { CondorError errstack; if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) { dprintf (D_ALWAYS, "Unable to authenticate, qutting\n"); goto EXIT; } } socket->decode(); if (!socket->code(name)) { dprintf (D_ALWAYS, "Error receiving credential name\n"); goto EXIT; } user = socket->getFullyQualifiedUser(); dprintf (D_ALWAYS, "Authenticated as %s\n", user); if (strchr (name, ':')) { owner = strdup (name); char * pColon = strchr (owner, ':'); *pColon = '\0'; sprintf (name, (char*)(pColon+sizeof(char))); if (strcmp (owner, user) != 0) { dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name); if (!isSuperUser (user)) { dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user); goto EXIT; } else { dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user); } } } else { owner = strdup (user); } dprintf (D_ALWAYS, "sending cred %s for user %s\n", name, owner); credentials.Rewind(); while (credentials.Next(cred)) { if (cred->cred->GetType() == X509_CREDENTIAL_TYPE) { if ((strcmp(cred->cred->GetName(), name) == 0) && (strcmp(cred->cred->GetOwner(), owner) == 0)) { found_cred=true; break; // found it } } } socket->encode(); if (found_cred) { dprintf (D_FULLDEBUG, "Found cred %s\n", cred->GetStorageName()); int data_size; int rc = LoadData (cred->GetStorageName(), data, data_size); dprintf (D_FULLDEBUG, "Credential::LoadData returned %d\n", rc); if (rc == 0) { goto EXIT; } socket->code (data_size); socket->code_bytes (data, data_size); dprintf (D_ALWAYS, "Credential name %s for owner %s returned to user %s\n", name, owner, user); } else { dprintf (D_ALWAYS, "Cannot find cred %s\n", name); int rc = CREDD_CREDENTIAL_NOT_FOUND; socket->code (rc); } rtnVal = TRUE; EXIT: if ( name != NULL) { free (name); } if ( owner != NULL) { free (owner); } if ( data != NULL) { free (data); } return rtnVal; } Commit Message: CWE ID: CWE-134
get_cred_handler(Service * /*service*/, int /*i*/, Stream *stream) { char * name = NULL; int rtnVal = FALSE; bool found_cred=false; CredentialWrapper * cred = NULL; char * owner = NULL; const char * user = NULL; void * data = NULL; ReliSock * socket = (ReliSock*)stream; if (!socket->triedAuthentication()) { CondorError errstack; if( ! SecMan::authenticate_sock(socket, READ, &errstack) ) { dprintf (D_ALWAYS, "Unable to authenticate, qutting\n"); goto EXIT; } } socket->decode(); if (!socket->code(name)) { dprintf (D_ALWAYS, "Error receiving credential name\n"); goto EXIT; } user = socket->getFullyQualifiedUser(); dprintf (D_ALWAYS, "Authenticated as %s\n", user); if (strchr (name, ':')) { owner = strdup (name); char * pColon = strchr (owner, ':'); *pColon = '\0'; sprintf (name, "%s", (char*)(pColon+sizeof(char))); if (strcmp (owner, user) != 0) { dprintf (D_ALWAYS, "Requesting another user's (%s) credential %s\n", owner, name); if (!isSuperUser (user)) { dprintf (D_ALWAYS, "User %s is NOT super user, request DENIED\n", user); goto EXIT; } else { dprintf (D_FULLDEBUG, "User %s is super user, request GRANTED\n", user); } } } else { owner = strdup (user); } dprintf (D_ALWAYS, "sending cred %s for user %s\n", name, owner); credentials.Rewind(); while (credentials.Next(cred)) { if (cred->cred->GetType() == X509_CREDENTIAL_TYPE) { if ((strcmp(cred->cred->GetName(), name) == 0) && (strcmp(cred->cred->GetOwner(), owner) == 0)) { found_cred=true; break; // found it } } } socket->encode(); if (found_cred) { dprintf (D_FULLDEBUG, "Found cred %s\n", cred->GetStorageName()); int data_size; int rc = LoadData (cred->GetStorageName(), data, data_size); dprintf (D_FULLDEBUG, "Credential::LoadData returned %d\n", rc); if (rc == 0) { goto EXIT; } socket->code (data_size); socket->code_bytes (data, data_size); dprintf (D_ALWAYS, "Credential name %s for owner %s returned to user %s\n", name, owner, user); } else { dprintf (D_ALWAYS, "Cannot find cred %s\n", name); int rc = CREDD_CREDENTIAL_NOT_FOUND; socket->code (rc); } rtnVal = TRUE; EXIT: if ( name != NULL) { free (name); } if ( owner != NULL) { free (owner); } if ( data != NULL) { free (data); } return rtnVal; }
165,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: ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: ip_printts(ndo, cp, option_len); break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: ip_printroute(ndo, cp, option_len); break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); } Commit Message: CVE-2017-13022/IP: Add bounds checks to ip_printroute(). 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
ip_optprint(netdissect_options *ndo, register const u_char *cp, u_int length) { register u_int option_len; const char *sep = ""; for (; length > 0; cp += option_len, length -= option_len) { u_int option_code; ND_PRINT((ndo, "%s", sep)); sep = ","; ND_TCHECK(*cp); option_code = *cp; ND_PRINT((ndo, "%s", tok2str(ip_option_values,"unknown %u",option_code))); if (option_code == IPOPT_NOP || option_code == IPOPT_EOL) option_len = 1; else { ND_TCHECK(cp[1]); option_len = cp[1]; if (option_len < 2) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } } if (option_len > length) { ND_PRINT((ndo, " [bad length %u]", option_len)); return; } ND_TCHECK2(*cp, option_len); switch (option_code) { case IPOPT_EOL: return; case IPOPT_TS: ip_printts(ndo, cp, option_len); break; case IPOPT_RR: /* fall through */ case IPOPT_SSRR: case IPOPT_LSRR: if (ip_printroute(ndo, cp, option_len) == -1) goto trunc; break; case IPOPT_RA: if (option_len < 4) { ND_PRINT((ndo, " [bad length %u]", option_len)); break; } ND_TCHECK(cp[3]); if (EXTRACT_16BITS(&cp[2]) != 0) ND_PRINT((ndo, " value %u", EXTRACT_16BITS(&cp[2]))); break; case IPOPT_NOP: /* nothing to print - fall through */ case IPOPT_SECURITY: default: break; } } return; trunc: ND_PRINT((ndo, "%s", tstr)); }
167,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: GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync( content::CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kUnconnected || gpu_channel_->state() == GpuChannelHost::kConnected) return GetGpuChannel(); gpu_channel_ = NULL; } int client_id = 0; IPC::ChannelHandle channel_handle; base::ProcessHandle renderer_process_for_gpu; content::GPUInfo gpu_info; if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch, &client_id, &channel_handle, &renderer_process_for_gpu, &gpu_info)) || channel_handle.name.empty() || #if defined(OS_POSIX) channel_handle.socket.fd == -1 || #endif renderer_process_for_gpu == base::kNullProcessHandle) { gpu_channel_ = NULL; return NULL; } gpu_channel_ = new GpuChannelHost(this, 0, client_id); gpu_channel_->set_gpu_info(gpu_info); content::GetContentClient()->SetGpuInfo(gpu_info); gpu_channel_->Connect(channel_handle, renderer_process_for_gpu); return GetGpuChannel(); } Commit Message: Convert plugin and GPU process to brokered handle duplication. BUG=119250 Review URL: https://chromiumcodereview.appspot.com/9958034 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
GpuChannelHost* RenderThreadImpl::EstablishGpuChannelSync( content::CauseForGpuLaunch cause_for_gpu_launch) { if (gpu_channel_.get()) { if (gpu_channel_->state() == GpuChannelHost::kUnconnected || gpu_channel_->state() == GpuChannelHost::kConnected) return GetGpuChannel(); gpu_channel_ = NULL; } int client_id = 0; IPC::ChannelHandle channel_handle; content::GPUInfo gpu_info; if (!Send(new GpuHostMsg_EstablishGpuChannel(cause_for_gpu_launch, &client_id, &channel_handle, &gpu_info)) || #if defined(OS_POSIX) channel_handle.socket.fd == -1 || #endif channel_handle.name.empty()) { gpu_channel_ = NULL; return NULL; } gpu_channel_ = new GpuChannelHost(this, 0, client_id); gpu_channel_->set_gpu_info(gpu_info); content::GetContentClient()->SetGpuInfo(gpu_info); gpu_channel_->Connect(channel_handle); return GetGpuChannel(); }
170,954
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 ResourcePrefetchPredictor::GetRedirectEndpointsForPreconnect( const url::Origin& entry_origin, const RedirectDataMap& redirect_data, PreconnectPrediction* prediction) const { if (!base::FeatureList::IsEnabled( features::kLoadingPreconnectToRedirectTarget)) { return false; } DCHECK(!prediction || prediction->requests.empty()); RedirectData data; if (!redirect_data.TryGetData(entry_origin.host(), &data)) return false; const float kMinRedirectConfidenceToTriggerPrefetch = 0.1f; bool at_least_one_redirect_endpoint_added = false; for (const auto& redirect : data.redirect_endpoints()) { if (ComputeRedirectConfidence(redirect) < kMinRedirectConfidenceToTriggerPrefetch) { continue; } std::string redirect_scheme = redirect.url_scheme().empty() ? "https" : redirect.url_scheme(); int redirect_port = redirect.has_url_port() ? redirect.url_port() : 443; const url::Origin redirect_origin = url::Origin::CreateFromNormalizedTuple( redirect_scheme, redirect.url(), redirect_port); if (redirect_origin == entry_origin) { continue; } if (prediction) { prediction->requests.emplace_back( redirect_origin.GetURL(), 1 /* num_scokets */, net::NetworkIsolationKey(redirect_origin, redirect_origin)); } at_least_one_redirect_endpoint_added = true; } if (prediction && prediction->host.empty() && at_least_one_redirect_endpoint_added) { prediction->host = entry_origin.host(); } return at_least_one_redirect_endpoint_added; } 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
bool ResourcePrefetchPredictor::GetRedirectEndpointsForPreconnect( const url::Origin& entry_origin, const RedirectDataMap& redirect_data, PreconnectPrediction* prediction) const { if (!base::FeatureList::IsEnabled( features::kLoadingPreconnectToRedirectTarget)) { return false; } DCHECK(!prediction || prediction->requests.empty()); RedirectData data; if (!redirect_data.TryGetData(entry_origin.host(), &data)) return false; const float kMinRedirectConfidenceToTriggerPrefetch = 0.1f; bool at_least_one_redirect_endpoint_added = false; for (const auto& redirect : data.redirect_endpoints()) { if (ComputeRedirectConfidence(redirect) < kMinRedirectConfidenceToTriggerPrefetch) { continue; } std::string redirect_scheme = redirect.url_scheme().empty() ? "https" : redirect.url_scheme(); int redirect_port = redirect.has_url_port() ? redirect.url_port() : 443; const url::Origin redirect_origin = url::Origin::CreateFromNormalizedTuple( redirect_scheme, redirect.url(), redirect_port); if (redirect_origin == entry_origin) { continue; } if (prediction) { prediction->requests.emplace_back( redirect_origin, 1 /* num_scokets */, net::NetworkIsolationKey(redirect_origin, redirect_origin)); } at_least_one_redirect_endpoint_added = true; } if (prediction && prediction->host.empty() && at_least_one_redirect_endpoint_added) { prediction->host = entry_origin.host(); } return at_least_one_redirect_endpoint_added; }
172,378
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: ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->GetAppListTargetVisibility()) return AUTO_HIDE_SHOWN; if (shell->system_tray() && shell->system_tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; if (launcher_widget()->IsActive() || status_->IsActive()) return AUTO_HIDE_SHOWN; if (event_filter_.get() && event_filter_->in_mouse_drag()) return AUTO_HIDE_HIDDEN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; } 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
ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState( VisibilityState visibility_state) const { if (visibility_state != AUTO_HIDE || !launcher_widget()) return AUTO_HIDE_HIDDEN; Shell* shell = Shell::GetInstance(); if (shell->GetAppListTargetVisibility()) return AUTO_HIDE_SHOWN; if (shell->system_tray() && shell->system_tray()->should_show_launcher()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingMenu()) return AUTO_HIDE_SHOWN; if (launcher_ && launcher_->IsShowingOverflowBubble()) return AUTO_HIDE_SHOWN; if (launcher_widget()->IsActive() || status_->IsActive()) return AUTO_HIDE_SHOWN; if (event_filter_.get() && event_filter_->in_mouse_drag()) return AUTO_HIDE_HIDDEN; aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow(); bool mouse_over_launcher = launcher_widget()->GetWindowScreenBounds().Contains( root->last_mouse_location()); return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN; }
170,898
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UpdateContentLengthPrefsForDataReductionProxy( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, bool via_data_reduction_proxy, base::Time now, PrefService* prefs) { base::TimeDelta time_since_unix_epoch = now - base::Time::UnixEpoch(); const int kMinDaysSinceUnixEpoch = 365 * 2; // 2 years. const int kMaxDaysSinceUnixEpoch = 365 * 1000; // 1000 years. if (time_since_unix_epoch.InDays() < kMinDaysSinceUnixEpoch || time_since_unix_epoch.InDays() > kMaxDaysSinceUnixEpoch) { return; } int64 then_internal = prefs->GetInt64( prefs::kDailyHttpContentLengthLastUpdateDate); base::Time then_midnight = base::Time::FromInternalValue(then_internal).LocalMidnight(); base::Time midnight = now.LocalMidnight(); int days_since_last_update = (midnight - then_midnight).InDays(); DailyDataSavingUpdate total( prefs::kDailyHttpOriginalContentLength, prefs::kDailyHttpReceivedContentLength, prefs); total.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate proxy_enabled( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, prefs::kDailyContentLengthWithDataReductionProxyEnabled, prefs); proxy_enabled.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate via_proxy( prefs::kDailyOriginalContentLengthViaDataReductionProxy, prefs::kDailyContentLengthViaDataReductionProxy, prefs); via_proxy.UpdateForDataChange(days_since_last_update); total.Add(original_content_length, received_content_length); if (with_data_reduction_proxy_enabled) { proxy_enabled.Add(original_content_length, received_content_length); if (via_data_reduction_proxy) { via_proxy.Add(original_content_length, received_content_length); } } if (days_since_last_update) { prefs->SetInt64(prefs::kDailyHttpContentLengthLastUpdateDate, midnight.ToInternalValue()); if (days_since_last_update == 1) { RecordDailyContentLengthHistograms( total.GetOriginalListPrefValue(kNumDaysInHistory - 2), total.GetReceivedListPrefValue(kNumDaysInHistory - 2), proxy_enabled.GetOriginalListPrefValue(kNumDaysInHistory - 2), proxy_enabled.GetReceivedListPrefValue(kNumDaysInHistory - 2), via_proxy.GetOriginalListPrefValue(kNumDaysInHistory - 2), via_proxy.GetReceivedListPrefValue(kNumDaysInHistory - 2)); } } } Commit Message: Added daily UMA for non-data-reduction-proxy data usage when the proxy is enabled. BUG=325325 Review URL: https://codereview.chromium.org/106113002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@239897 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-416
void UpdateContentLengthPrefsForDataReductionProxy( int received_content_length, int original_content_length, bool with_data_reduction_proxy_enabled, DataReductionRequestType data_reduction_type, base::Time now, PrefService* prefs) { base::TimeDelta time_since_unix_epoch = now - base::Time::UnixEpoch(); const int kMinDaysSinceUnixEpoch = 365 * 2; // 2 years. const int kMaxDaysSinceUnixEpoch = 365 * 1000; // 1000 years. if (time_since_unix_epoch.InDays() < kMinDaysSinceUnixEpoch || time_since_unix_epoch.InDays() > kMaxDaysSinceUnixEpoch) { return; } int64 then_internal = prefs->GetInt64( prefs::kDailyHttpContentLengthLastUpdateDate); base::Time then_midnight = base::Time::FromInternalValue(then_internal).LocalMidnight(); base::Time midnight = now.LocalMidnight(); int days_since_last_update = (midnight - then_midnight).InDays(); DailyDataSavingUpdate total( prefs::kDailyHttpOriginalContentLength, prefs::kDailyHttpReceivedContentLength, prefs); total.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate proxy_enabled( prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled, prefs::kDailyContentLengthWithDataReductionProxyEnabled, prefs); proxy_enabled.UpdateForDataChange(days_since_last_update); DailyDataSavingUpdate via_proxy( prefs::kDailyOriginalContentLengthViaDataReductionProxy, prefs::kDailyContentLengthViaDataReductionProxy, prefs); via_proxy.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate https( prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled, prefs); https.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate short_bypass( prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled, prefs); short_bypass.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate long_bypass( prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled, prefs); long_bypass.UpdateForDataChange(days_since_last_update); DailyContentLengthUpdate unknown( prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled, prefs); unknown.UpdateForDataChange(days_since_last_update); total.Add(original_content_length, received_content_length); if (with_data_reduction_proxy_enabled) { proxy_enabled.Add(original_content_length, received_content_length); // Ignore data source cases, if exist, when // "with_data_reduction_proxy_enabled == false" switch (data_reduction_type) { case VIA_DATA_REDUCTION_PROXY: via_proxy.Add(original_content_length, received_content_length); break; case OFF_THE_RECORD: // We don't measure off-the-record data. break; case HTTPS: https.Add(received_content_length); break; case SHORT_BYPASS: short_bypass.Add(received_content_length); break; case LONG_BYPASS: long_bypass.Add(received_content_length); break; case UNKNOWN_TYPE: unknown.Add(received_content_length); break; } } if (days_since_last_update) { prefs->SetInt64(prefs::kDailyHttpContentLengthLastUpdateDate, midnight.ToInternalValue()); if (days_since_last_update == 1) { // Therefore (kNumDaysInHistory - 2) below. RecordDailyContentLengthHistograms( total.GetOriginalListPrefValue(kNumDaysInHistory - 2), total.GetReceivedListPrefValue(kNumDaysInHistory - 2), proxy_enabled.GetOriginalListPrefValue(kNumDaysInHistory - 2), proxy_enabled.GetReceivedListPrefValue(kNumDaysInHistory - 2), via_proxy.GetOriginalListPrefValue(kNumDaysInHistory - 2), via_proxy.GetReceivedListPrefValue(kNumDaysInHistory - 2), https.GetListPrefValue(kNumDaysInHistory - 2), short_bypass.GetListPrefValue(kNumDaysInHistory - 2), long_bypass.GetListPrefValue(kNumDaysInHistory - 2), unknown.GetListPrefValue(kNumDaysInHistory - 2)); } } }
171,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: virtual status_t configureVideoTunnelMode( node_id node, OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(portIndex); data.writeInt32((int32_t)tunneled); data.writeInt32(audioHwSync); remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply); status_t err = reply.readInt32(); if (sidebandHandle) { *sidebandHandle = (native_handle_t *)reply.readNativeHandle(); } return err; } Commit Message: IOMX.cpp uninitialized pointer in BnOMX::onTransact This can lead to local code execution in media server. Fix initializes the pointer and checks the error conditions before returning Bug: 26403627 Change-Id: I7fa90682060148448dba01d6acbe3471d1ddb500 CWE ID: CWE-264
virtual status_t configureVideoTunnelMode( node_id node, OMX_U32 portIndex, OMX_BOOL tunneled, OMX_U32 audioHwSync, native_handle_t **sidebandHandle ) { Parcel data, reply; data.writeInterfaceToken(IOMX::getInterfaceDescriptor()); data.writeInt32((int32_t)node); data.writeInt32(portIndex); data.writeInt32((int32_t)tunneled); data.writeInt32(audioHwSync); remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply); status_t err = reply.readInt32(); if (err == OK && sidebandHandle) { *sidebandHandle = (native_handle_t *)reply.readNativeHandle(); } return err; }
173,897
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 HTMLMediaElement::ProgressEventTimerFired(TimerBase*) { if (network_state_ != kNetworkLoading) return; double time = WTF::CurrentTime(); double timedelta = time - previous_progress_time_; if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) { ScheduleEvent(EventTypeNames::progress); previous_progress_time_ = time; sent_stalled_event_ = false; if (GetLayoutObject()) GetLayoutObject()->UpdateFromElement(); } else if (timedelta > 3.0 && !sent_stalled_event_) { ScheduleEvent(EventTypeNames::stalled); sent_stalled_event_ = true; SetShouldDelayLoadEvent(false); } } Commit Message: defeat cors attacks on audio/video tags Neutralize error messages and fire no progress events until media metadata has been loaded for media loaded from cross-origin locations. Bug: 828265, 826187 Change-Id: Iaf15ef38676403687d6a913cbdc84f2d70a6f5c6 Reviewed-on: https://chromium-review.googlesource.com/1015794 Reviewed-by: Mounir Lamouri <mlamouri@chromium.org> Reviewed-by: Dale Curtis <dalecurtis@chromium.org> Commit-Queue: Fredrik Hubinette <hubbe@chromium.org> Cr-Commit-Position: refs/heads/master@{#557312} CWE ID: CWE-200
void HTMLMediaElement::ProgressEventTimerFired(TimerBase*) { if (network_state_ != kNetworkLoading) return; // If this is an cross-origin request, and we haven't discovered whether // the media is actually playable yet, don't fire any progress events as // those may let the page know information about the resource that it's // not supposed to know. if (MediaShouldBeOpaque()) return; double time = WTF::CurrentTime(); double timedelta = time - previous_progress_time_; if (GetWebMediaPlayer() && GetWebMediaPlayer()->DidLoadingProgress()) { ScheduleEvent(EventTypeNames::progress); previous_progress_time_ = time; sent_stalled_event_ = false; if (GetLayoutObject()) GetLayoutObject()->UpdateFromElement(); } else if (timedelta > 3.0 && !sent_stalled_event_) { ScheduleEvent(EventTypeNames::stalled); sent_stalled_event_ = true; SetShouldDelayLoadEvent(false); } }
173,164
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: ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct ext4_ext_path *path, int flags, unsigned int allocated, struct buffer_head *bh_result, ext4_fsblk_t newblock) { int ret = 0; int err = 0; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical" "block %llu, max_blocks %u, flags %d, allocated %u", inode->i_ino, (unsigned long long)iblock, max_blocks, flags, allocated); ext4_ext_show_leaf(inode, path); /* get_block() before submit the IO, split the extent */ if (flags == EXT4_GET_BLOCKS_PRE_IO) { ret = ext4_split_unwritten_extents(handle, inode, path, iblock, max_blocks, flags); /* * Flag the inode(non aio case) or end_io struct (aio case) * that this IO needs to convertion to written when IO is * completed */ if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); goto out; } /* IO end_io complete, convert the filled extent to written */ if (flags == EXT4_GET_BLOCKS_CONVERT) { ret = ext4_convert_unwritten_extents_endio(handle, inode, path); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); goto out2; } /* buffered IO case */ /* * repeat fallocate creation request * we already have an unwritten extent */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT) goto map_out; /* buffered READ or buffered write_begin() lookup */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * We have blocks reserved already. We * return allocated blocks so that delalloc * won't do block reservation for us. But * the buffer head will be unmapped so that * a read from the block returns 0s. */ set_buffer_unwritten(bh_result); goto out1; } /* buffered write, writepage time, convert*/ ret = ext4_ext_convert_to_initialized(handle, inode, path, iblock, max_blocks); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); out: if (ret <= 0) { err = ret; goto out2; } else allocated = ret; set_buffer_new(bh_result); /* * if we allocated more blocks than requested * we need to make sure we unmap the extra block * allocated. The actual needed block will get * unmapped later when we find the buffer_head marked * new. */ if (allocated > max_blocks) { unmap_underlying_metadata_blocks(inode->i_sb->s_bdev, newblock + max_blocks, allocated - max_blocks); allocated = max_blocks; } /* * If we have done fallocate with the offset that is already * delayed allocated, we would have block reservation * and quota reservation done in the delayed write path. * But fallocate would have already updated quota and block * count for this offset. So cancel these reservation */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 0); map_out: set_buffer_mapped(bh_result); out1: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <jiayingz@google.com> Signed-off-by: "Theodore Ts'o" <tytso@mit.edu> CWE ID:
ext4_ext_handle_uninitialized_extents(handle_t *handle, struct inode *inode, ext4_lblk_t iblock, unsigned int max_blocks, struct ext4_ext_path *path, int flags, unsigned int allocated, struct buffer_head *bh_result, ext4_fsblk_t newblock) { int ret = 0; int err = 0; ext4_io_end_t *io = EXT4_I(inode)->cur_aio_dio; ext_debug("ext4_ext_handle_uninitialized_extents: inode %lu, logical" "block %llu, max_blocks %u, flags %d, allocated %u", inode->i_ino, (unsigned long long)iblock, max_blocks, flags, allocated); ext4_ext_show_leaf(inode, path); /* get_block() before submit the IO, split the extent */ if ((flags & EXT4_GET_BLOCKS_PRE_IO)) { ret = ext4_split_unwritten_extents(handle, inode, path, iblock, max_blocks, flags); /* * Flag the inode(non aio case) or end_io struct (aio case) * that this IO needs to convertion to written when IO is * completed */ if (io) io->flag = EXT4_IO_UNWRITTEN; else ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); if (ext4_should_dioread_nolock(inode)) set_buffer_uninit(bh_result); goto out; } /* IO end_io complete, convert the filled extent to written */ if ((flags & EXT4_GET_BLOCKS_CONVERT)) { ret = ext4_convert_unwritten_extents_endio(handle, inode, path); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); goto out2; } /* buffered IO case */ /* * repeat fallocate creation request * we already have an unwritten extent */ if (flags & EXT4_GET_BLOCKS_UNINIT_EXT) goto map_out; /* buffered READ or buffered write_begin() lookup */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { /* * We have blocks reserved already. We * return allocated blocks so that delalloc * won't do block reservation for us. But * the buffer head will be unmapped so that * a read from the block returns 0s. */ set_buffer_unwritten(bh_result); goto out1; } /* buffered write, writepage time, convert*/ ret = ext4_ext_convert_to_initialized(handle, inode, path, iblock, max_blocks); if (ret >= 0) ext4_update_inode_fsync_trans(handle, inode, 1); out: if (ret <= 0) { err = ret; goto out2; } else allocated = ret; set_buffer_new(bh_result); /* * if we allocated more blocks than requested * we need to make sure we unmap the extra block * allocated. The actual needed block will get * unmapped later when we find the buffer_head marked * new. */ if (allocated > max_blocks) { unmap_underlying_metadata_blocks(inode->i_sb->s_bdev, newblock + max_blocks, allocated - max_blocks); allocated = max_blocks; } /* * If we have done fallocate with the offset that is already * delayed allocated, we would have block reservation * and quota reservation done in the delayed write path. * But fallocate would have already updated quota and block * count for this offset. So cancel these reservation */ if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) ext4_da_update_reserve_space(inode, allocated, 0); map_out: set_buffer_mapped(bh_result); out1: if (allocated > max_blocks) allocated = max_blocks; ext4_ext_show_leaf(inode, path); bh_result->b_bdev = inode->i_sb->s_bdev; bh_result->b_blocknr = newblock; out2: if (path) { ext4_ext_drop_refs(path); kfree(path); } return err ? err : allocated; }
167,537
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 AppControllerImpl::GetApps( mojom::AppController::GetAppsCallback callback) { std::vector<chromeos::kiosk_next_home::mojom::AppPtr> app_list; app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { app_list.push_back(CreateAppPtr(update)); }); std::move(callback).Run(std::move(app_list)); } Commit Message: Refactor the AppController implementation into a KeyedService. This is necessary to guarantee that the AppController will not outlive the AppServiceProxy, which could happen before during Profile destruction. Bug: 945427 Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336 Reviewed-by: Michael Giuffrida <michaelpg@chromium.org> Commit-Queue: Lucas Tenório <ltenorio@chromium.org> Cr-Commit-Position: refs/heads/master@{#645122} CWE ID: CWE-416
void AppControllerImpl::GetApps( void AppControllerService::GetApps( mojom::AppController::GetAppsCallback callback) { std::vector<chromeos::kiosk_next_home::mojom::AppPtr> app_list; app_service_proxy_->AppRegistryCache().ForEachApp( [this, &app_list](const apps::AppUpdate& update) { app_list.push_back(CreateAppPtr(update)); }); std::move(callback).Run(std::move(app_list)); }
172,082
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: SplashPath *Splash::makeDashedPath(SplashPath *path) { SplashPath *dPath; SplashCoord lineDashTotal; SplashCoord lineDashStartPhase, lineDashDist, segLen; SplashCoord x0, y0, x1, y1, xa, ya; GBool lineDashStartOn, lineDashOn, newPath; int lineDashStartIdx, lineDashIdx; int i, j, k; lineDashTotal = 0; for (i = 0; i < state->lineDashLength; ++i) { lineDashTotal += state->lineDash[i]; } if (lineDashTotal == 0) { return new SplashPath(); } lineDashStartPhase = state->lineDashPhase; i = splashFloor(lineDashStartPhase / lineDashTotal); lineDashStartPhase -= (SplashCoord)i * lineDashTotal; lineDashStartOn = gTrue; lineDashStartIdx = 0; if (lineDashStartPhase > 0) { while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { lineDashStartOn = !lineDashStartOn; lineDashStartPhase -= state->lineDash[lineDashStartIdx]; ++lineDashStartIdx; } } dPath = new SplashPath(); while (i < path->length) { for (j = i; j < path->length - 1 && !(path->flags[j] & splashPathLast); ++j) ; lineDashOn = lineDashStartOn; lineDashIdx = lineDashStartIdx; lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; newPath = gTrue; for (k = i; k < j; ++k) { x0 = path->pts[k].x; y0 = path->pts[k].y; x1 = path->pts[k+1].x; y1 = path->pts[k+1].y; segLen = splashDist(x0, y0, x1, y1); while (segLen > 0) { if (lineDashDist >= segLen) { if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(x1, y1); } lineDashDist -= segLen; segLen = 0; } else { xa = x0 + (lineDashDist / segLen) * (x1 - x0); ya = y0 + (lineDashDist / segLen) * (y1 - y0); if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(xa, ya); } x0 = xa; y0 = ya; segLen -= lineDashDist; lineDashDist = 0; } if (lineDashDist <= 0) { lineDashOn = !lineDashOn; if (++lineDashIdx == state->lineDashLength) { lineDashIdx = 0; } lineDashDist = state->lineDash[lineDashIdx]; newPath = gTrue; } } } i = j + 1; } if (dPath->length == 0) { GBool allSame = gTrue; for (int i = 0; allSame && i < path->length - 1; ++i) { allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; } if (allSame) { x0 = path->pts[0].x; y0 = path->pts[0].y; dPath->moveTo(x0, y0); dPath->lineTo(x0, y0); } } return dPath; } Commit Message: CWE ID: CWE-119
SplashPath *Splash::makeDashedPath(SplashPath *path) { SplashPath *dPath; SplashCoord lineDashTotal; SplashCoord lineDashStartPhase, lineDashDist, segLen; SplashCoord x0, y0, x1, y1, xa, ya; GBool lineDashStartOn, lineDashOn, newPath; int lineDashStartIdx, lineDashIdx; int i, j, k; lineDashTotal = 0; for (i = 0; i < state->lineDashLength; ++i) { lineDashTotal += state->lineDash[i]; } if (lineDashTotal == 0) { return new SplashPath(); } lineDashStartPhase = state->lineDashPhase; i = splashFloor(lineDashStartPhase / lineDashTotal); lineDashStartPhase -= (SplashCoord)i * lineDashTotal; lineDashStartOn = gTrue; lineDashStartIdx = 0; if (lineDashStartPhase > 0) { while (lineDashStartIdx < state->lineDashLength && lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { lineDashStartOn = !lineDashStartOn; lineDashStartPhase -= state->lineDash[lineDashStartIdx]; ++lineDashStartIdx; } if (unlikely(lineDashStartIdx == state->lineDashLength)) { return new SplashPath(); } } dPath = new SplashPath(); while (i < path->length) { for (j = i; j < path->length - 1 && !(path->flags[j] & splashPathLast); ++j) ; lineDashOn = lineDashStartOn; lineDashIdx = lineDashStartIdx; lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; newPath = gTrue; for (k = i; k < j; ++k) { x0 = path->pts[k].x; y0 = path->pts[k].y; x1 = path->pts[k+1].x; y1 = path->pts[k+1].y; segLen = splashDist(x0, y0, x1, y1); while (segLen > 0) { if (lineDashDist >= segLen) { if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(x1, y1); } lineDashDist -= segLen; segLen = 0; } else { xa = x0 + (lineDashDist / segLen) * (x1 - x0); ya = y0 + (lineDashDist / segLen) * (y1 - y0); if (lineDashOn) { if (newPath) { dPath->moveTo(x0, y0); newPath = gFalse; } dPath->lineTo(xa, ya); } x0 = xa; y0 = ya; segLen -= lineDashDist; lineDashDist = 0; } if (lineDashDist <= 0) { lineDashOn = !lineDashOn; if (++lineDashIdx == state->lineDashLength) { lineDashIdx = 0; } lineDashDist = state->lineDash[lineDashIdx]; newPath = gTrue; } } } i = j + 1; } if (dPath->length == 0) { GBool allSame = gTrue; for (int i = 0; allSame && i < path->length - 1; ++i) { allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; } if (allSame) { x0 = path->pts[0].x; y0 = path->pts[0].y; dPath->moveTo(x0, y0); dPath->lineTo(x0, y0); } } return dPath; }
164,734
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 RequestSender::OnNetworkFetcherComplete( const GURL& original_url, std::unique_ptr<std::string> response_body, int net_error, const std::string& header_etag, int64_t xheader_retry_after_sec) { DCHECK(thread_checker_.CalledOnValidThread()); VLOG(1) << "request completed from url: " << original_url.spec(); int error = -1; if (response_body && response_code_ == 200) { DCHECK_EQ(0, net_error); error = 0; } else if (response_code_ != -1) { error = response_code_; } else { error = net_error; } int retry_after_sec = -1; if (original_url.SchemeIsCryptographic() && error > 0) retry_after_sec = base::saturated_cast<int>(xheader_retry_after_sec); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&RequestSender::SendInternalComplete, base::Unretained(this), error, response_body ? *response_body : std::string(), header_etag, retry_after_sec)); } Commit Message: Fix error handling in the request sender and url fetcher downloader. That means handling the network errors by primarily looking at net_error. Bug: 1028369 Change-Id: I8181bced25f8b56144ea336a03883d0dceea5108 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1935428 Reviewed-by: Joshua Pawlicki <waffles@chromium.org> Commit-Queue: Sorin Jianu <sorin@chromium.org> Cr-Commit-Position: refs/heads/master@{#719199} CWE ID: CWE-20
void RequestSender::OnNetworkFetcherComplete( const GURL& original_url, std::unique_ptr<std::string> response_body, int net_error, const std::string& header_etag, int64_t xheader_retry_after_sec) { DCHECK(thread_checker_.CalledOnValidThread()); VLOG(1) << "request completed from url: " << original_url.spec(); int error = -1; if (!net_error && response_code_ == 200) error = 0; else if (response_code_ != -1) error = response_code_; else error = net_error; int retry_after_sec = -1; if (original_url.SchemeIsCryptographic() && error > 0) retry_after_sec = base::saturated_cast<int>(xheader_retry_after_sec); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&RequestSender::SendInternalComplete, base::Unretained(this), error, response_body ? *response_body : std::string(), header_etag, retry_after_sec)); }
172,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: log2vis_utf8 (PyObject * string, int unicode_length, FriBidiParType base_direction, int clean, int reordernsm) { FriBidiChar *logical = NULL; /* input fribidi unicode buffer */ FriBidiChar *visual = NULL; /* output fribidi unicode buffer */ char *visual_utf8 = NULL; /* output fribidi UTF-8 buffer */ FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */ PyObject *result = NULL; /* failure */ /* Allocate fribidi unicode buffers */ logical = PyMem_New (FriBidiChar, unicode_length + 1); if (logical == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } visual = PyMem_New (FriBidiChar, unicode_length + 1); if (visual == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate unicode buffer"); goto cleanup; } /* Convert to unicode and order visually */ fribidi_set_reorder_nsm(reordernsm); fribidi_utf8_to_unicode (PyString_AS_STRING (string), PyString_GET_SIZE (string), logical); if (!fribidi_log2vis (logical, unicode_length, &base_direction, visual, NULL, NULL, NULL)) { PyErr_SetString (PyExc_RuntimeError, "fribidi failed to order string"); goto cleanup; } /* Cleanup the string if requested */ if (clean) fribidi_remove_bidi_marks (visual, unicode_length, NULL, NULL, NULL); /* Allocate fribidi UTF-8 buffer */ visual_utf8 = PyMem_New(char, (unicode_length * 4)+1); if (visual_utf8 == NULL) { PyErr_SetString (PyExc_MemoryError, "failed to allocate UTF-8 buffer"); goto cleanup; } /* Encode the reordered string and create result string */ new_len = fribidi_unicode_to_utf8 (visual, unicode_length, visual_utf8); result = PyString_FromStringAndSize (visual_utf8, new_len); if (result == NULL) /* XXX does it raise any error? */ goto cleanup; cleanup: /* Delete unicode buffers */ PyMem_Del (logical); PyMem_Del (visual); PyMem_Del (visual_utf8); return result; } Commit Message: refactor pyfribidi.c module pyfribidi.c is now compiled as _pyfribidi. This module only handles unicode internally and doesn't use the fribidi_utf8_to_unicode function (which can't handle 4 byte utf-8 sequences). This fixes the buffer overflow in issue #2. The code is now also much simpler: pyfribidi.c is down from 280 to 130 lines of code. We now ship a pure python pyfribidi that handles the case when non-unicode strings are passed in. We now also adapt the size of the output string if clean=True is passed. CWE ID: CWE-119
log2vis_utf8 (PyObject * string, int unicode_length,
165,642
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlXPathObjectPtr obj; xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } xmlXPathFreeObject(obj); } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } Commit Message: Fix harmless memory error in generate-id. BUG=140368 Review URL: https://chromiumcodereview.appspot.com/10823168 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@149998 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)doc); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); }
170,903
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: xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlBufferPtr buf; int l, c; int count = 0; if ((ctxt == NULL) || (entity == NULL) || ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) || (entity->content != NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Reading %s entity content input\n", entity->name); buf = xmlBufferCreate(); if (buf == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } input = xmlNewEntityInputStream(ctxt, entity); if (input == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent input error"); xmlBufferFree(buf); return(-1); } /* * Push the entity as the current input, read char by char * saving to the buffer until the end of the entity or an error */ if (xmlPushInput(ctxt, input) < 0) { xmlBufferFree(buf); return(-1); } GROW; c = CUR_CHAR(l); while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) && (IS_CHAR(c))) { xmlBufferAdd(buf, ctxt->input->cur, l); if (count++ > 100) { count = 0; GROW; } NEXTL(l); c = CUR_CHAR(l); } if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) { xmlPopInput(ctxt); } else if (!IS_CHAR(c)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlLoadEntityContent: invalid char value %d\n", c); xmlBufferFree(buf); return(-1); } entity->content = buf->content; buf->content = NULL; xmlBufferFree(buf); return(0); } 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
xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { xmlParserInputPtr input; xmlBufferPtr buf; int l, c; int count = 0; if ((ctxt == NULL) || (entity == NULL) || ((entity->etype != XML_EXTERNAL_PARAMETER_ENTITY) && (entity->etype != XML_EXTERNAL_GENERAL_PARSED_ENTITY)) || (entity->content != NULL)) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } if (xmlParserDebugEntities) xmlGenericError(xmlGenericErrorContext, "Reading %s entity content input\n", entity->name); buf = xmlBufferCreate(); if (buf == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent parameter error"); return(-1); } input = xmlNewEntityInputStream(ctxt, entity); if (input == NULL) { xmlFatalErr(ctxt, XML_ERR_INTERNAL_ERROR, "xmlLoadEntityContent input error"); xmlBufferFree(buf); return(-1); } /* * Push the entity as the current input, read char by char * saving to the buffer until the end of the entity or an error */ if (xmlPushInput(ctxt, input) < 0) { xmlBufferFree(buf); return(-1); } GROW; c = CUR_CHAR(l); while ((ctxt->input == input) && (ctxt->input->cur < ctxt->input->end) && (IS_CHAR(c))) { xmlBufferAdd(buf, ctxt->input->cur, l); if (count++ > 100) { count = 0; GROW; if (ctxt->instate == XML_PARSER_EOF) { xmlBufferFree(buf); return(-1); } } NEXTL(l); c = CUR_CHAR(l); } if ((ctxt->input == input) && (ctxt->input->cur >= ctxt->input->end)) { xmlPopInput(ctxt); } else if (!IS_CHAR(c)) { xmlFatalErrMsgInt(ctxt, XML_ERR_INVALID_CHAR, "xmlLoadEntityContent: invalid char value %d\n", c); xmlBufferFree(buf); return(-1); } entity->content = buf->content; buf->content = NULL; xmlBufferFree(buf); return(0); }
171,269
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 SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (dds_info->ddscaps1 & DDSCAPS_MIPMAP && (dds_info->ddscaps1 & DDSCAPS_TEXTURE || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) { if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } w = DIV2(dds_info->width); h = DIV2(dds_info->height); /* Mipmapcount includes the main image, so start from one */ for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++) { offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size; (void) SeekBlob(image, offset, SEEK_CUR); w = DIV2(w); h = DIV2(h); } } return(MagickTrue); }
168,904
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: transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id, PNG_CONST image_transform *transform_list) { memset(dp, 0, sizeof *dp); /* Standard fields */ standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/, pm->use_update_info); /* Parameter fields */ dp->pm = pm; dp->transform_list = transform_list; /* Local variable fields */ dp->output_colour_type = 255; /* invalid */ dp->output_bit_depth = 255; /* invalid */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id, const image_transform *transform_list) { memset(dp, 0, sizeof *dp); /* Standard fields */ standard_display_init(&dp->this, &pm->this, id, do_read_interlace, pm->use_update_info); /* Parameter fields */ dp->pm = pm; dp->transform_list = transform_list; dp->max_gamma_8 = 16; /* Local variable fields */ dp->output_colour_type = 255; /* invalid */ dp->output_bit_depth = 255; /* invalid */ dp->unpacked = 0; /* not unpacked */ }
173,712
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: rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size) { static iconv_t icv_utf16_to_local; size_t ibl, obl; char *pin, *pout; if (!icv_utf16_to_local) { icv_utf16_to_local = iconv_open(g_codepage, WINDOWS_CODEPAGE); if (icv_utf16_to_local == (iconv_t) - 1) { logger(Protocol, Error, "rdp_in_unistr(), iconv_open[%s -> %s] fail %p", WINDOWS_CODEPAGE, g_codepage, icv_utf16_to_local); abort(); } } /* Dynamic allocate of destination string if not provided */ if (*string == NULL) { *string = xmalloc(in_len * 2); *str_size = in_len * 2; } ibl = in_len; obl = *str_size - 1; pin = (char *) s->p; pout = *string; if (iconv(icv_utf16_to_local, (char **) &pin, &ibl, &pout, &obl) == (size_t) - 1) { if (errno == E2BIG) { logger(Protocol, Warning, "rdp_in_unistr(), server sent an unexpectedly long string, truncating"); } else { logger(Protocol, Warning, "rdp_in_unistr(), iconv fail, errno %d", errno); free(*string); *string = NULL; *str_size = 0; } abort(); } /* we must update the location of the current STREAM for future reads of s->p */ s->p += in_len; *pout = 0; if (*string) *str_size = pout - *string; } 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
rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size) { static iconv_t icv_utf16_to_local; size_t ibl, obl; char *pin, *pout; struct stream packet = *s; if ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2))) { logger(Protocol, Error, "rdp_in_unistr(), length of unicode data is out of bounds."); abort(); } if (!s_check_rem(s, in_len)) { rdp_protocol_error("rdp_in_unistr(), consume of unicode data from stream would overrun", &packet); } if (!icv_utf16_to_local) { icv_utf16_to_local = iconv_open(g_codepage, WINDOWS_CODEPAGE); if (icv_utf16_to_local == (iconv_t) - 1) { logger(Protocol, Error, "rdp_in_unistr(), iconv_open[%s -> %s] fail %p", WINDOWS_CODEPAGE, g_codepage, icv_utf16_to_local); abort(); } } /* Dynamic allocate of destination string if not provided */ if (*string == NULL) { *string = xmalloc(in_len * 2); *str_size = in_len * 2; } ibl = in_len; obl = *str_size - 1; pin = (char *) s->p; pout = *string; if (iconv(icv_utf16_to_local, (char **) &pin, &ibl, &pout, &obl) == (size_t) - 1) { if (errno == E2BIG) { logger(Protocol, Warning, "rdp_in_unistr(), server sent an unexpectedly long string, truncating"); } else { logger(Protocol, Warning, "rdp_in_unistr(), iconv fail, errno %d", errno); free(*string); *string = NULL; *str_size = 0; } abort(); } /* we must update the location of the current STREAM for future reads of s->p */ s->p += in_len; *pout = 0; if (*string) *str_size = pout - *string; }
169,804
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 exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (size_t)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return (size_t)*(double *)value; } return 0; } Commit Message: Fix bug #73737 FPE when parsing a tag format CWE ID: CWE-189
static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel TSRMLS_DC) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(uchar *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den); } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type single"); #endif return (size_t)*(float *)value; case TAG_FMT_DOUBLE: #ifdef EXIF_DEBUG php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Found value of type double"); #endif return (size_t)*(double *)value; } return 0; }
168,516
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 ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) { ASSERT(m_alreadyStarted); if (sourceCode.isEmpty()) return; RefPtr<Document> elementDocument(m_element->document()); RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); if (!contextDocument) return; LocalFrame* frame = contextDocument->frame(); bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source()); if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) return; if (m_isExternalScript && m_resource && !m_resource->mimeTypeAllowedByNosniff()) { contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + m_resource->url().elidedString() + "' because its MIME type ('" + m_resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."); return; } if (frame) { const bool isImportedScript = contextDocument != elementDocument; IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0); if (isHTMLScriptLoader(m_element)) contextDocument->pushCurrentScript(toHTMLScriptElement(m_element)); AccessControlStatus corsCheck = NotSharableCrossOrigin; if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin())) corsCheck = SharableCrossOrigin; frame->script().executeScriptInMainWorld(sourceCode, corsCheck); if (isHTMLScriptLoader(m_element)) { ASSERT(contextDocument->currentScript() == m_element); contextDocument->popCurrentScript(); } } } Commit Message: Apply 'x-content-type-options' check to dynamically inserted script. BUG=348581 Review URL: https://codereview.chromium.org/185593011 git-svn-id: svn://svn.chromium.org/blink/trunk@168570 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-362
void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode) { ASSERT(m_alreadyStarted); if (sourceCode.isEmpty()) return; RefPtr<Document> elementDocument(m_element->document()); RefPtr<Document> contextDocument = elementDocument->contextDocument().get(); if (!contextDocument) return; LocalFrame* frame = contextDocument->frame(); bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source()); if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber))) return; if (m_isExternalScript) { ScriptResource* resource = m_resource ? m_resource.get() : sourceCode.resource(); if (resource && !resource->mimeTypeAllowedByNosniff()) { contextDocument->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Refused to execute script from '" + resource->url().elidedString() + "' because its MIME type ('" + resource->mimeType() + "') is not executable, and strict MIME type checking is enabled."); return; } } if (frame) { const bool isImportedScript = contextDocument != elementDocument; IgnoreDestructiveWriteCountIncrementer ignoreDestructiveWriteCountIncrementer(m_isExternalScript || isImportedScript ? contextDocument.get() : 0); if (isHTMLScriptLoader(m_element)) contextDocument->pushCurrentScript(toHTMLScriptElement(m_element)); AccessControlStatus corsCheck = NotSharableCrossOrigin; if (sourceCode.resource() && sourceCode.resource()->passesAccessControlCheck(m_element->document().securityOrigin())) corsCheck = SharableCrossOrigin; frame->script().executeScriptInMainWorld(sourceCode, corsCheck); if (isHTMLScriptLoader(m_element)) { ASSERT(contextDocument->currentScript() == m_element); contextDocument->popCurrentScript(); } } }
171,408
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NetworkHandler::SetCookie(const std::string& name, const std::string& value, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, Maybe<bool> secure, Maybe<bool> http_only, Maybe<std::string> same_site, Maybe<double> expires, std::unique_ptr<SetCookieCallback> callback) { if (!process_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &SetCookieOnIO, base::Unretained( process_->GetStoragePartition()->GetURLRequestContext()), name, value, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), secure.fromMaybe(false), http_only.fromMaybe(false), same_site.fromMaybe(""), expires.fromMaybe(-1), base::BindOnce(&CookieSetOnIO, std::move(callback)))); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void NetworkHandler::SetCookie(const std::string& name, const std::string& value, Maybe<std::string> url, Maybe<std::string> domain, Maybe<std::string> path, Maybe<bool> secure, Maybe<bool> http_only, Maybe<std::string> same_site, Maybe<double> expires, std::unique_ptr<SetCookieCallback> callback) { if (!storage_partition_) { callback->sendFailure(Response::InternalError()); return; } if (!url.isJust() && !domain.isJust()) { callback->sendFailure(Response::InvalidParams( "At least one of the url and domain needs to be specified")); } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce( &SetCookieOnIO, base::Unretained(storage_partition_->GetURLRequestContext()), name, value, url.fromMaybe(""), domain.fromMaybe(""), path.fromMaybe(""), secure.fromMaybe(false), http_only.fromMaybe(false), same_site.fromMaybe(""), expires.fromMaybe(-1), base::BindOnce(&CookieSetOnIO, std::move(callback)))); }
172,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(locale_compose) { smart_str loc_name_s = {0}; smart_str *loc_name = &loc_name_s; zval* arr = NULL; HashTable* hash_arr = NULL; int result = 0; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } hash_arr = HASH_OF( arr ); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) RETURN_FALSE; /* Check for grandfathered first */ result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG); if( result == SUCCESS){ RETURN_SMART_STR(loc_name); } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Not grandfathered */ result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG); if( result == LOC_NOT_FOUND ){ intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC ); smart_str_free(loc_name); RETURN_FALSE; } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Extlang */ result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Script */ result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Region */ result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Variant */ result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Private */ result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } RETURN_SMART_STR(loc_name); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
PHP_FUNCTION(locale_compose) { smart_str loc_name_s = {0}; smart_str *loc_name = &loc_name_s; zval* arr = NULL; HashTable* hash_arr = NULL; int result = 0; intl_error_reset( NULL TSRMLS_CC ); if(zend_parse_parameters( ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE) { intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: unable to parse input params", 0 TSRMLS_CC ); RETURN_FALSE; } hash_arr = HASH_OF( arr ); if( !hash_arr || zend_hash_num_elements( hash_arr ) == 0 ) RETURN_FALSE; /* Check for grandfathered first */ result = append_key_value(loc_name, hash_arr, LOC_GRANDFATHERED_LANG_TAG); if( result == SUCCESS){ RETURN_SMART_STR(loc_name); } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Not grandfathered */ result = append_key_value(loc_name, hash_arr , LOC_LANG_TAG); if( result == LOC_NOT_FOUND ){ intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "locale_compose: parameter array does not contain 'language' tag.", 0 TSRMLS_CC ); smart_str_free(loc_name); RETURN_FALSE; } if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Extlang */ result = append_multiple_key_values(loc_name, hash_arr , LOC_EXTLANG_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Script */ result = append_key_value(loc_name, hash_arr , LOC_SCRIPT_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Region */ result = append_key_value( loc_name, hash_arr , LOC_REGION_TAG); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Variant */ result = append_multiple_key_values( loc_name, hash_arr , LOC_VARIANT_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } /* Private */ result = append_multiple_key_values( loc_name, hash_arr , LOC_PRIVATE_TAG TSRMLS_CC); if( !handleAppendResult( result, loc_name TSRMLS_CC)){ RETURN_FALSE; } RETURN_SMART_STR(loc_name); }
167,191
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: Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK)) { /* Not a tunnel packet, just a pseudo packet */ p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); } Commit Message: teredo: be stricter on what to consider valid teredo Invalid Teredo can lead to valid DNS traffic (or other UDP traffic) being misdetected as Teredo. This leads to false negatives in the UDP payload inspection. Make the teredo code only consider a packet teredo if the encapsulated data was decoded without any 'invalid' events being set. Bug #2736. CWE ID: CWE-20
Packet *PacketTunnelPktSetup(ThreadVars *tv, DecodeThreadVars *dtv, Packet *parent, uint8_t *pkt, uint32_t len, enum DecodeTunnelProto proto, PacketQueue *pq) { int ret; SCEnter(); /* get us a packet */ Packet *p = PacketGetFromQueueOrAlloc(); if (unlikely(p == NULL)) { SCReturnPtr(NULL, "Packet"); } /* copy packet and set lenght, proto */ PacketCopyData(p, pkt, len); p->recursion_level = parent->recursion_level + 1; p->ts.tv_sec = parent->ts.tv_sec; p->ts.tv_usec = parent->ts.tv_usec; p->datalink = DLT_RAW; p->tenant_id = parent->tenant_id; /* set the root ptr to the lowest layer */ if (parent->root != NULL) p->root = parent->root; else p->root = parent; /* tell new packet it's part of a tunnel */ SET_TUNNEL_PKT(p); ret = DecodeTunnel(tv, dtv, p, GET_PKT_DATA(p), GET_PKT_LEN(p), pq, proto); if (unlikely(ret != TM_ECODE_OK) || (proto == DECODE_TUNNEL_IPV6_TEREDO && (p->flags & PKT_IS_INVALID))) { /* Not a (valid) tunnel packet */ SCLogDebug("tunnel packet is invalid"); p->root = NULL; UNSET_TUNNEL_PKT(p); TmqhOutputPacketpool(tv, p); SCReturnPtr(NULL, "Packet"); } /* tell parent packet it's part of a tunnel */ SET_TUNNEL_PKT(parent); /* increment tunnel packet refcnt in the root packet */ TUNNEL_INCR_PKT_TPR(p); /* disable payload (not packet) inspection on the parent, as the payload * is the packet we will now run through the system separately. We do * check it against the ip/port/other header checks though */ DecodeSetNoPayloadInspectionFlag(parent); SCReturnPtr(p, "Packet"); }
169,479
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: build_principal_va(krb5_context context, krb5_principal princ, unsigned int rlen, const char *realm, va_list ap) { krb5_error_code retval = 0; char *r = NULL; krb5_data *data = NULL; krb5_int32 count = 0; krb5_int32 size = 2; /* initial guess at needed space */ char *component = NULL; data = malloc(size * sizeof(krb5_data)); if (!data) { retval = ENOMEM; } if (!retval) { r = strdup(realm); if (!r) { retval = ENOMEM; } } while (!retval && (component = va_arg(ap, char *))) { if (count == size) { krb5_data *new_data = NULL; size *= 2; new_data = realloc(data, size * sizeof(krb5_data)); if (new_data) { data = new_data; } else { retval = ENOMEM; } } if (!retval) { data[count].length = strlen(component); data[count].data = strdup(component); if (!data[count].data) { retval = ENOMEM; } count++; } } if (!retval) { princ->type = KRB5_NT_UNKNOWN; princ->magic = KV5M_PRINCIPAL; princ->realm = make_data(r, rlen); princ->data = data; princ->length = count; r = NULL; /* take ownership */ data = NULL; /* take ownership */ } if (data) { while (--count >= 0) { free(data[count].data); } free(data); } free(r); return retval; } Commit Message: Fix build_principal memory bug [CVE-2015-2697] In build_principal_va(), use k5memdup0() instead of strdup() to make a copy of the realm, to ensure that we allocate the correct number of bytes and do not read past the end of the input string. This bug affects krb5_build_principal(), krb5_build_principal_va(), and krb5_build_principal_alloc_va(). krb5_build_principal_ext() is not affected. CVE-2015-2697: In MIT krb5 1.7 and later, an authenticated attacker may be able to cause a KDC to crash using a TGS request with a large realm field beginning with a null byte. If the KDC attempts to find a referral to answer the request, it constructs a principal name for lookup using krb5_build_principal() with the requested realm. Due to a bug in this function, the null byte causes only one byte be allocated for the realm field of the constructed principal, far less than its length. Subsequent operations on the lookup principal may cause a read beyond the end of the mapped memory region, causing the KDC process to crash. CVSSv2: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8252 (new) target_version: 1.14 tags: pullup CWE ID: CWE-119
build_principal_va(krb5_context context, krb5_principal princ, unsigned int rlen, const char *realm, va_list ap) { krb5_error_code retval = 0; char *r = NULL; krb5_data *data = NULL; krb5_int32 count = 0; krb5_int32 size = 2; /* initial guess at needed space */ char *component = NULL; data = malloc(size * sizeof(krb5_data)); if (!data) { retval = ENOMEM; } if (!retval) r = k5memdup0(realm, rlen, &retval); while (!retval && (component = va_arg(ap, char *))) { if (count == size) { krb5_data *new_data = NULL; size *= 2; new_data = realloc(data, size * sizeof(krb5_data)); if (new_data) { data = new_data; } else { retval = ENOMEM; } } if (!retval) { data[count].length = strlen(component); data[count].data = strdup(component); if (!data[count].data) { retval = ENOMEM; } count++; } } if (!retval) { princ->type = KRB5_NT_UNKNOWN; princ->magic = KV5M_PRINCIPAL; princ->realm = make_data(r, rlen); princ->data = data; princ->length = count; r = NULL; /* take ownership */ data = NULL; /* take ownership */ } if (data) { while (--count >= 0) { free(data[count].data); } free(data); } free(r); return retval; }
166,641
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 amd_gpio_remove(struct platform_device *pdev) { struct amd_gpio *gpio_dev; gpio_dev = platform_get_drvdata(pdev); gpiochip_remove(&gpio_dev->gc); pinctrl_unregister(gpio_dev->pctrl); return 0; } Commit Message: pinctrl/amd: Drop pinctrl_unregister for devm_ registered device It's not necessary to unregister pin controller device registered with devm_pinctrl_register() and using pinctrl_unregister() leads to a double free. Fixes: 3bfd44306c65 ("pinctrl: amd: Add support for additional GPIO") Signed-off-by: Wei Yongjun <weiyongjun1@huawei.com> Signed-off-by: Linus Walleij <linus.walleij@linaro.org> CWE ID: CWE-415
static int amd_gpio_remove(struct platform_device *pdev) { struct amd_gpio *gpio_dev; gpio_dev = platform_get_drvdata(pdev); gpiochip_remove(&gpio_dev->gc); return 0; }
169,419
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 ixheaacd_esbr_postradixcompute2(WORD32 *ptr_y, WORD32 *ptr_x, const WORD32 *pdig_rev_tbl, WORD32 npoints) { WORD32 i, k; WORD32 h2; WORD32 x_0, x_1, x_2, x_3; WORD32 x_4, x_5, x_6, x_7; WORD32 x_8, x_9, x_a, x_b, x_c, x_d, x_e, x_f; WORD32 n00, n10, n20, n30, n01, n11, n21, n31; WORD32 n02, n12, n22, n32, n03, n13, n23, n33; WORD32 n0, j0; WORD32 *x2, *x0; WORD32 *y0, *y1, *y2, *y3; y0 = ptr_y; y2 = ptr_y + (WORD32)npoints; x0 = ptr_x; x2 = ptr_x + (WORD32)(npoints >> 1); y1 = y0 + (WORD32)(npoints >> 2); y3 = y2 + (WORD32)(npoints >> 2); j0 = 8; n0 = npoints >> 1; for (k = 0; k < 2; k++) { for (i = 0; i<npoints>> 1; i += 8) { h2 = *pdig_rev_tbl++ >> 2; x_0 = *x0++; x_1 = *x0++; x_2 = *x0++; x_3 = *x0++; x_4 = *x0++; x_5 = *x0++; x_6 = *x0++; x_7 = *x0++; n00 = x_0 + x_2; n01 = x_1 + x_3; n20 = x_0 - x_2; n21 = x_1 - x_3; n10 = x_4 + x_6; n11 = x_5 + x_7; n30 = x_4 - x_6; n31 = x_5 - x_7; y0[h2] = n00; y0[h2 + 1] = n01; y1[h2] = n10; y1[h2 + 1] = n11; y2[h2] = n20; y2[h2 + 1] = n21; y3[h2] = n30; y3[h2 + 1] = n31; x_8 = *x2++; x_9 = *x2++; x_a = *x2++; x_b = *x2++; x_c = *x2++; x_d = *x2++; x_e = *x2++; x_f = *x2++; n02 = x_8 + x_a; n03 = x_9 + x_b; n22 = x_8 - x_a; n23 = x_9 - x_b; n12 = x_c + x_e; n13 = x_d + x_f; n32 = x_c - x_e; n33 = x_d - x_f; y0[h2 + 2] = n02; y0[h2 + 3] = n03; y1[h2 + 2] = n12; y1[h2 + 3] = n13; y2[h2 + 2] = n22; y2[h2 + 3] = n23; y3[h2 + 2] = n32; y3[h2 + 3] = n33; } x0 += (WORD32)npoints >> 1; x2 += (WORD32)npoints >> 1; } } Commit Message: Fix for stack corruption in esbr Bug: 110769924 Test: poc from bug before/after Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e (cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a) (cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50) CWE ID: CWE-787
VOID ixheaacd_esbr_postradixcompute2(WORD32 *ptr_y, WORD32 *ptr_x, const WORD32 *pdig_rev_tbl, WORD32 npoints) { WORD32 i, k; WORD32 h2; WORD32 x_0, x_1, x_2, x_3; WORD32 x_4, x_5, x_6, x_7; WORD32 x_8, x_9, x_a, x_b, x_c, x_d, x_e, x_f; WORD32 n0, j0; WORD32 *x2, *x0; WORD32 *y0, *y1, *y2, *y3; y0 = ptr_y; y2 = ptr_y + (WORD32)npoints; x0 = ptr_x; x2 = ptr_x + (WORD32)(npoints >> 1); y1 = y0 + (WORD32)(npoints >> 2); y3 = y2 + (WORD32)(npoints >> 2); j0 = 8; n0 = npoints >> 1; for (k = 0; k < 2; k++) { for (i = 0; i<npoints>> 1; i += 8) { h2 = *pdig_rev_tbl++ >> 2; x_0 = *x0++; x_1 = *x0++; x_2 = *x0++; x_3 = *x0++; x_4 = *x0++; x_5 = *x0++; x_6 = *x0++; x_7 = *x0++; y0[h2] = ixheaacd_add32_sat(x_0, x_2); y0[h2 + 1] = ixheaacd_add32_sat(x_1, x_3); y1[h2] = ixheaacd_add32_sat(x_4, x_6); y1[h2 + 1] = ixheaacd_add32_sat(x_5, x_7); y2[h2] = ixheaacd_sub32_sat(x_0, x_2); y2[h2 + 1] = ixheaacd_sub32_sat(x_1, x_3); y3[h2] = ixheaacd_sub32_sat(x_4, x_6); y3[h2 + 1] = ixheaacd_sub32_sat(x_5, x_7); x_8 = *x2++; x_9 = *x2++; x_a = *x2++; x_b = *x2++; x_c = *x2++; x_d = *x2++; x_e = *x2++; x_f = *x2++; y0[h2 + 2] = ixheaacd_add32_sat(x_8, x_a); y0[h2 + 3] = ixheaacd_add32_sat(x_9, x_b); y1[h2 + 2] = ixheaacd_add32_sat(x_c, x_e); y1[h2 + 3] = ixheaacd_add32_sat(x_d, x_f); y2[h2 + 2] = ixheaacd_sub32_sat(x_8, x_a); y2[h2 + 3] = ixheaacd_sub32_sat(x_9, x_b); y3[h2 + 2] = ixheaacd_sub32_sat(x_c, x_e); y3[h2 + 3] = ixheaacd_sub32_sat(x_d, x_f); } x0 += (WORD32)npoints >> 1; x2 += (WORD32)npoints >> 1; } }
174,087
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ResourceTracker::CleanupInstanceData(PP_Instance instance, bool delete_instance) { DLOG_IF(ERROR, !CheckIdType(instance, PP_ID_TYPE_INSTANCE)) << instance << " is not a PP_Instance."; InstanceMap::iterator found = instance_map_.find(instance); if (found == instance_map_.end()) { NOTREACHED(); return; } InstanceData& data = *found->second; ResourceSet::iterator cur_res = data.resources.begin(); while (cur_res != data.resources.end()) { ResourceMap::iterator found_resource = live_resources_.find(*cur_res); if (found_resource == live_resources_.end()) { NOTREACHED(); } else { Resource* resource = found_resource->second.first; resource->LastPluginRefWasDeleted(true); live_resources_.erase(*cur_res); } ResourceSet::iterator current = cur_res++; data.resources.erase(current); } DCHECK(data.resources.empty()); VarSet::iterator cur_var = data.object_vars.begin(); while (cur_var != data.object_vars.end()) { VarSet::iterator current = cur_var++; PP_Var object_pp_var; object_pp_var.type = PP_VARTYPE_OBJECT; object_pp_var.value.as_id = *current; scoped_refptr<ObjectVar> object_var(ObjectVar::FromPPVar(object_pp_var)); if (object_var.get()) object_var->InstanceDeleted(); live_vars_.erase(*current); data.object_vars.erase(*current); } DCHECK(data.object_vars.empty()); if (delete_instance) instance_map_.erase(found); } Commit Message: Maintain a map of all resources in the resource tracker and clear instance back pointers when needed, BUG=85808 Review URL: http://codereview.chromium.org/7196001 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89746 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void ResourceTracker::CleanupInstanceData(PP_Instance instance, bool delete_instance) { DLOG_IF(ERROR, !CheckIdType(instance, PP_ID_TYPE_INSTANCE)) << instance << " is not a PP_Instance."; InstanceMap::iterator found = instance_map_.find(instance); if (found == instance_map_.end()) { NOTREACHED(); return; } InstanceData& data = *found->second; ResourceSet::iterator cur_res = data.ref_resources.begin(); while (cur_res != data.ref_resources.end()) { ResourceMap::iterator found_resource = live_resources_.find(*cur_res); if (found_resource == live_resources_.end()) { NOTREACHED(); } else { Resource* resource = found_resource->second.first; resource->LastPluginRefWasDeleted(); live_resources_.erase(*cur_res); } ResourceSet::iterator current = cur_res++; data.ref_resources.erase(current); } DCHECK(data.ref_resources.empty()); VarSet::iterator cur_var = data.object_vars.begin(); while (cur_var != data.object_vars.end()) { VarSet::iterator current = cur_var++; PP_Var object_pp_var; object_pp_var.type = PP_VARTYPE_OBJECT; object_pp_var.value.as_id = *current; scoped_refptr<ObjectVar> object_var(ObjectVar::FromPPVar(object_pp_var)); if (object_var.get()) object_var->InstanceDeleted(); live_vars_.erase(*current); data.object_vars.erase(*current); } DCHECK(data.object_vars.empty()); // Clear any resources that still reference this instance. for (std::set<Resource*>::iterator res = data.assoc_resources.begin(); res != data.assoc_resources.end(); ++res) (*res)->ClearInstance(); data.assoc_resources.clear(); if (delete_instance) instance_map_.erase(found); }
170,417
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 FeatureInfo::EnableOESTextureHalfFloatLinear() { if (!oes_texture_half_float_linear_available_) return; AddExtensionString("GL_OES_texture_half_float_linear"); feature_flags_.enable_texture_half_float_linear = true; feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RGBA_F16); } Commit Message: gpu: Disallow use of IOSurfaces for half-float format with swiftshader. R=kbr@chromium.org Bug: 998038 Change-Id: Ic31d28938ef205b36657fc7bd297fe8a63d08543 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1798052 Commit-Queue: Kenneth Russell <kbr@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Auto-Submit: Khushal <khushalsagar@chromium.org> Cr-Commit-Position: refs/heads/master@{#695826} CWE ID: CWE-125
void FeatureInfo::EnableOESTextureHalfFloatLinear() { if (!oes_texture_half_float_linear_available_) return; AddExtensionString("GL_OES_texture_half_float_linear"); feature_flags_.enable_texture_half_float_linear = true; // TODO(capn) : Re-enable this once we have ANGLE+SwiftShader supporting // IOSurfaces. if (workarounds_.disable_half_float_for_gmb) return; feature_flags_.gpu_memory_buffer_formats.Add(gfx::BufferFormat::RGBA_F16); }
172,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: download::DownloadInterruptReason DownloadManagerImpl::BeginDownloadRequest( std::unique_ptr<net::URLRequest> url_request, ResourceContext* resource_context, download::DownloadUrlParameters* params) { if (ResourceDispatcherHostImpl::Get()->is_shutdown()) return download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN; ResourceDispatcherHostImpl::Get()->InitializeURLRequest( url_request.get(), Referrer(params->referrer(), Referrer::NetReferrerPolicyToBlinkReferrerPolicy( params->referrer_policy())), true, // download. params->render_process_host_id(), params->render_view_host_routing_id(), params->render_frame_host_routing_id(), PREVIEWS_OFF, resource_context); url_request->set_first_party_url_policy( net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT); const GURL& url = url_request->original_url(); const net::URLRequestContext* request_context = url_request->context(); if (!request_context->job_factory()->IsHandledProtocol(url.scheme())) { DVLOG(1) << "Download request for unsupported protocol: " << url.possibly_invalid_spec(); return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST; } std::unique_ptr<ResourceHandler> handler( DownloadResourceHandler::CreateForNewRequest( url_request.get(), params->request_origin(), params->download_source(), params->follow_cross_origin_redirects())); ResourceDispatcherHostImpl::Get()->BeginURLRequest( std::move(url_request), std::move(handler), true, // download params->content_initiated(), params->do_not_prompt_for_login(), resource_context); return download::DOWNLOAD_INTERRUPT_REASON_NONE; } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <japhet@chromium.org> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
download::DownloadInterruptReason DownloadManagerImpl::BeginDownloadRequest( std::unique_ptr<net::URLRequest> url_request, ResourceContext* resource_context, download::DownloadUrlParameters* params) { if (ResourceDispatcherHostImpl::Get()->is_shutdown()) return download::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN; ResourceDispatcherHostImpl::Get()->InitializeURLRequest( url_request.get(), Referrer(params->referrer(), Referrer::NetReferrerPolicyToBlinkReferrerPolicy( params->referrer_policy())), true, // download. params->render_process_host_id(), params->render_view_host_routing_id(), params->render_frame_host_routing_id(), params->frame_tree_node_id(), PREVIEWS_OFF, resource_context); url_request->set_first_party_url_policy( net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT); const GURL& url = url_request->original_url(); const net::URLRequestContext* request_context = url_request->context(); if (!request_context->job_factory()->IsHandledProtocol(url.scheme())) { DVLOG(1) << "Download request for unsupported protocol: " << url.possibly_invalid_spec(); return download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST; } std::unique_ptr<ResourceHandler> handler( DownloadResourceHandler::CreateForNewRequest( url_request.get(), params->request_origin(), params->download_source(), params->follow_cross_origin_redirects())); ResourceDispatcherHostImpl::Get()->BeginURLRequest( std::move(url_request), std::move(handler), true, // download params->content_initiated(), params->do_not_prompt_for_login(), resource_context); return download::DOWNLOAD_INTERRUPT_REASON_NONE; }
173,021
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: set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth, png_uint_32 value, png_const_bytep gamma_table, double conv) { unsigned int mask = (1U << bit_depth)-1; x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */ if (value <= mask) { png_uint_32 offset = x >> 3; if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes)) { row += offset; switch (bit_depth) { case 1: case 2: case 4: /* Don't gamma correct - values get smashed */ { unsigned int shift = (8 - bit_depth) - (x & 0x7U); mask <<= shift; value = (value << shift) & mask; *row = (png_byte)((*row & ~mask) | value); } return; default: fprintf(stderr, "makepng: bad bit depth (internal error)\n"); exit(1); case 16: value = (unsigned int)floor(65535*pow(value/65535.,conv)+.5); *row++ = (png_byte)(value >> 8); *row = (png_byte)value; return; case 8: *row = gamma_table[value]; return; } } else { fprintf(stderr, "makepng: row buffer overflow (internal error)\n"); exit(1); } } else { fprintf(stderr, "makepng: component overflow (internal error)\n"); exit(1); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
set_value(png_bytep row, size_t rowbytes, png_uint_32 x, unsigned int bit_depth, png_uint_32 value, png_const_bytep gamma_table, double conv) { unsigned int mask = (1U << bit_depth)-1; x *= bit_depth; /* Maximum x is 4*1024, maximum bit_depth is 16 */ if (value <= mask) { png_uint_32 offset = x >> 3; if (offset < rowbytes && (bit_depth < 16 || offset+1 < rowbytes)) { row += offset; switch (bit_depth) { case 1: case 2: case 4: /* Don't gamma correct - values get smashed */ { unsigned int shift = (8 - bit_depth) - (x & 0x7U); mask <<= shift; value = (value << shift) & mask; *row = (png_byte)((*row & ~mask) | value); } return; default: fprintf(stderr, "makepng: bad bit depth (internal error)\n"); exit(1); case 16: value = flooru(65535*pow(value/65535.,conv)+.5); *row++ = (png_byte)(value >> 8); *row = (png_byte)value; return; case 8: *row = gamma_table[value]; return; } } else { fprintf(stderr, "makepng: row buffer overflow (internal error)\n"); exit(1); } } else { fprintf(stderr, "makepng: component overflow (internal error)\n"); exit(1); } }
173,585
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); }
167,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: PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s) { static const char module[] = "PredictorEncodeTile"; TIFFPredictorState *sp = PredictorState(tif); uint8 *working_copy; tmsize_t cc = cc0, rowsize; unsigned char* bp; int result_code; assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encodetile != NULL); /* * Do predictor manipulation in a working buffer to avoid altering * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965 */ working_copy = (uint8*) _TIFFmalloc(cc0); if( working_copy == NULL ) { TIFFErrorExt(tif->tif_clientdata, module, "Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.", cc0 ); return 0; } memcpy( working_copy, bp0, cc0 ); bp = working_copy; rowsize = sp->rowsize; assert(rowsize > 0); assert((cc0%rowsize)==0); while (cc > 0) { (*sp->encodepfunc)(tif, bp, rowsize); cc -= rowsize; bp += rowsize; } result_code = (*sp->encodetile)(tif, working_copy, cc0, s); _TIFFfree( working_copy ); return result_code; } Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c: Replace assertions by runtime checks to avoid assertions in debug mode, or buffer overflows in release mode. Can happen when dealing with unusual tile size like YCbCr with subsampling. Reported as MSVR 35105 by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations team. CWE ID: CWE-119
PredictorEncodeTile(TIFF* tif, uint8* bp0, tmsize_t cc0, uint16 s) { static const char module[] = "PredictorEncodeTile"; TIFFPredictorState *sp = PredictorState(tif); uint8 *working_copy; tmsize_t cc = cc0, rowsize; unsigned char* bp; int result_code; assert(sp != NULL); assert(sp->encodepfunc != NULL); assert(sp->encodetile != NULL); /* * Do predictor manipulation in a working buffer to avoid altering * the callers buffer. http://trac.osgeo.org/gdal/ticket/1965 */ working_copy = (uint8*) _TIFFmalloc(cc0); if( working_copy == NULL ) { TIFFErrorExt(tif->tif_clientdata, module, "Out of memory allocating " TIFF_SSIZE_FORMAT " byte temp buffer.", cc0 ); return 0; } memcpy( working_copy, bp0, cc0 ); bp = working_copy; rowsize = sp->rowsize; assert(rowsize > 0); if((cc0%rowsize)!=0) { TIFFErrorExt(tif->tif_clientdata, "PredictorEncodeTile", "%s", "(cc0%rowsize)!=0"); return 0; } while (cc > 0) { (*sp->encodepfunc)(tif, bp, rowsize); cc -= rowsize; bp += rowsize; } result_code = (*sp->encodetile)(tif, working_copy, cc0, s); _TIFFfree( working_copy ); return result_code; }
166,879
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) //error return true; //must assume done if (total < 0) return false; //assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); } 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
bool Segment::DoneParsing() const bool Segment::DoneParsing() const { if (m_size < 0) { long long total, avail; const int status = m_pReader->Length(&total, &avail); if (status < 0) // error return true; // must assume done if (total < 0) return false; // assume live stream return (m_pos >= total); } const long long stop = m_start + m_size; return (m_pos >= stop); }
174,268
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int imap_subscribe(char *path, bool subscribe) { struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; char errstr[STRING]; struct Buffer err, token; struct ImapMbox mx; if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox) { mutt_error(_("Bad mailbox name")); return -1; } idata = imap_conn_find(&(mx.account), 0); if (!idata) goto fail; imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); if (ImapCheckSubscribed) { mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); snprintf(mbox, sizeof(mbox), "%smailboxes \"%s\"", subscribe ? "" : "un", path); if (mutt_parse_rc_line(mbox, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } if (subscribe) mutt_message(_("Subscribing to %s..."), buf); else mutt_message(_("Unsubscribing from %s..."), buf); imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox); if (imap_exec(idata, buf, 0) < 0) goto fail; imap_unmunge_mbox_name(idata, mx.mbox); if (subscribe) mutt_message(_("Subscribed to %s"), mx.mbox); else mutt_message(_("Unsubscribed from %s"), mx.mbox); FREE(&mx.mbox); return 0; fail: FREE(&mx.mbox); return -1; } Commit Message: Quote path in imap_subscribe CWE ID: CWE-77
int imap_subscribe(char *path, bool subscribe) { struct ImapData *idata = NULL; char buf[LONG_STRING]; char mbox[LONG_STRING]; char errstr[STRING]; struct Buffer err, token; struct ImapMbox mx; size_t len = 0; if (!mx_is_imap(path) || imap_parse_path(path, &mx) || !mx.mbox) { mutt_error(_("Bad mailbox name")); return -1; } idata = imap_conn_find(&(mx.account), 0); if (!idata) goto fail; imap_fix_path(idata, mx.mbox, buf, sizeof(buf)); if (!*buf) mutt_str_strfcpy(buf, "INBOX", sizeof(buf)); if (ImapCheckSubscribed) { mutt_buffer_init(&token); mutt_buffer_init(&err); err.data = errstr; err.dsize = sizeof(errstr); len = snprintf(mbox, sizeof(mbox), "%smailboxes ", subscribe ? "" : "un"); imap_quote_string(mbox + len, sizeof(mbox) - len, path, true); if (mutt_parse_rc_line(mbox, &token, &err)) mutt_debug(1, "Error adding subscribed mailbox: %s\n", errstr); FREE(&token.data); } if (subscribe) mutt_message(_("Subscribing to %s..."), buf); else mutt_message(_("Unsubscribing from %s..."), buf); imap_munge_mbox_name(idata, mbox, sizeof(mbox), buf); snprintf(buf, sizeof(buf), "%sSUBSCRIBE %s", subscribe ? "" : "UN", mbox); if (imap_exec(idata, buf, 0) < 0) goto fail; imap_unmunge_mbox_name(idata, mx.mbox); if (subscribe) mutt_message(_("Subscribed to %s"), mx.mbox); else mutt_message(_("Unsubscribed from %s"), mx.mbox); FREE(&mx.mbox); return 0; fail: FREE(&mx.mbox); return -1; }
169,137
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 BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) { if (!_zgfx) return FALSE; while (_zgfx->cBitsCurrent < _nbits) { _zgfx->BitsCurrent <<= 8; if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd) _zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++; _zgfx->cBitsCurrent += 8; } _zgfx->cBitsRemaining -= _nbits; _zgfx->cBitsCurrent -= _nbits; _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); } Commit Message: Fixed CVE-2018-8784 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-119
static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) { if (!_zgfx) return FALSE; while (_zgfx->cBitsCurrent < _nbits) { _zgfx->BitsCurrent <<= 8; if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd) _zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++; _zgfx->cBitsCurrent += 8; } _zgfx->cBitsRemaining -= _nbits; _zgfx->cBitsCurrent -= _nbits; _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); return TRUE; }
169,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: static int create_problem_dir(GHashTable *problem_info, unsigned pid) { /* Exit if free space is less than 1/4 of MaxCrashReportsSize */ if (g_settings_nMaxCrashReportsSize > 0) { if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) exit(1); } /* Create temp directory with the problem data. * This directory is renamed to final directory name after * all files have been stored into it. */ gchar *dir_basename = g_hash_table_lookup(problem_info, "basename"); if (!dir_basename) dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE); char *path = xasprintf("%s/%s-%s-%u.new", g_settings_dump_location, dir_basename, iso_date_string(NULL), pid); /* This item is useless, don't save it */ g_hash_table_remove(problem_info, "basename"); /* No need to check the path length, as all variables used are limited, * and dd_create() fails if the path is too long. */ struct dump_dir *dd = dd_create(path, client_uid, DEFAULT_DUMP_DIR_MODE); if (!dd) { error_msg_and_die("Error creating problem directory '%s'", path); } dd_create_basic_files(dd, client_uid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE); if (!gpkey) { /* Obtain and save the command line. */ char *cmdline = get_cmdline(pid); if (cmdline) { dd_save_text(dd, FILENAME_CMDLINE, cmdline); free(cmdline); } } /* Store id of the user whose application crashed. */ char uid_str[sizeof(long) * 3 + 2]; sprintf(uid_str, "%lu", (long)client_uid); dd_save_text(dd, FILENAME_UID, uid_str); GHashTableIter iter; gpointer gpvalue; g_hash_table_iter_init(&iter, problem_info); while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue)) { dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue); } dd_close(dd); /* Not needing it anymore */ g_hash_table_destroy(problem_info); /* Move the completely created problem directory * to final directory. */ char *newpath = xstrndup(path, strlen(path) - strlen(".new")); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log_notice("Saved problem directory of pid %u to '%s'", pid, path); /* We let the peer know that problem dir was created successfully * _before_ we run potentially long-running post-create. */ printf("HTTP/1.1 201 Created\r\n\r\n"); fflush(NULL); close(STDOUT_FILENO); xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */ /* Trim old problem directories if necessary */ if (g_settings_nMaxCrashReportsSize > 0) { trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path); } run_post_create(path); /* free(path); */ exit(0); } Commit Message: make the dump directories owned by root by default It was discovered that the abrt event scripts create a user-readable copy of a sosreport file in abrt problem directories, and include excerpts of /var/log/messages selected by the user-controlled process name, leading to an information disclosure. This issue was discovered by Florian Weimer of Red Hat Product Security. Related: #1212868 Signed-off-by: Jakub Filak <jfilak@redhat.com> CWE ID: CWE-200
static int create_problem_dir(GHashTable *problem_info, unsigned pid) { /* Exit if free space is less than 1/4 of MaxCrashReportsSize */ if (g_settings_nMaxCrashReportsSize > 0) { if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) exit(1); } /* Create temp directory with the problem data. * This directory is renamed to final directory name after * all files have been stored into it. */ gchar *dir_basename = g_hash_table_lookup(problem_info, "basename"); if (!dir_basename) dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE); char *path = xasprintf("%s/%s-%s-%u.new", g_settings_dump_location, dir_basename, iso_date_string(NULL), pid); /* This item is useless, don't save it */ g_hash_table_remove(problem_info, "basename"); /* No need to check the path length, as all variables used are limited, * and dd_create() fails if the path is too long. */ struct dump_dir *dd = dd_create(path, g_settings_privatereports ? 0 : client_uid, DEFAULT_DUMP_DIR_MODE); if (!dd) { error_msg_and_die("Error creating problem directory '%s'", path); } dd_create_basic_files(dd, client_uid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE); if (!gpkey) { /* Obtain and save the command line. */ char *cmdline = get_cmdline(pid); if (cmdline) { dd_save_text(dd, FILENAME_CMDLINE, cmdline); free(cmdline); } } /* Store id of the user whose application crashed. */ char uid_str[sizeof(long) * 3 + 2]; sprintf(uid_str, "%lu", (long)client_uid); dd_save_text(dd, FILENAME_UID, uid_str); GHashTableIter iter; gpointer gpvalue; g_hash_table_iter_init(&iter, problem_info); while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue)) { dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue); } dd_close(dd); /* Not needing it anymore */ g_hash_table_destroy(problem_info); /* Move the completely created problem directory * to final directory. */ char *newpath = xstrndup(path, strlen(path) - strlen(".new")); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log_notice("Saved problem directory of pid %u to '%s'", pid, path); /* We let the peer know that problem dir was created successfully * _before_ we run potentially long-running post-create. */ printf("HTTP/1.1 201 Created\r\n\r\n"); fflush(NULL); close(STDOUT_FILENO); xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */ /* Trim old problem directories if necessary */ if (g_settings_nMaxCrashReportsSize > 0) { trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path); } run_post_create(path); /* free(path); */ exit(0); }
170,147
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: perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! */ while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) if (palette_number == 0) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); 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:
perform_gamma_threshold_tests(png_modifier *pm) { png_byte colour_type = 0; png_byte bit_depth = 0; unsigned int palette_number = 0; /* Don't test more than one instance of each palette - it's pointless, in * fact this test is somewhat excessive since libpng doesn't make this * decision based on colour type or bit depth! * * CHANGED: now test two palettes and, as a side effect, images with and * without tRNS. */ while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg_gamma_threshold, pm->test_tRNS)) if (palette_number < 2) { double test_gamma = 1.0; while (test_gamma >= .4) { /* There's little point testing the interlacing vs non-interlacing, * but this can be set from the command line. */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, test_gamma, 1/test_gamma); test_gamma *= .95; } /* And a special test for sRGB */ gamma_threshold_test(pm, colour_type, bit_depth, pm->interlace_type, .45455, 2.2); if (fail(pm)) return; } }
173,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void coroutine_fn v9fs_xattrcreate(void *opaque) { int flags; int32_t fid; int64_t size; ssize_t err = 0; V9fsString name; size_t offset = 7; V9fsFidState *file_fidp; V9fsFidState *xattr_fidp; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags); if (err < 0) { goto out_nofid; } trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); file_fidp = get_fid(pdu, fid); if (file_fidp == NULL) { err = -EINVAL; goto out_nofid; } /* Make the file fid point to xattr */ xattr_fidp = file_fidp; xattr_fidp->fid_type = P9_FID_XATTR; xattr_fidp->fs.xattr.copied_len = 0; xattr_fidp->fs.xattr.len = size; xattr_fidp->fs.xattr.flags = flags; v9fs_string_init(&xattr_fidp->fs.xattr.name); v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); xattr_fidp->fs.xattr.value = g_malloc(size); err = offset; put_fid(pdu, file_fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&name); } Commit Message: CWE ID: CWE-119
static void coroutine_fn v9fs_xattrcreate(void *opaque) { int flags; int32_t fid; int64_t size; ssize_t err = 0; V9fsString name; size_t offset = 7; V9fsFidState *file_fidp; V9fsFidState *xattr_fidp; V9fsPDU *pdu = opaque; v9fs_string_init(&name); err = pdu_unmarshal(pdu, offset, "dsqd", &fid, &name, &size, &flags); if (err < 0) { goto out_nofid; } trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags); file_fidp = get_fid(pdu, fid); if (file_fidp == NULL) { err = -EINVAL; goto out_nofid; } /* Make the file fid point to xattr */ xattr_fidp = file_fidp; xattr_fidp->fid_type = P9_FID_XATTR; xattr_fidp->fs.xattr.copied_len = 0; xattr_fidp->fs.xattr.len = size; xattr_fidp->fs.xattr.flags = flags; v9fs_string_init(&xattr_fidp->fs.xattr.name); v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name); xattr_fidp->fs.xattr.value = g_malloc0(size); err = offset; put_fid(pdu, file_fidp); out_nofid: pdu_complete(pdu, err); v9fs_string_free(&name); }
164,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: le64addr_string(netdissect_options *ndo, const u_char *ep) { const unsigned int len = 8; register u_int i; register char *cp; register struct enamemem *tp; char buf[BUFSIZE]; tp = lookup_bytestring(ndo, ep, len); if (tp->e_name) return (tp->e_name); cp = buf; for (i = len; i > 0 ; --i) { *cp++ = hex[*(ep + i - 1) >> 4]; *cp++ = hex[*(ep + i - 1) & 0xf]; *cp++ = ':'; } cp --; *cp = '\0'; tp->e_name = strdup(buf); if (tp->e_name == NULL) (*ndo->ndo_error)(ndo, "le64addr_string: strdup(buf)"); return (tp->e_name); } Commit Message: CVE-2017-12894/In lookup_bytestring(), take the length of the byte string into account. Otherwise, if, in our search of the hash table, we come across a byte string that's shorter than the string we're looking for, we'll search past the end of the string in the hash table. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
le64addr_string(netdissect_options *ndo, const u_char *ep) { const unsigned int len = 8; register u_int i; register char *cp; register struct bsnamemem *tp; char buf[BUFSIZE]; tp = lookup_bytestring(ndo, ep, len); if (tp->bs_name) return (tp->bs_name); cp = buf; for (i = len; i > 0 ; --i) { *cp++ = hex[*(ep + i - 1) >> 4]; *cp++ = hex[*(ep + i - 1) & 0xf]; *cp++ = ':'; } cp --; *cp = '\0'; tp->bs_name = strdup(buf); if (tp->bs_name == NULL) (*ndo->ndo_error)(ndo, "le64addr_string: strdup(buf)"); return (tp->bs_name); }
167,958
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { assert(pReader); assert(pos >= 0); int status; len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) //error or underflow return status; if (status > 0) //interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) //we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) int status; //#ifdef _DEBUG // long long total, available; // status = pReader->Length(&total, &available); // assert(status >= 0); // assert((total < 0) || (available <= total)); // assert(pos < available); // assert((available - pos) >= 1); //assume here max u-int len is 8 //#endif len = 1; unsigned char b; status = pReader->Read(pos, 1, &b); if (status < 0) // error or underflow return status; if (status > 0) // interpreted as "underflow" return E_BUFFER_NOT_FULL; if (b == 0) // we can't handle u-int values larger than 8 bytes return E_FILE_FORMAT_INVALID; unsigned char m = 0x80; while (!(b & m)) { m >>= 1; ++len; } //#ifdef _DEBUG // assert((available - pos) >= len); //#endif long long result = b & (~m); ++pos; for (int i = 1; i < len; ++i) { status = pReader->Read(pos, 1, &b); if (status < 0) { len = 1; return status; } if (status > 0) { len = 1; return E_BUFFER_NOT_FULL; } result <<= 8; result |= b; ++pos; } return result; }
174,434
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 __init xfrm6_tunnel_spi_init(void) { xfrm6_tunnel_spi_kmem = kmem_cache_create("xfrm6_tunnel_spi", sizeof(struct xfrm6_tunnel_spi), 0, SLAB_HWCACHE_ALIGN, NULL); if (!xfrm6_tunnel_spi_kmem) return -ENOMEM; return 0; } Commit Message: tunnels: fix netns vs proto registration ordering Same stuff as in ip_gre patch: receive hook can be called before netns setup is done, oopsing in net_generic(). Signed-off-by: Alexey Dobriyan <adobriyan@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-362
static int __init xfrm6_tunnel_spi_init(void)
165,882
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: NavigationPolicy GetNavigationPolicy(const WebInputEvent* current_event, const WebWindowFeatures& features) { //// Check that the desired NavigationPolicy |policy| is compatible with the //// observed input event |current_event|. bool as_popup = !features.tool_bar_visible || !features.status_bar_visible || !features.scrollbars_visible || !features.menu_bar_visible || !features.resizable; NavigationPolicy policy = as_popup ? kNavigationPolicyNewPopup : kNavigationPolicyNewForegroundTab; UpdatePolicyForEvent(current_event, &policy); return policy; } Commit Message: Only allow downloading in response to real keyboard modifiers BUG=848531 Change-Id: I97554c8d312243b55647f1376945aee32dbd95bf Reviewed-on: https://chromium-review.googlesource.com/1082216 Reviewed-by: Mike West <mkwst@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#564051} CWE ID:
NavigationPolicy GetNavigationPolicy(const WebInputEvent* current_event, } // anonymous namespace //// Check that the desired NavigationPolicy |policy| is compatible with the //// observed input event |current_event|. NavigationPolicy EffectiveNavigationPolicy(NavigationPolicy policy, const WebInputEvent* current_event, const WebWindowFeatures& features) { bool as_popup = !features.tool_bar_visible || !features.status_bar_visible || !features.scrollbars_visible || !features.menu_bar_visible || !features.resizable; NavigationPolicy user_policy = as_popup ? kNavigationPolicyNewPopup : kNavigationPolicyNewForegroundTab;
173,193
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: WebGLObject::WebGLObject(WebGLRenderingContext* context) : m_object(0) , m_attachmentCount(0) , m_deleted(false) { } Commit Message: Unreviewed, build fix for unused argument warning after r104954. https://bugs.webkit.org/show_bug.cgi?id=75906 Also fixed up somebody's bad merge in Source/WebCore/ChangeLog. * html/canvas/WebGLObject.cpp: (WebCore::WebGLObject::WebGLObject): git-svn-id: svn://svn.chromium.org/blink/trunk@104959 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
WebGLObject::WebGLObject(WebGLRenderingContext* context) WebGLObject::WebGLObject(WebGLRenderingContext*) : m_object(0) , m_attachmentCount(0) , m_deleted(false) { }
170,251
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_inquire_context(minor_status, context_handle, initiator_name, acceptor_name, lifetime_rec, mech_type, ret_flags, locally_initiated, opened) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_name_t *initiator_name; gss_name_t *acceptor_name; OM_uint32 *lifetime_rec; gss_OID *mech_type; OM_uint32 *ret_flags; int *locally_initiated; int *opened; { krb5_context context; krb5_error_code code; krb5_gss_ctx_id_rec *ctx; krb5_gss_name_t initiator, acceptor; krb5_timestamp now; krb5_deltat lifetime; if (initiator_name) *initiator_name = (gss_name_t) NULL; if (acceptor_name) *acceptor_name = (gss_name_t) NULL; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (! ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } initiator = NULL; acceptor = NULL; context = ctx->k5_context; if ((code = krb5_timeofday(context, &now))) { *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } if ((lifetime = ctx->krb_times.endtime - now) < 0) lifetime = 0; if (initiator_name) { if ((code = kg_duplicate_name(context, ctx->initiate ? ctx->here : ctx->there, &initiator))) { *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } } if (acceptor_name) { if ((code = kg_duplicate_name(context, ctx->initiate ? ctx->there : ctx->here, &acceptor))) { if (initiator) kg_release_name(context, &initiator); *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } } if (initiator_name) *initiator_name = (gss_name_t) initiator; if (acceptor_name) *acceptor_name = (gss_name_t) acceptor; if (lifetime_rec) *lifetime_rec = lifetime; if (mech_type) *mech_type = (gss_OID) ctx->mech_used; if (ret_flags) *ret_flags = ctx->gss_flags; if (locally_initiated) *locally_initiated = ctx->initiate; if (opened) *opened = ctx->established; *minor_status = 0; return((lifetime == 0)?GSS_S_CONTEXT_EXPIRED: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_inquire_context(minor_status, context_handle, initiator_name, acceptor_name, lifetime_rec, mech_type, ret_flags, locally_initiated, opened) OM_uint32 *minor_status; gss_ctx_id_t context_handle; gss_name_t *initiator_name; gss_name_t *acceptor_name; OM_uint32 *lifetime_rec; gss_OID *mech_type; OM_uint32 *ret_flags; int *locally_initiated; int *opened; { krb5_context context; krb5_error_code code; krb5_gss_ctx_id_rec *ctx; krb5_gss_name_t initiator, acceptor; krb5_timestamp now; krb5_deltat lifetime; if (initiator_name) *initiator_name = (gss_name_t) NULL; if (acceptor_name) *acceptor_name = (gss_name_t) NULL; ctx = (krb5_gss_ctx_id_rec *) context_handle; if (ctx->terminated || !ctx->established) { *minor_status = KG_CTX_INCOMPLETE; return(GSS_S_NO_CONTEXT); } initiator = NULL; acceptor = NULL; context = ctx->k5_context; if ((code = krb5_timeofday(context, &now))) { *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } if ((lifetime = ctx->krb_times.endtime - now) < 0) lifetime = 0; if (initiator_name) { if ((code = kg_duplicate_name(context, ctx->initiate ? ctx->here : ctx->there, &initiator))) { *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } } if (acceptor_name) { if ((code = kg_duplicate_name(context, ctx->initiate ? ctx->there : ctx->here, &acceptor))) { if (initiator) kg_release_name(context, &initiator); *minor_status = code; save_error_info(*minor_status, context); return(GSS_S_FAILURE); } } if (initiator_name) *initiator_name = (gss_name_t) initiator; if (acceptor_name) *acceptor_name = (gss_name_t) acceptor; if (lifetime_rec) *lifetime_rec = lifetime; if (mech_type) *mech_type = (gss_OID) ctx->mech_used; if (ret_flags) *ret_flags = ctx->gss_flags; if (locally_initiated) *locally_initiated = ctx->initiate; if (opened) *opened = ctx->established; *minor_status = 0; return((lifetime == 0)?GSS_S_CONTEXT_EXPIRED:GSS_S_COMPLETE); }
166,816
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; int count, i; count = be32_to_cpu(aclp->acl_cnt); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); } Commit Message: xfs: validate acl count This prevents in-memory corruption and possible panics if the on-disk ACL is badly corrupted. Signed-off-by: Christoph Hellwig <hch@lst.de> Signed-off-by: Ben Myers <bpm@sgi.com> CWE ID: CWE-189
xfs_acl_from_disk(struct xfs_acl *aclp) { struct posix_acl_entry *acl_e; struct posix_acl *acl; struct xfs_acl_entry *ace; int count, i; count = be32_to_cpu(aclp->acl_cnt); if (count > XFS_ACL_MAX_ENTRIES) return ERR_PTR(-EFSCORRUPTED); acl = posix_acl_alloc(count, GFP_KERNEL); if (!acl) return ERR_PTR(-ENOMEM); for (i = 0; i < count; i++) { acl_e = &acl->a_entries[i]; ace = &aclp->acl_entry[i]; /* * The tag is 32 bits on disk and 16 bits in core. * * Because every access to it goes through the core * format first this is not a problem. */ acl_e->e_tag = be32_to_cpu(ace->ae_tag); acl_e->e_perm = be16_to_cpu(ace->ae_perm); switch (acl_e->e_tag) { case ACL_USER: case ACL_GROUP: acl_e->e_id = be32_to_cpu(ace->ae_id); break; case ACL_USER_OBJ: case ACL_GROUP_OBJ: case ACL_MASK: case ACL_OTHER: acl_e->e_id = ACL_UNDEFINED_ID; break; default: goto fail; } } return acl; fail: posix_acl_release(acl); return ERR_PTR(-EINVAL); }
165,656
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: Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, const FrameLoadRequest& r, const WebWindowFeatures& features, NavigationPolicy navigation_policy, SandboxFlags sandbox_flags) { if (!web_view_->Client()) return nullptr; if (!frame->GetPage() || frame->GetPage()->Paused()) return nullptr; DCHECK(frame->GetDocument()); Fullscreen::FullyExitFullscreen(*frame->GetDocument()); const AtomicString& frame_name = !EqualIgnoringASCIICase(r.FrameName(), "_blank") ? r.FrameName() : g_empty_atom; WebViewImpl* new_view = static_cast<WebViewImpl*>(web_view_->Client()->CreateView( WebLocalFrameImpl::FromFrame(frame), WrappedResourceRequest(r.GetResourceRequest()), features, frame_name, static_cast<WebNavigationPolicy>(navigation_policy), r.GetShouldSetOpener() == kNeverSetOpener, static_cast<WebSandboxFlags>(sandbox_flags))); if (!new_view) return nullptr; return new_view->GetPage(); } Commit Message: If a page shows a popup, end fullscreen. This was implemented in Blink r159834, but it is susceptible to a popup/fullscreen race. This CL reverts that implementation and re-implements it in WebContents. BUG=752003 TEST=WebContentsImplBrowserTest.PopupsFromJavaScriptEndFullscreen Change-Id: Ia345cdeda273693c3231ad8f486bebfc3d83927f Reviewed-on: https://chromium-review.googlesource.com/606987 Commit-Queue: Avi Drissman <avi@chromium.org> Reviewed-by: Charlie Reis <creis@chromium.org> Reviewed-by: Philip Jägenstedt <foolip@chromium.org> Cr-Commit-Position: refs/heads/master@{#498171} CWE ID: CWE-20
Page* ChromeClientImpl::CreateWindow(LocalFrame* frame, const FrameLoadRequest& r, const WebWindowFeatures& features, NavigationPolicy navigation_policy, SandboxFlags sandbox_flags) { if (!web_view_->Client()) return nullptr; if (!frame->GetPage() || frame->GetPage()->Paused()) return nullptr; const AtomicString& frame_name = !EqualIgnoringASCIICase(r.FrameName(), "_blank") ? r.FrameName() : g_empty_atom; WebViewImpl* new_view = static_cast<WebViewImpl*>(web_view_->Client()->CreateView( WebLocalFrameImpl::FromFrame(frame), WrappedResourceRequest(r.GetResourceRequest()), features, frame_name, static_cast<WebNavigationPolicy>(navigation_policy), r.GetShouldSetOpener() == kNeverSetOpener, static_cast<WebSandboxFlags>(sandbox_flags))); if (!new_view) return nullptr; return new_view->GetPage(); }
172,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { int result; handle_t *handle = NULL; struct super_block *sb = file_inode(vma->vm_file)->i_sb; bool write = vmf->flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, EXT4_DATA_TRANS_BLOCKS(sb)); } if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_fault(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); sb_end_pagefault(sb); } return result; } Commit Message: ext4: fix races between page faults and hole punching Currently, page faults and hole punching are completely unsynchronized. This can result in page fault faulting in a page into a range that we are punching after truncate_pagecache_range() has been called and thus we can end up with a page mapped to disk blocks that will be shortly freed. Filesystem corruption will shortly follow. Note that the same race is avoided for truncate by checking page fault offset against i_size but there isn't similar mechanism available for punching holes. Fix the problem by creating new rw semaphore i_mmap_sem in inode and grab it for writing over truncate, hole punching, and other functions removing blocks from extent tree and for read over page faults. We cannot easily use i_data_sem for this since that ranks below transaction start and we need something ranking above it so that it can be held over the whole truncate / hole punching operation. Also remove various workarounds we had in the code to reduce race window when page fault could have created pages with stale mapping information. Signed-off-by: Jan Kara <jack@suse.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> CWE ID: CWE-362
static int ext4_dax_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { int result; handle_t *handle = NULL; struct inode *inode = file_inode(vma->vm_file); struct super_block *sb = inode->i_sb; bool write = vmf->flags & FAULT_FLAG_WRITE; if (write) { sb_start_pagefault(sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); handle = ext4_journal_start_sb(sb, EXT4_HT_WRITE_PAGE, EXT4_DATA_TRANS_BLOCKS(sb)); } else down_read(&EXT4_I(inode)->i_mmap_sem); if (IS_ERR(handle)) result = VM_FAULT_SIGBUS; else result = __dax_fault(vma, vmf, ext4_get_block_dax, ext4_end_io_unwritten); if (write) { if (!IS_ERR(handle)) ext4_journal_stop(handle); up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(sb); } else up_read(&EXT4_I(inode)->i_mmap_sem); return result; }
167,486
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 _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr, const u_char **pktdata, const char *funcname, const int line, const char *file) { int res = pcap_next_ex(pcap, pkthdr, pktdata); if (*pktdata && *pkthdr) { if ((*pkthdr)->len > MAXPACKET) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", file, funcname, line, (*pkthdr)->len, MAXPACKET); exit(-1); } if ((*pkthdr)->len < (*pkthdr)->caplen) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n", file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen); exit(-1); } } return res; } Commit Message: Bug #520 Fix heap overflow on zero or 0xFFFF packet length Add check for packets that report zero packet length. Example of fix: src/tcpprep --auto=bridge --pcap=poc16-get_l2len-heapoverflow --cachefile=/dev/null Warning: poc16-get_l2len-heapoverflow was captured using a snaplen of 17 bytes. This may mean you have truncated packets. safe_pcap_next ERROR: Invalid packet length in tcpprep.c:process_raw_packets() line 334: packet length=0 capture length=0 CWE ID: CWE-125
int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr, const u_char **pktdata, const char *funcname, const int line, const char *file) { int res = pcap_next_ex(pcap, pkthdr, pktdata); if (*pktdata && *pkthdr) { if ((*pkthdr)->len > MAXPACKET) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n", file, funcname, line, (*pkthdr)->len, MAXPACKET); exit(-1); } if (!(*pkthdr)->len || (*pkthdr)->len < (*pkthdr)->caplen) { fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length=%u capture length=%u\n", file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen); exit(-1); } } return res; }
168,947
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 gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { int refs; struct page *head, *page; if (!pgd_access_permitted(orig, write)) return 0; BUILD_BUG_ON(pgd_devmap(orig)); refs = 0; page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = compound_head(pgd_page(orig)); if (!page_cache_add_speculative(head, refs)) { *nr -= refs; return 0; } if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; } Commit Message: Merge branch 'page-refs' (page ref overflow) Merge page ref overflow branch. Jann Horn reported that he can overflow the page ref count with sufficient memory (and a filesystem that is intentionally extremely slow). Admittedly it's not exactly easy. To have more than four billion references to a page requires a minimum of 32GB of kernel memory just for the pointers to the pages, much less any metadata to keep track of those pointers. Jann needed a total of 140GB of memory and a specially crafted filesystem that leaves all reads pending (in order to not ever free the page references and just keep adding more). Still, we have a fairly straightforward way to limit the two obvious user-controllable sources of page references: direct-IO like page references gotten through get_user_pages(), and the splice pipe page duplication. So let's just do that. * branch page-refs: fs: prevent page refcount overflow in pipe_buf_get mm: prevent get_user_pages() from overflowing page refcount mm: add 'try_get_page()' helper function mm: make page ref count overflow check tighter and more explicit CWE ID: CWE-416
static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr, unsigned long end, int write, struct page **pages, int *nr) { int refs; struct page *head, *page; if (!pgd_access_permitted(orig, write)) return 0; BUILD_BUG_ON(pgd_devmap(orig)); refs = 0; page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT); do { pages[*nr] = page; (*nr)++; page++; refs++; } while (addr += PAGE_SIZE, addr != end); head = try_get_compound_head(pgd_page(orig), refs); if (!head) { *nr -= refs; return 0; } if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) { *nr -= refs; while (refs--) put_page(head); return 0; } SetPageReferenced(head); return 1; }
170,225
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 xt_check_entry_offsets(const void *base, unsigned int target_offset, unsigned int next_offset) { const struct xt_entry_target *t; const char *e = base; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct xt_standard_target) != next_offset) return -EINVAL; return 0; } Commit Message: netfilter: x_tables: check for bogus target offset We're currently asserting that targetoff + targetsize <= nextoff. Extend it to also check that targetoff is >= sizeof(xt_entry). Since this is generic code, add an argument pointing to the start of the match/target, we can then derive the base structure size from the delta. We also need the e->elems pointer in a followup change to validate matches. Signed-off-by: Florian Westphal <fw@strlen.de> Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org> CWE ID: CWE-264
int xt_check_entry_offsets(const void *base, const char *elems, unsigned int target_offset, unsigned int next_offset) { long size_of_base_struct = elems - (const char *)base; const struct xt_entry_target *t; const char *e = base; /* target start is within the ip/ip6/arpt_entry struct */ if (target_offset < size_of_base_struct) return -EINVAL; if (target_offset + sizeof(*t) > next_offset) return -EINVAL; t = (void *)(e + target_offset); if (t->u.target_size < sizeof(*t)) return -EINVAL; if (target_offset + t->u.target_size > next_offset) return -EINVAL; if (strcmp(t->u.user.name, XT_STANDARD_TARGET) == 0 && target_offset + sizeof(struct xt_standard_target) != next_offset) return -EINVAL; return 0; }
167,221
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: eval_js(WebKitWebView * web_view, gchar *script, GString *result) { WebKitWebFrame *frame; JSGlobalContextRef context; JSObjectRef globalobject; JSStringRef var_name; JSStringRef js_script; JSValueRef js_result; JSStringRef js_result_string; size_t js_result_size; js_init(); frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view)); context = webkit_web_frame_get_global_context(frame); globalobject = JSContextGetGlobalObject(context); /* uzbl javascript namespace */ var_name = JSStringCreateWithUTF8CString("Uzbl"); JSObjectSetProperty(context, globalobject, var_name, JSObjectMake(context, uzbl.js.classref, NULL), kJSClassAttributeNone, NULL); /* evaluate the script and get return value*/ js_script = JSStringCreateWithUTF8CString(script); js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL); if (js_result && !JSValueIsUndefined(context, js_result)) { js_result_string = JSValueToStringCopy(context, js_result, NULL); js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string); if (js_result_size) { char js_result_utf8[js_result_size]; JSStringGetUTF8CString(js_result_string, js_result_utf8, js_result_size); g_string_assign(result, js_result_utf8); } JSStringRelease(js_result_string); } /* cleanup */ JSObjectDeleteProperty(context, globalobject, var_name, NULL); JSStringRelease(var_name); JSStringRelease(js_script); } Commit Message: disable Uzbl javascript object because of security problem. CWE ID: CWE-264
eval_js(WebKitWebView * web_view, gchar *script, GString *result) { WebKitWebFrame *frame; JSGlobalContextRef context; JSObjectRef globalobject; JSStringRef js_script; JSValueRef js_result; JSStringRef js_result_string; size_t js_result_size; js_init(); frame = webkit_web_view_get_main_frame(WEBKIT_WEB_VIEW(web_view)); context = webkit_web_frame_get_global_context(frame); globalobject = JSContextGetGlobalObject(context); /* evaluate the script and get return value*/ js_script = JSStringCreateWithUTF8CString(script); js_result = JSEvaluateScript(context, js_script, globalobject, NULL, 0, NULL); if (js_result && !JSValueIsUndefined(context, js_result)) { js_result_string = JSValueToStringCopy(context, js_result, NULL); js_result_size = JSStringGetMaximumUTF8CStringSize(js_result_string); if (js_result_size) { char js_result_utf8[js_result_size]; JSStringGetUTF8CString(js_result_string, js_result_utf8, js_result_size); g_string_assign(result, js_result_utf8); } JSStringRelease(js_result_string); } /* cleanup */ JSStringRelease(js_script); }
165,523
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 decode_level3_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) { return 0; } if (!extend_raw_data(header, stream, LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) { return 0; } header_len = lha_decode_uint32(&RAW_DATA(header, 24)); if (header_len > LEVEL_3_MAX_HEADER_LEN) { return 0; } if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; (*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7)); (*header)->length = lha_decode_uint32(&RAW_DATA(header, 11)); (*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15)); (*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21)); (*header)->os_type = RAW_DATA(header, 23); if (!decode_extended_headers(header, 28)) { return 0; } return 1; } Commit Message: Fix integer underflow vulnerability in L3 decode. Marcin 'Icewall' Noga of Cisco TALOS discovered that the level 3 header decoding routines were vulnerable to an integer underflow, if the 32-bit header length was less than the base level 3 header length. This could lead to an exploitable heap corruption condition. Thanks go to Marcin Noga and Regina Wilson of Cisco TALOS for reporting this vulnerability. CWE ID: CWE-190
static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream) { unsigned int header_len; if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) { return 0; } if (!extend_raw_data(header, stream, LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) { return 0; } header_len = lha_decode_uint32(&RAW_DATA(header, 24)); if (header_len > LEVEL_3_MAX_HEADER_LEN || header_len < RAW_DATA_LEN(header)) { return 0; } if (!extend_raw_data(header, stream, header_len - RAW_DATA_LEN(header))) { return 0; } memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5); (*header)->compress_method[5] = '\0'; (*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7)); (*header)->length = lha_decode_uint32(&RAW_DATA(header, 11)); (*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15)); (*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21)); (*header)->os_type = RAW_DATA(header, 23); if (!decode_extended_headers(header, 28)) { return 0; } return 1; }
168,846
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 ExtensionUninstaller::Run() { const extensions::Extension* extension = extensions::ExtensionSystem::Get(profile_)->extension_service()-> GetInstalledExtension(app_id_); if (!extension) { CleanUp(); return; } controller_->OnShowChildDialog(); dialog_.reset(extensions::ExtensionUninstallDialog::Create( profile_, controller_->GetAppListWindow(), this)); dialog_->ConfirmUninstall(extension, extensions::UNINSTALL_REASON_USER_INITIATED); } 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:
void ExtensionUninstaller::Run() { const extensions::Extension* extension = extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension( app_id_); if (!extension) { CleanUp(); return; } controller_->OnShowChildDialog(); dialog_.reset(extensions::ExtensionUninstallDialog::Create( profile_, controller_->GetAppListWindow(), this)); dialog_->ConfirmUninstall(extension, extensions::UNINSTALL_REASON_USER_INITIATED); }
171,724
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 rds_rdma_extra_size(struct rds_rdma_args *args) { struct rds_iovec vec; struct rds_iovec __user *local_vec; int tot_pages = 0; unsigned int nr_pages; unsigned int i; local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr; /* figure out the number of pages in the vector */ for (i = 0; i < args->nr_local; i++) { if (copy_from_user(&vec, &local_vec[i], sizeof(struct rds_iovec))) return -EFAULT; nr_pages = rds_pages_in_vec(&vec); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages * sizeof(struct scatterlist); } Commit Message: RDS: Heap OOB write in rds_message_alloc_sgs() When args->nr_local is 0, nr_pages gets also 0 due some size calculation via rds_rm_size(), which is later used to allocate pages for DMA, this bug produces a heap Out-Of-Bound write access to a specific memory region. Signed-off-by: Mohamed Ghannam <simo.ghannam@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-787
int rds_rdma_extra_size(struct rds_rdma_args *args) { struct rds_iovec vec; struct rds_iovec __user *local_vec; int tot_pages = 0; unsigned int nr_pages; unsigned int i; local_vec = (struct rds_iovec __user *)(unsigned long) args->local_vec_addr; if (args->nr_local == 0) return -EINVAL; /* figure out the number of pages in the vector */ for (i = 0; i < args->nr_local; i++) { if (copy_from_user(&vec, &local_vec[i], sizeof(struct rds_iovec))) return -EFAULT; nr_pages = rds_pages_in_vec(&vec); if (nr_pages == 0) return -EINVAL; tot_pages += nr_pages; /* * nr_pages for one entry is limited to (UINT_MAX>>PAGE_SHIFT)+1, * so tot_pages cannot overflow without first going negative. */ if (tot_pages < 0) return -EINVAL; } return tot_pages * sizeof(struct scatterlist); }
169,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = (x >> 56) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { psf->header.ptr [psf->header.indx++] = (x >> 56) ; psf->header.ptr [psf->header.indx++] = (x >> 48) ; psf->header.ptr [psf->header.indx++] = (x >> 40) ; psf->header.ptr [psf->header.indx++] = (x >> 32) ; psf->header.ptr [psf->header.indx++] = (x >> 24) ; psf->header.ptr [psf->header.indx++] = (x >> 16) ; psf->header.ptr [psf->header.indx++] = (x >> 8) ; psf->header.ptr [psf->header.indx++] = x ; } /* header_put_be_8byte */
170,050
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */
167,112
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 copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir) { memcpy(&p->sel, &xp->selector, sizeof(p->sel)); memcpy(&p->lft, &xp->lft, sizeof(p->lft)); memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft)); p->priority = xp->priority; p->index = xp->index; p->sel.family = xp->family; p->dir = dir; p->action = xp->action; p->flags = xp->flags; p->share = XFRM_SHARE_ANY; /* XXX xp->share */ } Commit Message: xfrm_user: fix info leak in copy_to_user_policy() The memory reserved to dump the xfrm policy includes multiple padding bytes added by the compiler for alignment (padding bytes in struct xfrm_selector and struct xfrm_userpolicy_info). Add an explicit memset(0) before filling the buffer to avoid the heap info leak. Signed-off-by: Mathias Krause <minipli@googlemail.com> Acked-by: Steffen Klassert <steffen.klassert@secunet.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir) { memset(p, 0, sizeof(*p)); memcpy(&p->sel, &xp->selector, sizeof(p->sel)); memcpy(&p->lft, &xp->lft, sizeof(p->lft)); memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft)); p->priority = xp->priority; p->index = xp->index; p->sel.family = xp->family; p->dir = dir; p->action = xp->action; p->flags = xp->flags; p->share = XFRM_SHARE_ANY; /* XXX xp->share */ }
169,902
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 Np_toString(js_State *J) { char buf[32]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, "invalid radix"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[100]; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, "0"); return; } if (isnan(number)) { js_pushstring(J, "NaN"); return; } if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } } Commit Message: Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed(). 32 is not enough to fit sprintf("%.20f", 1e20). We need at least 43 bytes to fit that format. Bump the static buffer size. CWE ID: CWE-119
static void Np_toString(js_State *J) { char buf[100]; js_Object *self = js_toobject(J, 0); int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1); if (self->type != JS_CNUMBER) js_typeerror(J, "not a number"); if (radix == 10) { js_pushstring(J, jsV_numbertostring(J, buf, self->u.number)); return; } if (radix < 2 || radix > 36) js_rangeerror(J, "invalid radix"); /* lame number to string conversion for any radix from 2 to 36 */ { static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; double number = self->u.number; int sign = self->u.number < 0; js_Buffer *sb = NULL; uint64_t u, limit = ((uint64_t)1<<52); int ndigits, exp, point; if (number == 0) { js_pushstring(J, "0"); return; } if (isnan(number)) { js_pushstring(J, "NaN"); return; } if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; } if (sign) number = -number; /* fit as many digits as we want in an int */ exp = 0; while (number * pow(radix, exp) > limit) --exp; while (number * pow(radix, exp+1) < limit) ++exp; u = number * pow(radix, exp) + 0.5; /* trim trailing zeros */ while (u > 0 && (u % radix) == 0) { u /= radix; --exp; } /* serialize digits */ ndigits = 0; while (u > 0) { buf[ndigits++] = digits[u % radix]; u /= radix; } point = ndigits - exp; if (js_try(J)) { js_free(J, sb); js_throw(J); } if (sign) js_putc(J, &sb, '-'); if (point <= 0) { js_putc(J, &sb, '0'); js_putc(J, &sb, '.'); while (point++ < 0) js_putc(J, &sb, '0'); while (ndigits-- > 0) js_putc(J, &sb, buf[ndigits]); } else { while (ndigits-- > 0) { js_putc(J, &sb, buf[ndigits]); if (--point == 0 && ndigits > 0) js_putc(J, &sb, '.'); } while (point-- > 0) js_putc(J, &sb, '0'); } js_putc(J, &sb, 0); js_pushstring(J, sb->s); js_endtry(J); js_free(J, sb); } }
169,703
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: HeadlessWebContentsImpl::HeadlessWebContentsImpl( content::WebContents* web_contents, HeadlessBrowserContextImpl* browser_context) : content::WebContentsObserver(web_contents), web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)), web_contents_(web_contents), agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)), inject_mojo_services_into_isolated_world_(false), browser_context_(browser_context), render_process_host_(web_contents->GetMainFrame()->GetProcess()), weak_ptr_factory_(this) { #if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD) HeadlessPrintManager::CreateForWebContents(web_contents); //// TODO(weili): Add support for printing OOPIFs. #endif web_contents->GetMutableRendererPrefs()->accept_languages = browser_context->options()->accept_language(); web_contents_->SetDelegate(web_contents_delegate_.get()); render_process_host_->AddObserver(this); agent_host_->AddObserver(this); } 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
HeadlessWebContentsImpl::HeadlessWebContentsImpl( content::WebContents* web_contents, HeadlessBrowserContextImpl* browser_context) : content::WebContentsObserver(web_contents), web_contents_delegate_(new HeadlessWebContentsImpl::Delegate(this)), web_contents_(web_contents), agent_host_(content::DevToolsAgentHost::GetOrCreateFor(web_contents)), inject_mojo_services_into_isolated_world_(false), browser_context_(browser_context), render_process_host_(web_contents->GetMainFrame()->GetProcess()), weak_ptr_factory_(this) { #if BUILDFLAG(ENABLE_BASIC_PRINTING) && !defined(CHROME_MULTIPLE_DLL_CHILD) HeadlessPrintManager::CreateForWebContents(web_contents); //// TODO(weili): Add support for printing OOPIFs. #endif web_contents->GetMutableRendererPrefs()->accept_languages = browser_context->options()->accept_language(); web_contents_->SetDelegate(web_contents_delegate_.get()); render_process_host_->AddObserver(this); agent_host_->AddObserver(this); }
171,896
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 svc_rdma_xdr_encode_array_chunk(struct rpcrdma_write_array *ary, int chunk_no, __be32 rs_handle, __be64 rs_offset, u32 write_len) { struct rpcrdma_segment *seg = &ary->wc_array[chunk_no].wc_target; seg->rs_handle = rs_handle; seg->rs_offset = rs_offset; seg->rs_length = cpu_to_be32(write_len); } 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
void svc_rdma_xdr_encode_array_chunk(struct rpcrdma_write_array *ary,
168,159
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: PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } } Commit Message: * libtiff/tif_pixarlog.c: fix potential buffer write overrun in PixarLogDecode() on corrupted/unexpected images (reported by Mathias Svensson) CWE ID: CWE-787
PixarLogSetupDecode(TIFF* tif) { static const char module[] = "PixarLogSetupDecode"; TIFFDirectory *td = &tif->tif_dir; PixarLogState* sp = DecoderState(tif); tmsize_t tbuf_size; assert(sp != NULL); /* Make sure no byte swapping happens on the data * after decompression. */ tif->tif_postdecode = _TIFFNoPostDecode; /* for some reason, we can't do this in TIFFInitPixarLog */ sp->stride = (td->td_planarconfig == PLANARCONFIG_CONTIG ? td->td_samplesperpixel : 1); tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth), td->td_rowsperstrip), sizeof(uint16)); /* add one more stride in case input ends mid-stride */ tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride); if (tbuf_size == 0) return (0); /* TODO: this is an error return without error report through TIFFErrorExt */ sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size); if (sp->tbuf == NULL) return (0); sp->tbuf_size = tbuf_size; if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) sp->user_datafmt = PixarLogGuessDataFmt(td); if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN) { TIFFErrorExt(tif->tif_clientdata, module, "PixarLog compression can't handle bits depth/data format combination (depth: %d)", td->td_bitspersample); return (0); } if (inflateInit(&sp->stream) != Z_OK) { TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg ? sp->stream.msg : "(null)"); return (0); } else { sp->state |= PLSTATE_INIT; return (1); } }
169,450
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: raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; } Commit Message: CVE-2012-0037 Enforce entity loading policy in raptor_libxml_resolveEntity and raptor_libxml_getEntity by checking for file URIs and network URIs. Add RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES / loadExternalEntities for turning on loading of XML external entity loading, disabled by default. This affects all the parsers that use SAX2: rdfxml, rss-tag-soup (and aliases) and rdfa. CWE ID: CWE-200
raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; }
165,663
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 copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); if (chown(dest, getuid(), getgid()) < 0) errExit("chown"); if (chmod(dest, S_IRUSR | S_IWUSR) < 0) errExit("chmod"); unlink(src); } Commit Message: security fix CWE ID: CWE-269
static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user fs_logger2("clone", dest); unlink(src); }
170,097
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: SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return in; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 )); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; return chr; } Commit Message: New Pre Source CWE ID: CWE-119
SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in ) { SQLWCHAR *chr; int len = 0; if ( !in ) { return NULL; } while ( in[ len ] != 0 ) { len ++; } chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 )); len = 0; while ( in[ len ] != 0 ) { chr[ len ] = in[ len ]; len ++; } chr[ len ++ ] = 0; return chr; }
169,316
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 git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; } Commit Message: delta: fix overflow when computing limit When checking whether a delta base offset and length fit into the base we have in memory already, we can trigger an overflow which breaks the check. This would subsequently result in us reading memory from out of bounds of the base. The issue is easily fixed by checking for overflow when adding `off` and `len`, thus guaranteeting that we are never indexing beyond `base_len`. This corresponds to the git patch 8960844a7 (check patch_delta bounds more carefully, 2006-04-07), which adds these overflow checks. Reported-by: Riccardo Schirone <rschiron@redhat.com> CWE ID: CWE-125
int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0, end; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (GIT_ADD_SIZET_OVERFLOW(&end, off, len) || base_len < end || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
169,245
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 dispatch_discard_io(struct xen_blkif *blkif, struct blkif_request *req) { int err = 0; int status = BLKIF_RSP_OKAY; struct block_device *bdev = blkif->vbd.bdev; unsigned long secure; blkif->st_ds_req++; xen_blkif_get(blkif); secure = (blkif->vbd.discard_secure && (req->u.discard.flag & BLKIF_DISCARD_SECURE)) ? BLKDEV_DISCARD_SECURE : 0; err = blkdev_issue_discard(bdev, req->u.discard.sector_number, req->u.discard.nr_sectors, GFP_KERNEL, secure); if (err == -EOPNOTSUPP) { pr_debug(DRV_PFX "discard op failed, not supported\n"); status = BLKIF_RSP_EOPNOTSUPP; } else if (err) status = BLKIF_RSP_ERROR; make_response(blkif, req->u.discard.id, req->operation, status); xen_blkif_put(blkif); return err; } Commit Message: xen/blkback: Check device permissions before allowing OP_DISCARD We need to make sure that the device is not RO or that the request is not past the number of sectors we want to issue the DISCARD operation for. This fixes CVE-2013-2140. Cc: stable@vger.kernel.org Acked-by: Jan Beulich <JBeulich@suse.com> Acked-by: Ian Campbell <Ian.Campbell@citrix.com> [v1: Made it pr_warn instead of pr_debug] Signed-off-by: Konrad Rzeszutek Wilk <konrad.wilk@oracle.com> CWE ID: CWE-20
static int dispatch_discard_io(struct xen_blkif *blkif, struct blkif_request *req) { int err = 0; int status = BLKIF_RSP_OKAY; struct block_device *bdev = blkif->vbd.bdev; unsigned long secure; struct phys_req preq; preq.sector_number = req->u.discard.sector_number; preq.nr_sects = req->u.discard.nr_sectors; err = xen_vbd_translate(&preq, blkif, WRITE); if (err) { pr_warn(DRV_PFX "access denied: DISCARD [%llu->%llu] on dev=%04x\n", preq.sector_number, preq.sector_number + preq.nr_sects, blkif->vbd.pdevice); goto fail_response; } blkif->st_ds_req++; xen_blkif_get(blkif); secure = (blkif->vbd.discard_secure && (req->u.discard.flag & BLKIF_DISCARD_SECURE)) ? BLKDEV_DISCARD_SECURE : 0; err = blkdev_issue_discard(bdev, req->u.discard.sector_number, req->u.discard.nr_sectors, GFP_KERNEL, secure); fail_response: if (err == -EOPNOTSUPP) { pr_debug(DRV_PFX "discard op failed, not supported\n"); status = BLKIF_RSP_EOPNOTSUPP; } else if (err) status = BLKIF_RSP_ERROR; make_response(blkif, req->u.discard.id, req->operation, status); xen_blkif_put(blkif); return err; }
166,083
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static bool CheckDts(const uint8_t* buffer, int buffer_size) { RCHECK(buffer_size > 11); int offset = 0; while (offset + 11 < buffer_size) { BitReader reader(buffer + offset, 11); RCHECK(ReadBits(&reader, 32) == 0x7ffe8001); reader.SkipBits(1 + 5); RCHECK(ReadBits(&reader, 1) == 0); // CPF must be 0. RCHECK(ReadBits(&reader, 7) >= 5); int frame_size = ReadBits(&reader, 14); RCHECK(frame_size >= 95); reader.SkipBits(6); RCHECK(kSamplingFrequencyValid[ReadBits(&reader, 4)]); RCHECK(ReadBits(&reader, 5) <= 25); RCHECK(ReadBits(&reader, 1) == 0); reader.SkipBits(1 + 1 + 1 + 1); RCHECK(kExtAudioIdValid[ReadBits(&reader, 3)]); reader.SkipBits(1 + 1); RCHECK(ReadBits(&reader, 2) != 3); offset += frame_size + 1; } return true; } Commit Message: Cleanup media BitReader ReadBits() calls Initialize temporary values, check return values. Small tweaks to solution proposed by adtolbar@microsoft.com. Bug: 929962 Change-Id: Iaa7da7534174882d040ec7e4c353ba5cd0da5735 Reviewed-on: https://chromium-review.googlesource.com/c/1481085 Commit-Queue: Chrome Cunningham <chcunningham@chromium.org> Reviewed-by: Dan Sanders <sandersd@chromium.org> Cr-Commit-Position: refs/heads/master@{#634889} CWE ID: CWE-200
static bool CheckDts(const uint8_t* buffer, int buffer_size) { RCHECK(buffer_size > 11); int offset = 0; while (offset + 11 < buffer_size) { BitReader reader(buffer + offset, 11); RCHECK(ReadBits(&reader, 32) == 0x7ffe8001); reader.SkipBits(1 + 5); RCHECK(ReadBits(&reader, 1) == 0); // CPF must be 0. RCHECK(ReadBits(&reader, 7) >= 5); int frame_size = ReadBits(&reader, 14); RCHECK(frame_size >= 95); reader.SkipBits(6); size_t sampling_freq_index = ReadBits(&reader, 4); RCHECK(sampling_freq_index < base::size(kSamplingFrequencyValid)); RCHECK(kSamplingFrequencyValid[sampling_freq_index]); RCHECK(ReadBits(&reader, 5) <= 25); RCHECK(ReadBits(&reader, 1) == 0); reader.SkipBits(1 + 1 + 1 + 1); size_t audio_id_index = ReadBits(&reader, 3); RCHECK(audio_id_index < base::size(kExtAudioIdValid)); RCHECK(kExtAudioIdValid[audio_id_index]); reader.SkipBits(1 + 1); RCHECK(ReadBits(&reader, 2) != 3); offset += frame_size + 1; } return true; }
173,018
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 spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */ { zval tmp; intern->type = SPL_FS_FILE; php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, &tmp TSRMLS_CC); if (Z_LVAL(tmp)) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Cannot use SplFileObject with directories"); return FAILURE; } intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0); intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context); if (!intern->file_name_len || !intern->u.file.stream) { if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : ""); } intern->file_name = NULL; /* until here it is not a copy */ intern->u.file.open_mode = NULL; return FAILURE; } if (intern->u.file.zcontext) { zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext)); } if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) { intern->file_name_len--; } intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path)); intern->file_name = estrndup(intern->file_name, intern->file_name_len); intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len); /* avoid reference counting in debug mode, thus do it manually */ ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); Z_SET_REFCOUNT(intern->u.file.zresource, 1); intern->u.file.delimiter = ','; intern->u.file.enclosure = '"'; intern->u.file.escape = '\\'; zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr); return SUCCESS; } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */ { zval tmp; intern->type = SPL_FS_FILE; php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, &tmp TSRMLS_CC); if (Z_LVAL(tmp)) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Cannot use SplFileObject with directories"); return FAILURE; } intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0); intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context); if (!intern->file_name_len || !intern->u.file.stream) { if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : ""); } intern->file_name = NULL; /* until here it is not a copy */ intern->u.file.open_mode = NULL; return FAILURE; } if (intern->u.file.zcontext) { zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext)); } if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) { intern->file_name_len--; } intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path)); intern->file_name = estrndup(intern->file_name, intern->file_name_len); intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len); /* avoid reference counting in debug mode, thus do it manually */ ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); Z_SET_REFCOUNT(intern->u.file.zresource, 1); intern->u.file.delimiter = ','; intern->u.file.enclosure = '"'; intern->u.file.escape = '\\'; zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr); return SUCCESS; } /* }}} */
167,075
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: gfx::Vector2d LayerTreeHost::DistributeScrollOffsetToViewports( const gfx::Vector2d offset, Layer* layer) { DCHECK(layer); if (layer != outer_viewport_scroll_layer_.get()) return offset; gfx::Vector2d inner_viewport_offset = inner_viewport_scroll_layer_->scroll_offset(); gfx::Vector2d outer_viewport_offset = outer_viewport_scroll_layer_->scroll_offset(); if (offset == inner_viewport_offset + outer_viewport_offset) { return outer_viewport_offset; } gfx::Vector2d max_outer_viewport_scroll_offset = outer_viewport_scroll_layer_->MaxScrollOffset(); gfx::Vector2d max_inner_viewport_scroll_offset = inner_viewport_scroll_layer_->MaxScrollOffset(); outer_viewport_offset = offset - inner_viewport_offset; outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset); outer_viewport_offset.SetToMax(gfx::Vector2d()); inner_viewport_offset = offset - outer_viewport_offset; inner_viewport_offset.SetToMin(max_inner_viewport_scroll_offset); inner_viewport_offset.SetToMax(gfx::Vector2d()); inner_viewport_scroll_layer_->SetScrollOffset(inner_viewport_offset); return outer_viewport_offset; } Commit Message: Removed pinch viewport scroll offset distribution The associated change in Blink makes the pinch viewport a proper ScrollableArea meaning the normal path for synchronizing layer scroll offsets is used. This is a 2 sided patch, the other CL: https://codereview.chromium.org/199253002/ BUG=349941 Review URL: https://codereview.chromium.org/210543002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
gfx::Vector2d LayerTreeHost::DistributeScrollOffsetToViewports(
171,199
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 cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s, false)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; } Commit Message: CWE ID: CWE-125
static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin, int off_pitch, int bytesperline, int lines) { int y; int off_cur; int off_cur_end; if (off_pitch < 0) { off_begin -= bytesperline - 1; } for (y = 0; y < lines; y++) { off_cur = off_begin; off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask; assert(off_cur_end >= off_cur); memory_region_set_dirty(&s->vga.vram, off_cur, off_cur_end - off_cur); off_begin += off_pitch; } uint8_t *dst; dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask); if (blit_is_unsafe(s, false)) return 0; (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; }
165,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigatorImpl::DidNavigate( RenderFrameHostImpl* render_frame_host, const FrameHostMsg_DidCommitProvisionalLoad_Params& params, std::unique_ptr<NavigationHandleImpl> navigation_handle) { FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree(); bool oopifs_possible = SiteIsolationPolicy::AreCrossProcessFramesPossible(); bool is_navigation_within_page = controller_->IsURLInPageNavigation( params.url, params.origin, params.was_within_same_document, render_frame_host); if (is_navigation_within_page && render_frame_host != render_frame_host->frame_tree_node() ->render_manager() ->current_frame_host()) { bad_message::ReceivedBadMessage(render_frame_host->GetProcess(), bad_message::NI_IN_PAGE_NAVIGATION); is_navigation_within_page = false; } if (ui::PageTransitionIsMainFrame(params.transition)) { if (delegate_) { if (delegate_->CanOverscrollContent()) { if (!params.was_within_same_document) controller_->TakeScreenshot(); } delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page); } if (!oopifs_possible) frame_tree->root()->render_manager()->DidNavigateFrame( render_frame_host, params.gesture == NavigationGestureUser); } render_frame_host->frame_tree_node()->SetCurrentOrigin( params.origin, params.has_potentially_trustworthy_unique_origin); render_frame_host->frame_tree_node()->SetInsecureRequestPolicy( params.insecure_request_policy); if (!is_navigation_within_page) { render_frame_host->ResetContentSecurityPolicies(); render_frame_host->frame_tree_node()->ResetCspHeaders(); render_frame_host->frame_tree_node()->ResetFeaturePolicyHeader(); } if (oopifs_possible) { FrameTreeNode* frame = render_frame_host->frame_tree_node(); frame->render_manager()->DidNavigateFrame( render_frame_host, params.gesture == NavigationGestureUser); } SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance(); if (!site_instance->HasSite() && ShouldAssignSiteForURL(params.url) && !params.url_is_unreachable) { site_instance->SetSite(params.url); } if (ui::PageTransitionIsMainFrame(params.transition) && delegate_) delegate_->SetMainFrameMimeType(params.contents_mime_type); int old_entry_count = controller_->GetEntryCount(); LoadCommittedDetails details; bool did_navigate = controller_->RendererDidNavigate( render_frame_host, params, &details, is_navigation_within_page, navigation_handle.get()); if (old_entry_count != controller_->GetEntryCount() || details.previous_entry_index != controller_->GetLastCommittedEntryIndex()) { frame_tree->root()->render_manager()->SendPageMessage( new PageMsg_SetHistoryOffsetAndLength( MSG_ROUTING_NONE, controller_->GetLastCommittedEntryIndex(), controller_->GetEntryCount()), site_instance); } render_frame_host->frame_tree_node()->SetCurrentURL(params.url); render_frame_host->SetLastCommittedOrigin(params.origin); if (!params.url_is_unreachable) render_frame_host->set_last_successful_url(params.url); if (did_navigate && !is_navigation_within_page) render_frame_host->ResetFeaturePolicy(); if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) { DCHECK_EQ(!render_frame_host->GetParent(), did_navigate ? details.is_main_frame : false); navigation_handle->DidCommitNavigation(params, did_navigate, details.did_replace_entry, details.previous_url, details.type, render_frame_host); navigation_handle.reset(); } if (!did_navigate) return; // No navigation happened. RecordNavigationMetrics(details, params, site_instance); if (delegate_) { if (details.is_main_frame) { delegate_->DidNavigateMainFramePostCommit(render_frame_host, details, params); } delegate_->DidNavigateAnyFramePostCommit( render_frame_host, details, params); } } Commit Message: Correctly reset FP in RFHI whenever origin changes Bug: 713364 Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f Reviewed-on: https://chromium-review.googlesource.com/482380 Commit-Queue: Ian Clelland <iclelland@chromium.org> Reviewed-by: Charles Reis <creis@chromium.org> Cr-Commit-Position: refs/heads/master@{#466778} CWE ID: CWE-254
void NavigatorImpl::DidNavigate( RenderFrameHostImpl* render_frame_host, const FrameHostMsg_DidCommitProvisionalLoad_Params& params, std::unique_ptr<NavigationHandleImpl> navigation_handle) { FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree(); bool oopifs_possible = SiteIsolationPolicy::AreCrossProcessFramesPossible(); bool is_navigation_within_page = controller_->IsURLInPageNavigation( params.url, params.origin, params.was_within_same_document, render_frame_host); if (is_navigation_within_page && render_frame_host != render_frame_host->frame_tree_node() ->render_manager() ->current_frame_host()) { bad_message::ReceivedBadMessage(render_frame_host->GetProcess(), bad_message::NI_IN_PAGE_NAVIGATION); is_navigation_within_page = false; } if (ui::PageTransitionIsMainFrame(params.transition)) { if (delegate_) { if (delegate_->CanOverscrollContent()) { if (!params.was_within_same_document) controller_->TakeScreenshot(); } delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page); } if (!oopifs_possible) frame_tree->root()->render_manager()->DidNavigateFrame( render_frame_host, params.gesture == NavigationGestureUser); } render_frame_host->frame_tree_node()->SetCurrentOrigin( params.origin, params.has_potentially_trustworthy_unique_origin); render_frame_host->frame_tree_node()->SetInsecureRequestPolicy( params.insecure_request_policy); if (!is_navigation_within_page) { render_frame_host->ResetContentSecurityPolicies(); render_frame_host->frame_tree_node()->ResetCspHeaders(); render_frame_host->frame_tree_node()->ResetFeaturePolicyHeader(); } if (oopifs_possible) { FrameTreeNode* frame = render_frame_host->frame_tree_node(); frame->render_manager()->DidNavigateFrame( render_frame_host, params.gesture == NavigationGestureUser); } SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance(); if (!site_instance->HasSite() && ShouldAssignSiteForURL(params.url) && !params.url_is_unreachable) { site_instance->SetSite(params.url); } if (ui::PageTransitionIsMainFrame(params.transition) && delegate_) delegate_->SetMainFrameMimeType(params.contents_mime_type); int old_entry_count = controller_->GetEntryCount(); LoadCommittedDetails details; bool did_navigate = controller_->RendererDidNavigate( render_frame_host, params, &details, is_navigation_within_page, navigation_handle.get()); if (old_entry_count != controller_->GetEntryCount() || details.previous_entry_index != controller_->GetLastCommittedEntryIndex()) { frame_tree->root()->render_manager()->SendPageMessage( new PageMsg_SetHistoryOffsetAndLength( MSG_ROUTING_NONE, controller_->GetLastCommittedEntryIndex(), controller_->GetEntryCount()), site_instance); } render_frame_host->frame_tree_node()->SetCurrentURL(params.url); render_frame_host->SetLastCommittedOrigin(params.origin); if (!params.url_is_unreachable) render_frame_host->set_last_successful_url(params.url); if (!is_navigation_within_page) render_frame_host->ResetFeaturePolicy(); if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) { DCHECK_EQ(!render_frame_host->GetParent(), did_navigate ? details.is_main_frame : false); navigation_handle->DidCommitNavigation(params, did_navigate, details.did_replace_entry, details.previous_url, details.type, render_frame_host); navigation_handle.reset(); } if (!did_navigate) return; // No navigation happened. RecordNavigationMetrics(details, params, site_instance); if (delegate_) { if (details.is_main_frame) { delegate_->DidNavigateMainFramePostCommit(render_frame_host, details, params); } delegate_->DidNavigateAnyFramePostCommit( render_frame_host, details, params); } }
171,963
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: xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; zend_bool old_allow_url_fopen; /* xmlInitParser(); */ old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; ctxt = xmlCreateFileParserCtxt(filename); PG(allow_url_fopen) = old_allow_url_fopen; if (ctxt) { ctxt->keepBlanks = 0; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; /*ctxt->sax->fatalError = NULL;*/ xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; } Commit Message: CWE ID: CWE-200
xmlDocPtr soap_xmlParseFile(const char *filename TSRMLS_DC) { xmlParserCtxtPtr ctxt = NULL; xmlDocPtr ret; zend_bool old_allow_url_fopen; /* xmlInitParser(); */ old_allow_url_fopen = PG(allow_url_fopen); PG(allow_url_fopen) = 1; ctxt = xmlCreateFileParserCtxt(filename); PG(allow_url_fopen) = old_allow_url_fopen; if (ctxt) { ctxt->keepBlanks = 0; ctxt->options -= XML_PARSE_DTDLOAD; ctxt->sax->ignorableWhitespace = soap_ignorableWhitespace; ctxt->sax->comment = soap_Comment; ctxt->sax->warning = NULL; /*ctxt->sax->fatalError = NULL;*/ xmlParseDocument(ctxt); if (ctxt->wellFormed) { ret = ctxt->myDoc; if (ret->URL == NULL && ctxt->directory != NULL) { ret->URL = xmlCharStrdup(ctxt->directory); } } else { ret = NULL; xmlFreeDoc(ctxt->myDoc); ctxt->myDoc = NULL; } xmlFreeParserCtxt(ctxt); } else { ret = NULL; } /* xmlCleanupParser(); */ if (ret) { cleanup_xml_node((xmlNodePtr)ret); } return ret; }
164,727
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. 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: nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ static char temp[NFSX_V3FHMAX+1]; /* Make sure string is null-terminated */ strncpy(temp, sfsname, NFSX_V3FHMAX); temp[sizeof(temp) - 1] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); } Commit Message: CVE-2017-13001/NFS: Don't copy more data than is in the file handle. Also, put the buffer on the stack; no reason to make it static. (65 bytes isn't a lot.) This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
nfs_printfh(netdissect_options *ndo, register const uint32_t *dp, const u_int len) { my_fsid fsid; uint32_t ino; const char *sfsname = NULL; char *spacep; if (ndo->ndo_uflag) { u_int i; char const *sep = ""; ND_PRINT((ndo, " fh[")); for (i=0; i<len; i++) { ND_PRINT((ndo, "%s%x", sep, dp[i])); sep = ":"; } ND_PRINT((ndo, "]")); return; } Parse_fh((const u_char *)dp, len, &fsid, &ino, NULL, &sfsname, 0); if (sfsname) { /* file system ID is ASCII, not numeric, for this server OS */ char temp[NFSX_V3FHMAX+1]; u_int stringlen; /* Make sure string is null-terminated */ stringlen = len; if (stringlen > NFSX_V3FHMAX) stringlen = NFSX_V3FHMAX; strncpy(temp, sfsname, stringlen); temp[stringlen] = '\0'; /* Remove trailing spaces */ spacep = strchr(temp, ' '); if (spacep) *spacep = '\0'; ND_PRINT((ndo, " fh %s/", temp)); } else { ND_PRINT((ndo, " fh %d,%d/", fsid.Fsid_dev.Major, fsid.Fsid_dev.Minor)); } if(fsid.Fsid_dev.Minor == 257) /* Print the undecoded handle */ ND_PRINT((ndo, "%s", fsid.Opaque_Handle)); else ND_PRINT((ndo, "%ld", (long) ino)); }
167,906
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host) : host_(RenderWidgetHostImpl::From(host)), ALLOW_THIS_IN_INITIALIZER_LIST(window_(new aura::Window(this))), in_shutdown_(false), is_fullscreen_(false), popup_parent_host_view_(NULL), popup_child_host_view_(NULL), is_loading_(false), text_input_type_(ui::TEXT_INPUT_TYPE_NONE), can_compose_inline_(true), has_composition_text_(false), device_scale_factor_(1.0f), current_surface_(0), current_surface_is_protected_(true), current_surface_in_use_by_compositor_(true), protection_state_id_(0), surface_route_id_(0), paint_canvas_(NULL), synthetic_move_sent_(false), accelerated_compositing_state_changed_(false), can_lock_compositor_(YES) { host_->SetView(this); window_observer_.reset(new WindowObserver(this)); window_->AddObserver(window_observer_.get()); aura::client::SetTooltipText(window_, &tooltip_); aura::client::SetActivationDelegate(window_, this); gfx::Screen::GetScreenFor(window_)->AddObserver(this); } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
RenderWidgetHostViewAura::RenderWidgetHostViewAura(RenderWidgetHost* host) : host_(RenderWidgetHostImpl::From(host)), ALLOW_THIS_IN_INITIALIZER_LIST(window_(new aura::Window(this))), in_shutdown_(false), is_fullscreen_(false), popup_parent_host_view_(NULL), popup_child_host_view_(NULL), is_loading_(false), text_input_type_(ui::TEXT_INPUT_TYPE_NONE), can_compose_inline_(true), has_composition_text_(false), device_scale_factor_(1.0f), current_surface_(0), paint_canvas_(NULL), synthetic_move_sent_(false), accelerated_compositing_state_changed_(false), can_lock_compositor_(YES) { host_->SetView(this); window_observer_.reset(new WindowObserver(this)); window_->AddObserver(window_observer_.get()); aura::client::SetTooltipText(window_, &tooltip_); aura::client::SetActivationDelegate(window_, this); gfx::Screen::GetScreenFor(window_)->AddObserver(this); }
171,383
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 WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_I32 *pMixBuffer; EAS_PCM *pInputBuffer; EAS_I32 gain; EAS_I32 gainIncrement; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 tmp2; EAS_I32 numSamples; #if (NUM_OUTPUT_CHANNELS == 2) EAS_I32 gainLeft, gainRight; #endif /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); return; } pMixBuffer = pWTIntFrame->pMixBuffer; pInputBuffer = pWTIntFrame->pAudioBuffer; /*lint -e{703} <avoid multiply for performance>*/ gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS); if (gainIncrement < 0) gainIncrement++; /*lint -e{703} <avoid multiply for performance>*/ gain = pWTIntFrame->prevGain << 16; #if (NUM_OUTPUT_CHANNELS == 2) gainLeft = pWTVoice->gainLeft; gainRight = pWTVoice->gainRight; #endif while (numSamples--) { /* incremental gain step to prevent zipper noise */ tmp0 = *pInputBuffer++; gain += gainIncrement; /*lint -e{704} <avoid divide>*/ tmp2 = gain >> 16; /* scale sample by gain */ tmp2 *= tmp0; /* stereo output */ #if (NUM_OUTPUT_CHANNELS == 2) /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> 14; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* left channel */ tmp0 = tmp2 * gainLeft; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* right channel */ tmp0 = tmp2 * gainRight; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* mono output */ #else /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1); tmp1 += tmp2; *pMixBuffer++ = tmp1; #endif } } Commit Message: Sonivox: add SafetyNet log. Bug: 26366256 Change-Id: Ief72e01b7cc6d87a015105af847a99d3d9b03cb0 CWE ID: CWE-119
void WT_VoiceGain (S_WT_VOICE *pWTVoice, S_WT_INT_FRAME *pWTIntFrame) { EAS_I32 *pMixBuffer; EAS_PCM *pInputBuffer; EAS_I32 gain; EAS_I32 gainIncrement; EAS_I32 tmp0; EAS_I32 tmp1; EAS_I32 tmp2; EAS_I32 numSamples; #if (NUM_OUTPUT_CHANNELS == 2) EAS_I32 gainLeft, gainRight; #endif /* initialize some local variables */ numSamples = pWTIntFrame->numSamples; if (numSamples <= 0) { ALOGE("b/26366256"); android_errorWriteLog(0x534e4554, "26366256"); return; } pMixBuffer = pWTIntFrame->pMixBuffer; pInputBuffer = pWTIntFrame->pAudioBuffer; /*lint -e{703} <avoid multiply for performance>*/ gainIncrement = (pWTIntFrame->frame.gainTarget - pWTIntFrame->prevGain) << (16 - SYNTH_UPDATE_PERIOD_IN_BITS); if (gainIncrement < 0) gainIncrement++; /*lint -e{703} <avoid multiply for performance>*/ gain = pWTIntFrame->prevGain << 16; #if (NUM_OUTPUT_CHANNELS == 2) gainLeft = pWTVoice->gainLeft; gainRight = pWTVoice->gainRight; #endif while (numSamples--) { /* incremental gain step to prevent zipper noise */ tmp0 = *pInputBuffer++; gain += gainIncrement; /*lint -e{704} <avoid divide>*/ tmp2 = gain >> 16; /* scale sample by gain */ tmp2 *= tmp0; /* stereo output */ #if (NUM_OUTPUT_CHANNELS == 2) /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> 14; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* left channel */ tmp0 = tmp2 * gainLeft; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /* right channel */ tmp0 = tmp2 * gainRight; /*lint -e{704} <avoid divide>*/ tmp0 = tmp0 >> NUM_MIXER_GUARD_BITS; tmp1 += tmp0; *pMixBuffer++ = tmp1; /* mono output */ #else /* get the current sample in the final mix buffer */ tmp1 = *pMixBuffer; /*lint -e{704} <avoid divide>*/ tmp2 = tmp2 >> (NUM_MIXER_GUARD_BITS - 1); tmp1 += tmp2; *pMixBuffer++ = tmp1; #endif } }
174,606
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 HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->Method() == FormSubmission::kPostMethod || submission->Method() == FormSubmission::kGetMethod); DCHECK(submission->Data()); DCHECK(submission->Form()); if (submission->Action().IsEmpty()) return; if (GetDocument().IsSandboxed(kSandboxForms)) { GetDocument().AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Blocked form submission to '" + submission->Action().ElidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!GetDocument().GetContentSecurityPolicy()->AllowFormAction( submission->Action())) { return; } if (submission->Action().ProtocolIsJavaScript()) { GetDocument() .GetFrame() ->GetScriptController() .ExecuteScriptIfJavaScriptURL(submission->Action(), this); return; } Frame* target_frame = GetDocument().GetFrame()->FindFrameForNavigation( submission->Target(), *GetDocument().GetFrame(), submission->RequestURL()); if (!target_frame) { target_frame = GetDocument().GetFrame(); } else { submission->ClearTarget(); } if (!target_frame->GetPage()) return; UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), WebFeature::kMixedContentFormsSubmitted); } if (target_frame->IsLocalFrame()) { ToLocalFrame(target_frame) ->GetNavigationScheduler() .ScheduleFormSubmission(&GetDocument(), submission); } else { FrameLoadRequest frame_load_request = submission->CreateFrameLoadRequest(&GetDocument()); ToRemoteFrame(target_frame)->Navigate(frame_load_request); } } Commit Message: Move user activation check to RemoteFrame::Navigate's callers. Currently RemoteFrame::Navigate is the user of Frame::HasTransientUserActivation that passes a RemoteFrame*, and it seems wrong because the user activation (user gesture) needed by the navigation should belong to the LocalFrame that initiated the navigation. Follow-up CLs after this one will update UserActivation code in Frame to take a LocalFrame* instead of a Frame*, and get rid of redundant IPCs. Bug: 811414 Change-Id: I771c1694043edb54374a44213d16715d9c7da704 Reviewed-on: https://chromium-review.googlesource.com/914736 Commit-Queue: Mustaq Ahmed <mustaq@chromium.org> Reviewed-by: Daniel Cheng <dcheng@chromium.org> Cr-Commit-Position: refs/heads/master@{#536728} CWE ID: CWE-190
void HTMLFormElement::ScheduleFormSubmission(FormSubmission* submission) { DCHECK(submission->Method() == FormSubmission::kPostMethod || submission->Method() == FormSubmission::kGetMethod); DCHECK(submission->Data()); DCHECK(submission->Form()); if (submission->Action().IsEmpty()) return; if (GetDocument().IsSandboxed(kSandboxForms)) { GetDocument().AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Blocked form submission to '" + submission->Action().ElidedString() + "' because the form's frame is sandboxed and the 'allow-forms' " "permission is not set.")); return; } if (!GetDocument().GetContentSecurityPolicy()->AllowFormAction( submission->Action())) { return; } if (submission->Action().ProtocolIsJavaScript()) { GetDocument() .GetFrame() ->GetScriptController() .ExecuteScriptIfJavaScriptURL(submission->Action(), this); return; } Frame* target_frame = GetDocument().GetFrame()->FindFrameForNavigation( submission->Target(), *GetDocument().GetFrame(), submission->RequestURL()); if (!target_frame) { target_frame = GetDocument().GetFrame(); } else { submission->ClearTarget(); } if (!target_frame->GetPage()) return; UseCounter::Count(GetDocument(), WebFeature::kFormsSubmitted); if (MixedContentChecker::IsMixedFormAction(GetDocument().GetFrame(), submission->Action())) { UseCounter::Count(GetDocument().GetFrame(), WebFeature::kMixedContentFormsSubmitted); } if (target_frame->IsLocalFrame()) { ToLocalFrame(target_frame) ->GetNavigationScheduler() .ScheduleFormSubmission(&GetDocument(), submission); } else { FrameLoadRequest frame_load_request = submission->CreateFrameLoadRequest(&GetDocument()); frame_load_request.GetResourceRequest().SetHasUserGesture( Frame::HasTransientUserActivation(GetDocument().GetFrame())); ToRemoteFrame(target_frame)->Navigate(frame_load_request); } }
173,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 struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs4_opendata *opendata; opendata = nfs4_opendata_alloc(&ctx->path, state->owner, 0, NULL); if (opendata == NULL) return ERR_PTR(-ENOMEM); opendata->state = state; atomic_inc(&state->count); return opendata; } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static struct nfs4_opendata *nfs4_open_recoverdata_alloc(struct nfs_open_context *ctx, struct nfs4_state *state) { struct nfs4_opendata *opendata; opendata = nfs4_opendata_alloc(&ctx->path, state->owner, 0, 0, NULL); if (opendata == NULL) return ERR_PTR(-ENOMEM); opendata->state = state; atomic_inc(&state->count); return opendata; }
165,697
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 FrameSelection::SelectAll(SetSelectionBy set_selection_by) { if (isHTMLSelectElement(GetDocument().FocusedElement())) { HTMLSelectElement* select_element = toHTMLSelectElement(GetDocument().FocusedElement()); if (select_element->CanSelectAll()) { select_element->SelectAll(); return; } } Node* root = nullptr; Node* select_start_target = nullptr; if (set_selection_by == SetSelectionBy::kUser && IsHidden()) { root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } else if (ComputeVisibleSelectionInDOMTree().IsContentEditable()) { root = HighestEditableRoot(ComputeVisibleSelectionInDOMTree().Start()); if (Node* shadow_root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start())) select_start_target = shadow_root->OwnerShadowHost(); else select_start_target = root; } else { root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start()); if (root) { select_start_target = root->OwnerShadowHost(); } else { root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } } if (!root || EditingIgnoresContent(*root)) return; if (select_start_target) { const Document& expected_document = GetDocument(); if (select_start_target->DispatchEvent(Event::CreateCancelableBubble( EventTypeNames::selectstart)) != DispatchEventResult::kNotCanceled) return; if (!IsAvailable()) { return; } if (!root->isConnected() || expected_document != root->GetDocument()) return; } SetSelection(SelectionInDOMTree::Builder() .SelectAllChildren(*root) .SetIsHandleVisible(IsHandleVisible()) .Build()); SelectFrameElementInParentIfFullySelected(); NotifyTextControlOfSelectionChange(SetSelectionBy::kUser); if (IsHandleVisible()) { ContextMenuAllowedScope scope; frame_->GetEventHandler().ShowNonLocatedContextMenu(nullptr, kMenuSourceTouch); } } 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
void FrameSelection::SelectAll(SetSelectionBy set_selection_by) { if (isHTMLSelectElement(GetDocument().FocusedElement())) { HTMLSelectElement* select_element = toHTMLSelectElement(GetDocument().FocusedElement()); if (select_element->CanSelectAll()) { select_element->SelectAll(); return; } } Node* root = nullptr; Node* select_start_target = nullptr; if (set_selection_by == SetSelectionBy::kUser && IsHidden()) { root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } else if (ComputeVisibleSelectionInDOMTree().IsContentEditable()) { root = HighestEditableRoot(ComputeVisibleSelectionInDOMTree().Start()); if (Node* shadow_root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start())) select_start_target = shadow_root->OwnerShadowHost(); else select_start_target = root; } else { root = NonBoundaryShadowTreeRootNode( ComputeVisibleSelectionInDOMTree().Start()); if (root) { select_start_target = root->OwnerShadowHost(); } else { root = GetDocument().documentElement(); select_start_target = GetDocument().body(); } } if (!root || EditingIgnoresContent(*root)) return; if (select_start_target) { const Document& expected_document = GetDocument(); if (select_start_target->DispatchEvent(Event::CreateCancelableBubble( EventTypeNames::selectstart)) != DispatchEventResult::kNotCanceled) return; if (!IsAvailable()) { return; } if (!root->isConnected() || expected_document != root->GetDocument()) return; } SetSelection(SelectionInDOMTree::Builder().SelectAllChildren(*root).Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetShouldShowHandle(IsHandleVisible()) .Build()); SelectFrameElementInParentIfFullySelected(); NotifyTextControlOfSelectionChange(SetSelectionBy::kUser); if (IsHandleVisible()) { ContextMenuAllowedScope scope; frame_->GetEventHandler().ShowNonLocatedContextMenu(nullptr, kMenuSourceTouch); } }
171,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: int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight) { uch sig[8]; /* first do a quick check that the file really is a PNG image; could * have used slightly more general png_sig_cmp() function instead */ fread(sig, 1, 8, infile); if (png_sig_cmp(sig, 0, 8)) return 1; /* bad signature */ /* could pass pointers to user-defined error handlers instead of NULLs: */ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } png_init_io(png_ptr, infile); png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */ png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); *pWidth = width; *pHeight = height; /* OK, that's all we need for now; return happy */ return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
int readpng_init(FILE *infile, ulg *pWidth, ulg *pHeight) { uch sig[8]; /* first do a quick check that the file really is a PNG image; could * have used slightly more general png_sig_cmp() function instead */ fread(sig, 1, 8, infile); if (png_sig_cmp(sig, 0, 8)) return 1; /* bad signature */ /* could pass pointers to user-defined error handlers instead of NULLs: */ png_ptr = png_create_read_struct(png_get_libpng_ver(NULL), NULL, NULL, NULL); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function */ if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } png_init_io(png_ptr, infile); png_set_sig_bytes(png_ptr, 8); /* we already read the 8 signature bytes */ png_read_info(png_ptr, info_ptr); /* read all PNG info up to image data */ /* alternatively, could make separate calls to png_get_image_width(), * etc., but want bit_depth and color_type for later [don't care about * compression_type and filter_type => NULLs] */ png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, NULL, NULL, NULL); *pWidth = width; *pHeight = height; /* OK, that's all we need for now; return happy */ return 0; }
173,567
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int bmp_getint32(jas_stream_t *in, int_fast32_t *val) { int n; uint_fast32_t v; int c; for (n = 4, v = 0;;) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } v |= (c << 24); if (--n <= 0) { break; } v >>= 8; } if (val) { *val = v; } return 0; } Commit Message: Fixed a sanitizer failure in the BMP codec. Also, added a --debug-level command line option to the imginfo command for debugging purposes. CWE ID: CWE-476
static int bmp_getint32(jas_stream_t *in, int_fast32_t *val) { int n; uint_fast32_t v; int c; for (n = 4, v = 0;;) { if ((c = jas_stream_getc(in)) == EOF) { return -1; } v |= (JAS_CAST(uint_fast32_t, c) << 24); if (--n <= 0) { break; } v >>= 8; } if (val) { *val = v; } return 0; }
168,763
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: RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation( const NavigationRequest& request) { DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme)) << "Don't call this method for JavaScript URLs as those create a " "temporary NavigationRequest and we don't want to reset an ongoing " "navigation's speculative RFH."; RenderFrameHostImpl* navigation_rfh = nullptr; SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigationRequest(request); bool use_current_rfh = current_site_instance == dest_site_instance; bool notify_webui_of_rf_creation = false; if (use_current_rfh) { if (speculative_render_frame_host_) { if (speculative_render_frame_host_->navigation_handle()) { frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded( speculative_render_frame_host_->navigation_handle() ->pending_nav_entry_id()); } DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost()); } if (frame_tree_node_->IsMainFrame()) { UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url, request.bindings()); } navigation_rfh = render_frame_host_.get(); DCHECK(!speculative_render_frame_host_); } else { if (!speculative_render_frame_host_ || speculative_render_frame_host_->GetSiteInstance() != dest_site_instance.get()) { CleanUpNavigation(); bool success = CreateSpeculativeRenderFrameHost(current_site_instance, dest_site_instance.get()); DCHECK(success); } DCHECK(speculative_render_frame_host_); if (frame_tree_node_->IsMainFrame()) { bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI( request.common_params().url, request.bindings()); speculative_render_frame_host_->CommitPendingWebUI(); DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui()); notify_webui_of_rf_creation = changed_web_ui && speculative_render_frame_host_->web_ui(); } navigation_rfh = speculative_render_frame_host_.get(); if (!render_frame_host_->IsRenderFrameLive()) { if (GetRenderFrameProxyHost(dest_site_instance.get())) { navigation_rfh->Send( new FrameMsg_SwapIn(navigation_rfh->GetRoutingID())); } CommitPending(); if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) { render_frame_host_->web_ui()->RenderFrameCreated( render_frame_host_.get()); notify_webui_of_rf_creation = false; } } } DCHECK(navigation_rfh && (navigation_rfh == render_frame_host_.get() || navigation_rfh == speculative_render_frame_host_.get())); if (!navigation_rfh->IsRenderFrameLive()) { if (!ReinitializeRenderFrame(navigation_rfh)) return nullptr; notify_webui_of_rf_creation = true; if (navigation_rfh == render_frame_host_.get()) { EnsureRenderFrameHostVisibilityConsistent(); EnsureRenderFrameHostPageFocusConsistent(); delegate_->NotifyMainFrameSwappedFromRenderManager( nullptr, render_frame_host_->render_view_host()); } } if (notify_webui_of_rf_creation && GetNavigatingWebUI() && frame_tree_node_->IsMainFrame()) { GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh); } return navigation_rfh; } Commit Message: Fix issue with pending NavigationEntry being discarded incorrectly This CL fixes an issue where we would attempt to discard a pending NavigationEntry when a cross-process navigation to this NavigationEntry is interrupted by another navigation to the same NavigationEntry. BUG=760342,797656,796135 Change-Id: I204deff1efd4d572dd2e0b20e492592d48d787d9 Reviewed-on: https://chromium-review.googlesource.com/850877 Reviewed-by: Charlie Reis <creis@chromium.org> Commit-Queue: Camille Lamy <clamy@chromium.org> Cr-Commit-Position: refs/heads/master@{#528611} CWE ID: CWE-20
RenderFrameHostImpl* RenderFrameHostManager::GetFrameHostForNavigation( const NavigationRequest& request) { DCHECK(!request.common_params().url.SchemeIs(url::kJavaScriptScheme)) << "Don't call this method for JavaScript URLs as those create a " "temporary NavigationRequest and we don't want to reset an ongoing " "navigation's speculative RFH."; RenderFrameHostImpl* navigation_rfh = nullptr; SiteInstance* current_site_instance = render_frame_host_->GetSiteInstance(); scoped_refptr<SiteInstance> dest_site_instance = GetSiteInstanceForNavigationRequest(request); bool use_current_rfh = current_site_instance == dest_site_instance; bool notify_webui_of_rf_creation = false; if (use_current_rfh) { if (speculative_render_frame_host_) { // NavigationEntry stopped if needed. This is the case if the new // navigation was started from BeginNavigation. If the navigation was // started through the NavigationController, the NavigationController has // already updated its state properly, and doesn't need to be notified. if (speculative_render_frame_host_->navigation_handle() && request.from_begin_navigation()) { frame_tree_node_->navigator()->DiscardPendingEntryIfNeeded( speculative_render_frame_host_->navigation_handle() ->pending_nav_entry_id()); } DiscardUnusedFrame(UnsetSpeculativeRenderFrameHost()); } if (frame_tree_node_->IsMainFrame()) { UpdatePendingWebUIOnCurrentFrameHost(request.common_params().url, request.bindings()); } navigation_rfh = render_frame_host_.get(); DCHECK(!speculative_render_frame_host_); } else { if (!speculative_render_frame_host_ || speculative_render_frame_host_->GetSiteInstance() != dest_site_instance.get()) { CleanUpNavigation(); bool success = CreateSpeculativeRenderFrameHost(current_site_instance, dest_site_instance.get()); DCHECK(success); } DCHECK(speculative_render_frame_host_); if (frame_tree_node_->IsMainFrame()) { bool changed_web_ui = speculative_render_frame_host_->UpdatePendingWebUI( request.common_params().url, request.bindings()); speculative_render_frame_host_->CommitPendingWebUI(); DCHECK_EQ(GetNavigatingWebUI(), speculative_render_frame_host_->web_ui()); notify_webui_of_rf_creation = changed_web_ui && speculative_render_frame_host_->web_ui(); } navigation_rfh = speculative_render_frame_host_.get(); if (!render_frame_host_->IsRenderFrameLive()) { if (GetRenderFrameProxyHost(dest_site_instance.get())) { navigation_rfh->Send( new FrameMsg_SwapIn(navigation_rfh->GetRoutingID())); } CommitPending(); if (notify_webui_of_rf_creation && render_frame_host_->web_ui()) { render_frame_host_->web_ui()->RenderFrameCreated( render_frame_host_.get()); notify_webui_of_rf_creation = false; } } } DCHECK(navigation_rfh && (navigation_rfh == render_frame_host_.get() || navigation_rfh == speculative_render_frame_host_.get())); if (!navigation_rfh->IsRenderFrameLive()) { if (!ReinitializeRenderFrame(navigation_rfh)) return nullptr; notify_webui_of_rf_creation = true; if (navigation_rfh == render_frame_host_.get()) { EnsureRenderFrameHostVisibilityConsistent(); EnsureRenderFrameHostPageFocusConsistent(); delegate_->NotifyMainFrameSwappedFromRenderManager( nullptr, render_frame_host_->render_view_host()); } } if (notify_webui_of_rf_creation && GetNavigatingWebUI() && frame_tree_node_->IsMainFrame()) { GetNavigatingWebUI()->RenderFrameCreated(navigation_rfh); } return navigation_rfh; }
172,684
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ ) { int rc = 0; gnutls_session *session = gnutls_malloc(sizeof(gnutls_session)); gnutls_init(session, type); # ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT /* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */ gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL); /* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */ # else gnutls_set_default_priority(*session); gnutls_kx_set_priority(*session, tls_kx_order); # endif gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock)); switch (type) { case GNUTLS_SERVER: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_s); break; case GNUTLS_CLIENT: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_c); break; } do { rc = gnutls_handshake(*session); } while (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN); if (rc < 0) { crm_err("Handshake failed: %s", gnutls_strerror(rc)); gnutls_deinit(*session); gnutls_free(session); return NULL; } return session; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ ) void * crm_create_anon_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */, void *credentials) { gnutls_session *session = gnutls_malloc(sizeof(gnutls_session)); gnutls_init(session, type); # ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT /* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */ gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL); /* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */ # else gnutls_set_default_priority(*session); gnutls_kx_set_priority(*session, anon_tls_kx_order); # endif gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock)); switch (type) { case GNUTLS_SERVER: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_server_credentials_t) credentials); break; case GNUTLS_CLIENT: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_client_credentials_t) credentials); break; } return session; }
166,162
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 WorkerProcessLauncher::Core::OnChannelConnected(int32 peer_pid) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); if (ipc_enabled_) worker_delegate_->OnChannelConnected(); } Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process. As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition. BUG=134694 Review URL: https://chromiumcodereview.appspot.com/11143025 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void WorkerProcessLauncher::Core::OnChannelConnected(int32 peer_pid) { DCHECK(caller_task_runner_->BelongsToCurrentThread()); if (!ipc_enabled_) return; // Verify |peer_pid| because it is controlled by the client and cannot be // trusted. DWORD actual_pid = launcher_delegate_->GetProcessId(); if (peer_pid != static_cast<int32>(actual_pid)) { LOG(ERROR) << "The actual client PID " << actual_pid << " does not match the one reported by the client: " << peer_pid; StopWorker(); return; } worker_delegate_->OnChannelConnected(peer_pid); }
171,548
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); } Commit Message: Add bounds validation to AsyncPixelTransfersCompletedQuery::End BUG=351852 R=jbauman@chromium.org, jorgelo@chromium.org Review URL: https://codereview.chromium.org/198253002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@256723 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
bool AsyncPixelTransfersCompletedQuery::End( base::subtle::Atomic32 submit_count) { AsyncMemoryParams mem_params; Buffer buffer = manager()->decoder()->GetSharedMemoryBuffer(shm_id()); if (!buffer.shared_memory) return false; mem_params.shared_memory = buffer.shared_memory; mem_params.shm_size = buffer.size; mem_params.shm_data_offset = shm_offset(); mem_params.shm_data_size = sizeof(QuerySync); uint32 end = mem_params.shm_data_offset + mem_params.shm_data_size; if (end > mem_params.shm_size || end < mem_params.shm_data_offset) return false; observer_ = new AsyncPixelTransferCompletionObserverImpl(submit_count); manager()->decoder()->GetAsyncPixelTransferManager() ->AsyncNotifyCompletion(mem_params, observer_); return AddToPendingTransferQueue(submit_count); }
171,682
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BrowserContextImpl::~BrowserContextImpl() { CHECK(!otr_context_); } Commit Message: CWE ID: CWE-20
BrowserContextImpl::~BrowserContextImpl() {
165,417
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: SortDirection AXTableCell::getSortDirection() const { if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole) return SortDirectionUndefined; const AtomicString& ariaSort = getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort); if (ariaSort.isEmpty()) return SortDirectionUndefined; if (equalIgnoringCase(ariaSort, "none")) return SortDirectionNone; if (equalIgnoringCase(ariaSort, "ascending")) return SortDirectionAscending; if (equalIgnoringCase(ariaSort, "descending")) return SortDirectionDescending; if (equalIgnoringCase(ariaSort, "other")) return SortDirectionOther; return SortDirectionUndefined; } 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
SortDirection AXTableCell::getSortDirection() const { if (roleValue() != RowHeaderRole && roleValue() != ColumnHeaderRole) return SortDirectionUndefined; const AtomicString& ariaSort = getAOMPropertyOrARIAAttribute(AOMStringProperty::kSort); if (ariaSort.isEmpty()) return SortDirectionUndefined; if (equalIgnoringASCIICase(ariaSort, "none")) return SortDirectionNone; if (equalIgnoringASCIICase(ariaSort, "ascending")) return SortDirectionAscending; if (equalIgnoringASCIICase(ariaSort, "descending")) return SortDirectionDescending; if (equalIgnoringASCIICase(ariaSort, "other")) return SortDirectionOther; return SortDirectionUndefined; }
171,931
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 addDataToStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); blobRegistry().addDataToStream(blobRegistryContext->url, blobRegistryContext->streamData); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
static void addDataToStreamTask(void* context) { OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context)); if (WebBlobRegistry* registry = blobRegistry()) { WebThreadSafeData webThreadSafeData(blobRegistryContext->streamData); registry->addDataToStream(blobRegistryContext->url, webThreadSafeData); } }
170,681
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 Sp_search(js_State *J) { js_Regexp *re; const char *text; Resub m; text = checkstring(J, 0); if (js_isregexp(J, 1)) js_copy(J, 1); else if (js_isundefined(J, 1)) js_newregexp(J, "", 0); else js_newregexp(J, js_tostring(J, 1), 0); re = js_toregexp(J, -1); if (!js_regexec(re->prog, text, &m, 0)) js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp)); else js_pushnumber(J, -1); } Commit Message: Bug 700937: Limit recursion in regexp matcher. Also handle negative return code as an error in the JS bindings. CWE ID: CWE-400
static void Sp_search(js_State *J) { js_Regexp *re; const char *text; Resub m; text = checkstring(J, 0); if (js_isregexp(J, 1)) js_copy(J, 1); else if (js_isundefined(J, 1)) js_newregexp(J, "", 0); else js_newregexp(J, js_tostring(J, 1), 0); re = js_toregexp(J, -1); if (!js_doregexec(J, re->prog, text, &m, 0)) js_pushnumber(J, js_utfptrtoidx(text, m.sub[0].sp)); else js_pushnumber(J, -1); }
169,700
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_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion() Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, loadPhar) { char *fname, *alias = NULL, *error; size_t fname_len, alias_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|s!", &fname, &fname_len, &alias, &alias_len) == FAILURE) { return; } phar_request_initialize(); RETVAL_BOOL(phar_open_from_filename(fname, fname_len, alias, alias_len, REPORT_ERRORS, NULL, &error) == SUCCESS); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } } /* }}} */ /* {{{ proto string Phar::apiVersion()
165,058
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 nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags) { write_seqlock(&state->seqlock); nfs_set_open_stateid_locked(state, stateid, open_flags); write_sequnlock(&state->seqlock); } Commit Message: NFSv4: Convert the open and close ops to use fmode Signed-off-by: Trond Myklebust <Trond.Myklebust@netapp.com> CWE ID:
static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, int open_flags) static void nfs_set_open_stateid(struct nfs4_state *state, nfs4_stateid *stateid, fmode_t fmode) { write_seqlock(&state->seqlock); nfs_set_open_stateid_locked(state, stateid, fmode); write_sequnlock(&state->seqlock); }
165,705
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 copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i]; } } } Commit Message: FLACExtractor: copy protect mWriteBuffer Bug: 30895578 Change-Id: I4cba36bbe3502678210e5925181683df9726b431 CWE ID: CWE-119
static void copyMultiCh16(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels) static void copyMultiCh16(short *dst, const int * src[FLACParser::kMaxChannels], unsigned nSamples, unsigned nChannels) { for (unsigned i = 0; i < nSamples; ++i) { for (unsigned c = 0; c < nChannels; ++c) { *dst++ = src[c][i]; } } }
174,018
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 fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fht8x8_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 fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { void reference_8x8_dct_2d(const int16_t input[kNumCoeffs], double output[kNumCoeffs]) { // First transform columns for (int i = 0; i < 8; ++i) { double temp_in[8], temp_out[8]; for (int j = 0; j < 8; ++j) temp_in[j] = input[j*8 + i]; reference_8x8_dct_1d(temp_in, temp_out, 1); for (int j = 0; j < 8; ++j) output[j * 8 + i] = temp_out[j]; } // Then transform rows for (int i = 0; i < 8; ++i) { double temp_in[8], temp_out[8]; for (int j = 0; j < 8; ++j) temp_in[j] = output[j + i*8]; reference_8x8_dct_1d(temp_in, temp_out, 1); // Scale by some magic number for (int j = 0; j < 8; ++j) output[j + i * 8] = temp_out[j] * 2; } } void fdct8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vpx_fdct8x8_c(in, out, stride); } void fht8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vp9_fht8x8_c(in, out, stride, tx_type); }
174,565
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 ProcessHeap::Init() { total_allocated_space_ = 0; total_allocated_object_size_ = 0; total_marked_object_size_ = 0; GCInfoTable::Init(); base::SamplingHeapProfiler::SetHooksInstallCallback([]() { HeapAllocHooks::SetAllocationHook(&BlinkGCAllocHook); HeapAllocHooks::SetFreeHook(&BlinkGCFreeHook); }); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <mlippautz@chromium.org> Reviewed-by: Kentaro Hara <haraken@chromium.org> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void ProcessHeap::Init() { total_allocated_space_ = 0; total_allocated_object_size_ = 0; total_marked_object_size_ = 0; base::SamplingHeapProfiler::SetHooksInstallCallback([]() { HeapAllocHooks::SetAllocationHook(&BlinkGCAllocHook); HeapAllocHooks::SetFreeHook(&BlinkGCFreeHook); }); }
173,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rpl_daoack_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp; const char *dagid_str = "<elided>"; ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN); if (length < ND_RPL_DAOACK_MIN_LEN) goto tooshort; bp += ND_RPL_DAOACK_MIN_LEN; length -= ND_RPL_DAOACK_MIN_LEN; if(RPL_DAOACK_D(daoack->rpl_flags)) { ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, daoack->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]", dagid_str, daoack->rpl_daoseq, daoack->rpl_instanceid, daoack->rpl_status)); /* no officially defined options for DAOACK, but print any we find */ if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo," [|dao-truncated]")); return; tooshort: ND_PRINT((ndo," [|dao-length too short]")); return; } Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check Moreover: Add and use *_tstr[] strings. Update four tests outputs accordingly. Fix a space. Wang Junjie of 360 ESG Codesafe Team had independently identified this vulnerability in 2018 by means of fuzzing and provided the packet capture file for the test. CWE ID: CWE-125
rpl_daoack_print(netdissect_options *ndo, const u_char *bp, u_int length) { const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp; const char *dagid_str = "<elided>"; ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN); if (length < ND_RPL_DAOACK_MIN_LEN) goto tooshort; bp += ND_RPL_DAOACK_MIN_LEN; length -= ND_RPL_DAOACK_MIN_LEN; if(RPL_DAOACK_D(daoack->rpl_flags)) { ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN); if (length < DAGID_LEN) goto tooshort; dagid_str = ip6addr_string (ndo, daoack->rpl_dagid); bp += DAGID_LEN; length -= DAGID_LEN; } ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]", dagid_str, daoack->rpl_daoseq, daoack->rpl_instanceid, daoack->rpl_status)); /* no officially defined options for DAOACK, but print any we find */ if(ndo->ndo_vflag > 1) { const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp; rpl_dio_printopt(ndo, opt, length); } return; trunc: ND_PRINT((ndo, "%s", rpl_tstr)); return; tooshort: ND_PRINT((ndo," [|dao-length too short]")); return; }
169,829
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; char *key; uint len; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!offset) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(error_zval_ptr);; } switch (Z_TYPE_P(offset)) { case IS_STRING: key = Z_STRVAL_P(offset); len = Z_STRLEN_P(offset) + 1; string_offest: if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined index: %s", key); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined index: %s", key); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; case IS_NULL: key = ""; len = 1; goto string_offest; case IS_RESOURCE: zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset)); case IS_DOUBLE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; default: zend_error(E_WARNING, "Illegal offset type"); return (type == BP_VAR_W || type == BP_VAR_RW) ? &EG(error_zval_ptr) : &EG(uninitialized_zval_ptr); } } /* }}} */ Commit Message: Fix bug #73029 - Missing type check when unserializing SplArray CWE ID: CWE-20
static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, zval *offset, int type TSRMLS_DC) /* {{{ */ { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(object TSRMLS_CC); zval **retval; char *key; uint len; long index; HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (!offset || !ht) { return &EG(uninitialized_zval_ptr); } if ((type == BP_VAR_W || type == BP_VAR_RW) && (ht->nApplyCount > 0)) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return &EG(error_zval_ptr);; } switch (Z_TYPE_P(offset)) { case IS_STRING: key = Z_STRVAL_P(offset); len = Z_STRLEN_P(offset) + 1; string_offest: if (zend_symtable_find(ht, key, len, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined index: %s", key); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE,"Undefined index: %s", key); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_symtable_update(ht, key, len, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; case IS_NULL: key = ""; len = 1; goto string_offest; case IS_RESOURCE: zend_error(E_STRICT, "Resource ID#%ld used as offset, casting to integer (%ld)", Z_LVAL_P(offset), Z_LVAL_P(offset)); case IS_DOUBLE: case IS_BOOL: case IS_LONG: if (offset->type == IS_DOUBLE) { index = (long)Z_DVAL_P(offset); } else { index = Z_LVAL_P(offset); } if (zend_hash_index_find(ht, index, (void **) &retval) == FAILURE) { switch (type) { case BP_VAR_R: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_UNSET: case BP_VAR_IS: retval = &EG(uninitialized_zval_ptr); break; case BP_VAR_RW: zend_error(E_NOTICE, "Undefined offset: %ld", index); case BP_VAR_W: { zval *value; ALLOC_INIT_ZVAL(value); zend_hash_index_update(ht, index, (void**)&value, sizeof(void*), (void **)&retval); } } } return retval; default: zend_error(E_WARNING, "Illegal offset type"); return (type == BP_VAR_W || type == BP_VAR_RW) ? &EG(error_zval_ptr) : &EG(uninitialized_zval_ptr); } } /* }}} */
166,931
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 key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = type->match, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse A previous patch added a ->match_preparse() method to the key type. This is allowed to override the function called by the iteration algorithm. Therefore, we can just set a default that simply checks for an exact match of the key description with the original criterion data and allow match_preparse to override it as needed. The key_type::match op is then redundant and can be removed, as can the user_match() function. Signed-off-by: David Howells <dhowells@redhat.com> Acked-by: Vivek Goyal <vgoyal@redhat.com> CWE ID: CWE-476
struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { construct_get_dest_keyring(&dest_keyring); ret = key_link(dest_keyring, key); key_put(dest_keyring); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; }
168,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: check_interlace_type(int PNG_CONST interlace_type) { if (interlace_type != PNG_INTERLACE_NONE) { /* This is an internal error - --interlace tests should be skipped, not * attempted. */ fprintf(stderr, "pngvalid: no interlace support\n"); exit(99); } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
check_interlace_type(int PNG_CONST interlace_type) check_interlace_type(int const interlace_type) { /* Prior to 1.7.0 libpng does not support the write of an interlaced image * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the * code here does the pixel interlace itself, so: */ if (interlace_type != PNG_INTERLACE_NONE) { /* This is an internal error - --interlace tests should be skipped, not * attempted. */ fprintf(stderr, "pngvalid: no interlace support\n"); exit(99); } }
173,605
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 Track::GetType() const { return m_info.type; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Track::GetType() const
174,375