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 av_cold int xpm_decode_close(AVCodecContext *avctx) { XPMDecContext *x = avctx->priv_data; av_freep(&x->pixels); return 0; } Commit Message: avcodec/xpmdec: Fix multiple pointer/memory issues Most of these were found through code review in response to fixing 1466/clusterfuzz-testcase-minimized-5961584419536896 There is thus no testcase for most of this. The initial issue was Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-119
static av_cold int xpm_decode_close(AVCodecContext *avctx) { XPMDecContext *x = avctx->priv_data; av_freep(&x->pixels); av_freep(&x->buf); x->buf_size = 0; return 0; }
168,077
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num)); asn1_write(data, blob->data, blob->length); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_ContextSimple(struct asn1_data *data, uint8_t num, DATA_BLOB *blob) { if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(num))) return false; if (!asn1_write(data, blob->data, blob->length)) return false; return asn1_pop_tag(data); }
164,587
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType( const Resource& cached_resource) { switch (cached_resource.GetType()) { case Resource::kImage: return InspectorPageAgent::kImageResource; case Resource::kFont: return InspectorPageAgent::kFontResource; case Resource::kMedia: return InspectorPageAgent::kMediaResource; case Resource::kManifest: return InspectorPageAgent::kManifestResource; case Resource::kTextTrack: return InspectorPageAgent::kTextTrackResource; case Resource::kCSSStyleSheet: case Resource::kXSLStyleSheet: return InspectorPageAgent::kStylesheetResource; case Resource::kScript: return InspectorPageAgent::kScriptResource; case Resource::kImportResource: case Resource::kMainResource: return InspectorPageAgent::kDocumentResource; default: break; } return InspectorPageAgent::kOtherResource; } Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent This patch plumbs resoure type into the DispatchWillSendRequest instrumenation. This allows us to report accurate type in Network.RequestWillBeSent event, instead of "Other", that we report today. BUG=765501 R=dgozman Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c Reviewed-on: https://chromium-review.googlesource.com/667504 Reviewed-by: Pavel Feldman <pfeldman@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Commit-Queue: Andrey Lushnikov <lushnikov@chromium.org> Cr-Commit-Position: refs/heads/master@{#507936} CWE ID: CWE-119
InspectorPageAgent::ResourceType InspectorPageAgent::CachedResourceType( InspectorPageAgent::ResourceType InspectorPageAgent::ToResourceType( const Resource::Type resource_type) { switch (resource_type) { case Resource::kImage: return InspectorPageAgent::kImageResource; case Resource::kFont: return InspectorPageAgent::kFontResource; case Resource::kMedia: return InspectorPageAgent::kMediaResource; case Resource::kManifest: return InspectorPageAgent::kManifestResource; case Resource::kTextTrack: return InspectorPageAgent::kTextTrackResource; case Resource::kCSSStyleSheet: case Resource::kXSLStyleSheet: return InspectorPageAgent::kStylesheetResource; case Resource::kScript: return InspectorPageAgent::kScriptResource; case Resource::kImportResource: case Resource::kMainResource: return InspectorPageAgent::kDocumentResource; default: break; } return InspectorPageAgent::kOtherResource; }
172,469
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bta_co_rfc_data_outgoing(void *user_data, uint8_t *buf, uint16_t size) { pthread_mutex_lock(&slot_lock); uint32_t id = (uintptr_t)user_data; int ret = false; rfc_slot_t *slot = find_rfc_slot_by_id(id); if (!slot) goto out; int received = recv(slot->fd, buf, size, 0); if(received == size) { ret = true; } else { LOG_ERROR("%s error receiving RFCOMM data from app: %s", __func__, strerror(errno)); cleanup_rfc_slot(slot); } out:; pthread_mutex_unlock(&slot_lock); return ret; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int bta_co_rfc_data_outgoing(void *user_data, uint8_t *buf, uint16_t size) { pthread_mutex_lock(&slot_lock); uint32_t id = (uintptr_t)user_data; int ret = false; rfc_slot_t *slot = find_rfc_slot_by_id(id); if (!slot) goto out; int received = TEMP_FAILURE_RETRY(recv(slot->fd, buf, size, 0)); if(received == size) { ret = true; } else { LOG_ERROR("%s error receiving RFCOMM data from app: %s", __func__, strerror(errno)); cleanup_rfc_slot(slot); } out:; pthread_mutex_unlock(&slot_lock); return ret; }
173,455
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintViewManager::PrintPreviewDone() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_NE(NOT_PREVIEWING, print_preview_state_); if (print_preview_state_ == SCRIPTED_PREVIEW) { auto& map = g_scripted_print_preview_closure_map.Get(); auto it = map.find(scripted_print_preview_rph_); CHECK(it != map.end()); it->second.Run(); map.erase(it); scripted_print_preview_rph_ = nullptr; } print_preview_state_ = NOT_PREVIEWING; print_preview_rfh_ = nullptr; } Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated(). BUG=694382,698622 Review-Url: https://codereview.chromium.org/2742853003 Cr-Commit-Position: refs/heads/master@{#457363} CWE ID: CWE-125
void PrintViewManager::PrintPreviewDone() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (print_preview_state_ == NOT_PREVIEWING) return; if (print_preview_state_ == SCRIPTED_PREVIEW) { auto& map = g_scripted_print_preview_closure_map.Get(); auto it = map.find(scripted_print_preview_rph_); CHECK(it != map.end()); it->second.Run(); map.erase(it); scripted_print_preview_rph_ = nullptr; } print_preview_state_ = NOT_PREVIEWING; print_preview_rfh_ = nullptr; }
172,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXNodeObject::canSetValueAttribute() const { if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true")) return false; if (isProgressIndicator() || isSlider()) return true; if (isTextControl() && !isNativeTextControl()) return true; return !isReadOnly(); } 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
bool AXNodeObject::canSetValueAttribute() const { if (equalIgnoringASCIICase(getAttribute(aria_readonlyAttr), "true")) return false; if (isProgressIndicator() || isSlider()) return true; if (isTextControl() && !isNativeTextControl()) return true; return !isReadOnly(); }
171,909
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t OMXNodeInstance::getConfig( OMX_INDEXTYPE index, void *params, size_t /* size */) { Mutex::Autolock autoLock(mLock); OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; if (err != OMX_ErrorNoMore) { CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index); } return StatusFromOMXError(err); } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
status_t OMXNodeInstance::getConfig( OMX_INDEXTYPE index, void *params, size_t /* size */) { Mutex::Autolock autoLock(mLock); if (isProhibitedIndex_l(index)) { android_errorWriteLog(0x534e4554, "29422020"); return BAD_INDEX; } OMX_ERRORTYPE err = OMX_GetConfig(mHandle, index, params); OMX_INDEXEXTTYPE extIndex = (OMX_INDEXEXTTYPE)index; if (err != OMX_ErrorNoMore) { CLOG_IF_ERROR(getConfig, err, "%s(%#x)", asString(extIndex), index); } return StatusFromOMXError(err); }
174,134
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { data[h * stride + w] = fill_constant; } } } 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 FillConstant(uint8_t *data, int stride, uint8_t fill_constant) { // Sum of Absolute Differences Average. Given two blocks, and a prediction // calculate the absolute difference between one pixel and average of the // corresponding and predicted pixels; accumulate. unsigned int ReferenceSADavg(int block_idx) { unsigned int sad = 0; const uint8_t *const reference8 = GetReference(block_idx); const uint8_t *const source8 = source_data_; const uint8_t *const second_pred8 = second_pred_; #if CONFIG_VP9_HIGHBITDEPTH const uint16_t *const reference16 = CONVERT_TO_SHORTPTR(GetReference(block_idx)); const uint16_t *const source16 = CONVERT_TO_SHORTPTR(source_data_); const uint16_t *const second_pred16 = CONVERT_TO_SHORTPTR(second_pred_); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { const int tmp = second_pred8[h * width_ + w] + reference8[h * reference_stride_ + w]; const uint8_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source8[h * source_stride_ + w] - comp_pred); #if CONFIG_VP9_HIGHBITDEPTH } else { const int tmp = second_pred16[h * width_ + w] + reference16[h * reference_stride_ + w]; const uint16_t comp_pred = ROUND_POWER_OF_TWO(tmp, 1); sad += abs(source16[h * source_stride_ + w] - comp_pred); #endif // CONFIG_VP9_HIGHBITDEPTH } } } return sad; } void FillConstant(uint8_t *data, int stride, uint16_t fill_constant) { uint8_t *data8 = data; #if CONFIG_VP9_HIGHBITDEPTH uint16_t *data16 = CONVERT_TO_SHORTPTR(data); #endif // CONFIG_VP9_HIGHBITDEPTH for (int h = 0; h < height_; ++h) { for (int w = 0; w < width_; ++w) { if (!use_high_bit_depth_) { data8[h * stride + w] = static_cast<uint8_t>(fill_constant); #if CONFIG_VP9_HIGHBITDEPTH } else { data16[h * stride + w] = fill_constant; #endif // CONFIG_VP9_HIGHBITDEPTH } } } }
174,571
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UnprivilegedProcessDelegate::CreateConnectedIpcChannel( const std::string& channel_name, IPC::Listener* delegate, ScopedHandle* client_out, scoped_ptr<IPC::ChannelProxy>* server_out) { scoped_ptr<IPC::ChannelProxy> server; if (!CreateIpcChannel(channel_name, kDaemonIpcSecurityDescriptor, io_task_runner_, delegate, &server)) { return false; } std::string pipe_name(kChromePipeNamePrefix); pipe_name.append(channel_name); SECURITY_ATTRIBUTES security_attributes; security_attributes.nLength = sizeof(security_attributes); security_attributes.lpSecurityDescriptor = NULL; security_attributes.bInheritHandle = TRUE; ScopedHandle client; client.Set(CreateFile(UTF8ToUTF16(pipe_name).c_str(), GENERIC_READ | GENERIC_WRITE, 0, &security_attributes, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED, NULL)); if (!client.IsValid()) return false; *client_out = client.Pass(); *server_out = server.Pass(); return true; } 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
bool UnprivilegedProcessDelegate::CreateConnectedIpcChannel(
171,544
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cssp_read_tsrequest(STREAM token, STREAM pubkey) { STREAM s; int length; int tagval; s = tcp_recv(NULL, 4); if (s == NULL) return False; if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) { logger(Protocol, Error, "cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x", s->p[0]); return False; } if (s->p[1] < 0x80) length = s->p[1] - 2; else if (s->p[1] == 0x81) length = s->p[2] - 1; else if (s->p[1] == 0x82) length = (s->p[2] << 8) | s->p[3]; else return False; s = tcp_recv(s, length); if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; in_uint8s(s, length); if (token) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; token->end = token->p = token->data; out_uint8p(token, s->p, length); s_mark_end(token); } if (pubkey) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; pubkey->data = pubkey->p = s->p; pubkey->end = pubkey->data + length; pubkey->size = length; } return True; } 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
cssp_read_tsrequest(STREAM token, STREAM pubkey) { STREAM s; int length; int tagval; struct stream packet; s = tcp_recv(NULL, 4); if (s == NULL) return False; if (s->p[0] != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) { logger(Protocol, Error, "cssp_read_tsrequest(), expected BER_TAG_SEQUENCE|BER_TAG_CONSTRUCTED, got %x", s->p[0]); return False; } if (s->p[1] < 0x80) length = s->p[1] - 2; else if (s->p[1] == 0x81) length = s->p[2] - 1; else if (s->p[1] == 0x82) length = (s->p[2] << 8) | s->p[3]; else return False; s = tcp_recv(s, length); packet = *s; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!s_check_rem(s, length)) { rdp_protocol_error("cssp_read_tsrequest(), consume of version from stream would overrun", &packet); } in_uint8s(s, length); if (token) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 1)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_SEQUENCE | BER_TAG_CONSTRUCTED)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 0)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; if (!s_check_rem(s, length)) { rdp_protocol_error("cssp_read_tsrequest(), consume of token from stream would overrun", &packet); } s_realloc(token, length); s_reset(token); out_uint8p(token, s->p, length); s_mark_end(token); } if (pubkey) { if (!ber_in_header(s, &tagval, &length) || tagval != (BER_TAG_CTXT_SPECIFIC | BER_TAG_CONSTRUCTED | 3)) return False; if (!ber_in_header(s, &tagval, &length) || tagval != BER_TAG_OCTET_STRING) return False; pubkey->data = pubkey->p = s->p; pubkey->end = pubkey->data + length; pubkey->size = length; } return True; }
169,797
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WarmupURLFetcher::FetchWarmupURLNow( const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1, 2); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server to warm up " "the connection to the proxy." trigger: "A network change while the data reduction proxy is enabled will " "trigger this request." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop it " "is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); GURL warmup_url_with_query_params; GetWarmupURLWithQueryParam(&warmup_url_with_query_params); url_loader_.reset(); fetch_timeout_timer_.Stop(); is_fetch_in_flight_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = warmup_url_with_query_params; resource_request->load_flags = net::LOAD_BYPASS_CACHE; resource_request->render_frame_id = MSG_ROUTING_CONTROL; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); url_loader_->SetAllowHttpErrorResults(true); fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this, &WarmupURLFetcher::OnFetchTimeout); url_loader_->SetOnResponseStartedCallback(base::BindOnce( &WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this))); url_loader_->SetOnRedirectCallback(base::BindRepeating( &WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this))); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( GetNetworkServiceURLLoaderFactory(proxy_server), base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete, base::Unretained(this))); } Commit Message: Disable all DRP URL fetches when holdback is enabled Disable secure proxy checker, warmup url fetcher and client config fetch when the client is in DRP (Data Reduction Proxy) holdback. This CL does not disable pingbacks when client is in the holdback, but the pingback code is going away soon. Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51 Bug: 984964 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965 Commit-Queue: Tarun Bansal <tbansal@chromium.org> Reviewed-by: Robert Ogden <robertogden@chromium.org> Cr-Commit-Position: refs/heads/master@{#679649} CWE ID: CWE-416
void WarmupURLFetcher::FetchWarmupURLNow( const DataReductionProxyServer& proxy_server) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!params::IsIncludedInHoldbackFieldTrial()); UMA_HISTOGRAM_EXACT_LINEAR("DataReductionProxy.WarmupURL.FetchInitiated", 1, 2); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("data_reduction_proxy_warmup", R"( semantics { sender: "Data Reduction Proxy" description: "Sends a request to the Data Reduction Proxy server to warm up " "the connection to the proxy." trigger: "A network change while the data reduction proxy is enabled will " "trigger this request." data: "A specific URL, not related to user data." destination: GOOGLE_OWNED_SERVICE } policy { cookies_allowed: NO setting: "Users can control Data Saver on Android via the 'Data Saver' " "setting. Data Saver is not available on iOS, and on desktop it " "is enabled by installing the Data Saver extension." policy_exception_justification: "Not implemented." })"); GURL warmup_url_with_query_params; GetWarmupURLWithQueryParam(&warmup_url_with_query_params); url_loader_.reset(); fetch_timeout_timer_.Stop(); is_fetch_in_flight_ = true; auto resource_request = std::make_unique<network::ResourceRequest>(); resource_request->url = warmup_url_with_query_params; resource_request->load_flags = net::LOAD_BYPASS_CACHE; resource_request->render_frame_id = MSG_ROUTING_CONTROL; url_loader_ = network::SimpleURLLoader::Create(std::move(resource_request), traffic_annotation); static const int kMaxRetries = 5; url_loader_->SetRetryOptions( kMaxRetries, network::SimpleURLLoader::RETRY_ON_NETWORK_CHANGE); url_loader_->SetAllowHttpErrorResults(true); fetch_timeout_timer_.Start(FROM_HERE, GetFetchTimeout(), this, &WarmupURLFetcher::OnFetchTimeout); url_loader_->SetOnResponseStartedCallback(base::BindOnce( &WarmupURLFetcher::OnURLLoadResponseStarted, base::Unretained(this))); url_loader_->SetOnRedirectCallback(base::BindRepeating( &WarmupURLFetcher::OnURLLoaderRedirect, base::Unretained(this))); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( GetNetworkServiceURLLoaderFactory(proxy_server), base::BindOnce(&WarmupURLFetcher::OnURLLoadComplete, base::Unretained(this))); }
172,425
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); }
167,033
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } Commit Message: re_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c CWE ID: CWE-476
static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; }
168,487
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), context_(context) { RouteFunction("GetAvailability", base::Bind(&V8ContextNativeHandler::GetAvailability, base::Unretained(this))); RouteFunction("GetModuleSystem", base::Bind(&V8ContextNativeHandler::GetModuleSystem, base::Unretained(this))); RouteFunction( "RunWithNativesEnabled", base::Bind(&V8ContextNativeHandler::RunWithNativesEnabled, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context) : ObjectBackedNativeHandler(context), context_(context) { RouteFunction("GetAvailability", base::Bind(&V8ContextNativeHandler::GetAvailability, base::Unretained(this))); RouteFunction("GetModuleSystem", base::Bind(&V8ContextNativeHandler::GetModuleSystem, base::Unretained(this))); RouteFunction("RunWithNativesEnabled", "test", base::Bind(&V8ContextNativeHandler::RunWithNativesEnabled, base::Unretained(this))); }
172,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: write_header( FT_Error error_code ) { FT_Face face; const char* basename; const char* format; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) Fatal( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%s %s (file `%s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%s')", basename ); break; default: sprintf( status.header_buffer, "File `%s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); format = status.encoding != FT_ENCODING_NONE ? "at %g points, first char code = 0x%x" : "at %g points, first glyph index = %d"; snprintf( status.header_buffer, 256, format, status.ptsize / 64.0, status.Num ); if ( FT_HAS_GLYPH_NAMES( face ) ) { char* p; int format_len, gindex, size; size = strlen( status.header_buffer ); p = status.header_buffer + size; size = 256 - size; format = ", name = "; format_len = strlen( format ); if ( size >= format_len + 2 ) { gindex = status.Num; if ( status.encoding != FT_ENCODING_NONE ) gindex = FTDemo_Get_Index( handle, status.Num ); strcpy( p, format ); if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) ) *p = '\0'; } } status.header = status.header_buffer; grWriteCellString( display->bitmap, 0, HEADER_HEIGHT, status.header_buffer, display->fore_color ); if ( status.use_custom_lcd_filter ) { int fwi = status.fw_index; unsigned char *fw = status.filter_weights; sprintf( status.header_buffer, "%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s", fwi == 0 ? "[" : " ", fw[0], fwi == 0 ? "]" : " ", fwi == 1 ? "[" : " ", fw[1], fwi == 1 ? "]" : " ", fwi == 2 ? "[" : " ", fw[2], fwi == 2 ? "]" : " ", fwi == 3 ? "[" : " ", fw[3], fwi == 3 ? "]" : " ", fwi == 4 ? "[" : " ", fw[4], fwi == 4 ? "]" : " " ); grWriteCellString( display->bitmap, 0, 2 * HEADER_HEIGHT, status.header_buffer, display->fore_color ); } grRefreshSurface( display->surface ); } Commit Message: CWE ID: CWE-119
write_header( FT_Error error_code ) { FT_Face face; const char* basename; const char* format; error = FTC_Manager_LookupFace( handle->cache_manager, handle->scaler.face_id, &face ); if ( error ) Fatal( "can't access font file" ); if ( !status.header ) { basename = ft_basename( handle->current_font->filepathname ); switch ( error_code ) { case FT_Err_Ok: sprintf( status.header_buffer, "%.50s %.50s (file `%.100s')", face->family_name, face->style_name, basename ); break; case FT_Err_Invalid_Pixel_Size: sprintf( status.header_buffer, "Invalid pixel size (file `%.100s')", basename ); break; case FT_Err_Invalid_PPem: sprintf( status.header_buffer, "Invalid ppem value (file `%.100s')", basename ); break; default: sprintf( status.header_buffer, "File `%.100s': error 0x%04x", basename, (FT_UShort)error_code ); break; } status.header = status.header_buffer; } grWriteCellString( display->bitmap, 0, 0, status.header, display->fore_color ); format = status.encoding != FT_ENCODING_NONE ? "at %g points, first char code = 0x%x" : "at %g points, first glyph index = %d"; snprintf( status.header_buffer, 256, format, status.ptsize / 64.0, status.Num ); if ( FT_HAS_GLYPH_NAMES( face ) ) { char* p; int format_len, gindex, size; size = strlen( status.header_buffer ); p = status.header_buffer + size; size = 256 - size; format = ", name = "; format_len = strlen( format ); if ( size >= format_len + 2 ) { gindex = status.Num; if ( status.encoding != FT_ENCODING_NONE ) gindex = FTDemo_Get_Index( handle, status.Num ); strcpy( p, format ); if ( FT_Get_Glyph_Name( face, gindex, p + format_len, size - format_len ) ) *p = '\0'; } } status.header = status.header_buffer; grWriteCellString( display->bitmap, 0, HEADER_HEIGHT, status.header_buffer, display->fore_color ); if ( status.use_custom_lcd_filter ) { int fwi = status.fw_index; unsigned char *fw = status.filter_weights; sprintf( status.header_buffer, "%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s%s0x%02X%s", fwi == 0 ? "[" : " ", fw[0], fwi == 0 ? "]" : " ", fwi == 1 ? "[" : " ", fw[1], fwi == 1 ? "]" : " ", fwi == 2 ? "[" : " ", fw[2], fwi == 2 ? "]" : " ", fwi == 3 ? "[" : " ", fw[3], fwi == 3 ? "]" : " ", fwi == 4 ? "[" : " ", fw[4], fwi == 4 ? "]" : " " ); grWriteCellString( display->bitmap, 0, 2 * HEADER_HEIGHT, status.header_buffer, display->fore_color ); } grRefreshSurface( display->surface ); }
165,001
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SpeechSynthesisLibrary* CrosLibrary::GetSpeechSynthesisLibrary() { return speech_synthesis_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
SpeechSynthesisLibrary* CrosLibrary::GetSpeechSynthesisLibrary() {
170,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind) : host_id_(host_id), gpu_process_(base::kNullProcessHandle), in_process_(false), software_rendering_(false), kind_(kind), process_launched_(false) { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) || CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU)) in_process_ = true; DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL); g_gpu_process_hosts[kind] = this; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id)); process_.reset( new BrowserChildProcessHostImpl(content::PROCESS_TYPE_GPU, this)); } 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:
GpuProcessHost::GpuProcessHost(int host_id, GpuProcessKind kind) : host_id_(host_id), in_process_(false), software_rendering_(false), kind_(kind), process_launched_(false) { if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess) || CommandLine::ForCurrentProcess()->HasSwitch(switches::kInProcessGPU)) in_process_ = true; DCHECK(!in_process_ || g_gpu_process_hosts[kind] == NULL); g_gpu_process_hosts[kind] = this; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(base::IgnoreResult(&GpuProcessHostUIShim::Create), host_id)); process_.reset( new BrowserChildProcessHostImpl(content::PROCESS_TYPE_GPU, this)); }
170,921
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: AudioTrack::AudioTrack( Segment* pSegment, long long element_start, long long element_size) : Track(pSegment, element_start, element_size) { } 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
AudioTrack::AudioTrack(
174,239
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ParamTraits<FilePath>::Read(const Message* m, PickleIterator* iter, param_type* r) { FilePath::StringType value; if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value)) return false; *r = FilePath(value); return true; } Commit Message: Validate that paths don't contain embedded NULLs at deserialization. BUG=166867 Review URL: https://chromiumcodereview.appspot.com/11743009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@174935 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool ParamTraits<FilePath>::Read(const Message* m, PickleIterator* iter, param_type* r) { FilePath::StringType value; if (!ParamTraits<FilePath::StringType>::Read(m, iter, &value)) return false; // Reject embedded NULs as they can cause security checks to go awry. if (value.find(FILE_PATH_LITERAL('\0')) != FilePath::StringType::npos) return false; *r = FilePath(value); return true; }
171,501
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DaemonProcessTest::LaunchNetworkProcess() { terminal_id_ = 0; daemon_process_->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 DaemonProcessTest::LaunchNetworkProcess() { terminal_id_ = 0; daemon_process_->OnChannelConnected(0); }
171,541
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SADs(unsigned int *results) { const uint8_t* refs[] = {GetReference(0), GetReference(1), GetReference(2), GetReference(3)}; REGISTER_STATE_CHECK(GET_PARAM(2)(source_data_, source_stride_, refs, reference_stride_, results)); } 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 SADs(unsigned int *results) { const uint8_t *references[] = {GetReference(0), GetReference(1), GetReference(2), GetReference(3)}; ASM_REGISTER_STATE_CHECK(GET_PARAM(2)(source_data_, source_stride_, references, reference_stride_, results)); }
174,576
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ldb_dn_escape_internal(char *dst, const char *src, int len) { const char *p, *s; char *d; size_t l; p = s = src; d = dst; while (p - src < len) { p += strcspn(p, ",=\n\r+<>#;\\\" "); if (p - src == len) /* found no escapable chars */ break; /* copy the part of the string before the stop */ memcpy(d, s, p - s); d += (p - s); /* move to current position */ switch (*p) { case ' ': if (p == src || (p-src)==(len-1)) { /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; case '?': /* these must be escaped using \c form */ *d++ = '\\'; *d++ = *p++; break; default: { /* any others get \XX form */ unsigned char v; const char *hexbytes = "0123456789ABCDEF"; v = *(const unsigned char *)p; *d++ = '\\'; *d++ = hexbytes[v>>4]; *d++ = hexbytes[v&0xF]; p++; break; } } s = p; /* move forward */ } Commit Message: CWE ID: CWE-200
static int ldb_dn_escape_internal(char *dst, const char *src, int len) { char c; char *d; int i; d = dst; for (i = 0; i < len; i++){ c = src[i]; switch (c) { case ' ': if (i == 0 || i == len - 1) { /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = c; } else { /* otherwise don't escape */ *d++ = c; } break; /* if at the beginning or end * of the string then escape */ *d++ = '\\'; *d++ = *p++; } else { /* otherwise don't escape */ *d++ = *p++; } break; case '?': /* these must be escaped using \c form */ *d++ = '\\'; *d++ = c; break; case ';': case '\r': case '\n': case '=': case '\0': { /* any others get \XX form */ unsigned char v; const char *hexbytes = "0123456789ABCDEF"; v = (const unsigned char)c; *d++ = '\\'; *d++ = hexbytes[v>>4]; *d++ = hexbytes[v&0xF]; break; } default: *d++ = c; } }
164,668
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: delete_policy_2_svc(dpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->name; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, NULL, NULL)) { log_unauth("kadm5_delete_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_DELETE; } else { ret.code = kadm5_delete_policy((void *)handle, arg->name); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
delete_policy_2_svc(dpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->name; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_DELETE, NULL, NULL)) { log_unauth("kadm5_delete_policy", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_DELETE; } else { ret.code = kadm5_delete_policy((void *)handle, arg->name); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_delete_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,511
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PluginInfoMessageFilter::PluginsLoaded( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const std::vector<WebPluginInfo>& plugins) { ChromeViewHostMsg_GetPluginInfo_Output output; scoped_ptr<PluginMetadata> plugin_metadata; if (context_.FindEnabledPlugin(params.render_view_id, params.url, params.top_origin_url, params.mime_type, &output.status, &output.plugin, &output.actual_mime_type, &plugin_metadata)) { context_.DecidePluginStatus(params, output.plugin, plugin_metadata.get(), &output.status); } if (plugin_metadata) { output.group_identifier = plugin_metadata->identifier(); output.group_name = plugin_metadata->name(); } context_.GrantAccess(output.status, output.plugin.path); ChromeViewHostMsg_GetPluginInfo::WriteReplyParams(reply_msg, output); Send(reply_msg); } Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/ BUG=172573 Review URL: https://codereview.chromium.org/12177018 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-287
void PluginInfoMessageFilter::PluginsLoaded( const GetPluginInfo_Params& params, IPC::Message* reply_msg, const std::vector<WebPluginInfo>& plugins) { ChromeViewHostMsg_GetPluginInfo_Output output; scoped_ptr<PluginMetadata> plugin_metadata; if (context_.FindEnabledPlugin(params.render_view_id, params.url, params.top_origin_url, params.mime_type, &output.status, &output.plugin, &output.actual_mime_type, &plugin_metadata)) { context_.DecidePluginStatus(params, output.plugin, plugin_metadata.get(), &output.status); } if (plugin_metadata) { output.group_identifier = plugin_metadata->identifier(); output.group_name = plugin_metadata->name(); } context_.MaybeGrantAccess(output.status, output.plugin.path); ChromeViewHostMsg_GetPluginInfo::WriteReplyParams(reply_msg, output); Send(reply_msg); }
171,473
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Response StorageHandler::UntrackCacheStorageForOrigin( const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&CacheStorageObserver::UntrackOriginOnIOThread, base::Unretained(GetCacheStorageObserver()), url::Origin::Create(origin_url))); return Response::OK(); } 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
Response StorageHandler::UntrackCacheStorageForOrigin( const std::string& origin) { if (!storage_partition_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::BindOnce(&CacheStorageObserver::UntrackOriginOnIOThread, base::Unretained(GetCacheStorageObserver()), url::Origin::Create(origin_url))); return Response::OK(); }
172,778
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: process_bitmap_updates(STREAM s) { uint16 num_updates; uint16 left, top, right, bottom, width, height; uint16 cx, cy, bpp, Bpp, compress, bufsize, size; uint8 *data, *bmpdata; int i; logger(Protocol, Debug, "%s()", __func__); in_uint16_le(s, num_updates); for (i = 0; i < num_updates; i++) { in_uint16_le(s, left); in_uint16_le(s, top); in_uint16_le(s, right); in_uint16_le(s, bottom); in_uint16_le(s, width); in_uint16_le(s, height); in_uint16_le(s, bpp); Bpp = (bpp + 7) / 8; in_uint16_le(s, compress); in_uint16_le(s, bufsize); cx = right - left + 1; cy = bottom - top + 1; logger(Graphics, Debug, "process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d", left, top, right, bottom, width, height, Bpp, compress); if (!compress) { int y; bmpdata = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp); } ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); xfree(bmpdata); continue; } if (compress & 0x400) { size = bufsize; } else { in_uint8s(s, 2); /* pad */ in_uint16_le(s, size); in_uint8s(s, 4); /* line_size, final_size */ } in_uint8p(s, data, size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); } else { logger(Graphics, Warning, "process_bitmap_updates(), failed to decompress bitmap"); } xfree(bmpdata); } } 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
process_bitmap_updates(STREAM s) /* Process TS_BITMAP_DATA */ static void process_bitmap_data(STREAM s) { uint16 left, top, right, bottom, width, height; uint16 cx, cy, bpp, Bpp, flags, bufsize, size; uint8 *data, *bmpdata; logger(Protocol, Debug, "%s()", __func__); struct stream packet = *s; in_uint16_le(s, left); /* destLeft */ in_uint16_le(s, top); /* destTop */ in_uint16_le(s, right); /* destRight */ in_uint16_le(s, bottom); /* destBottom */ in_uint16_le(s, width); /* width */ in_uint16_le(s, height); /* height */ in_uint16_le(s, bpp); /*bitsPerPixel */ Bpp = (bpp + 7) / 8; in_uint16_le(s, flags); /* flags */ in_uint16_le(s, bufsize); /* bitmapLength */ cx = right - left + 1; cy = bottom - top + 1; /* FIXME: There are a assumtion that we do not consider in this code. The value of bpp is not passed to ui_paint_bitmap() which relies on g_server_bpp for drawing the bitmap data. Does this means that we can sanity check bpp with g_server_bpp ? */ if (Bpp == 0 || width == 0 || height == 0) { logger(Protocol, Warning, "%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x", __func__, left, top, right, bottom, width, height, bpp, flags); rdp_protocol_error("TS_BITMAP_DATA, unsafe size of bitmap data received from server", &packet); } if ((RD_UINT32_MAX / Bpp) <= (width * height)) { logger(Protocol, Warning, "%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x", __func__, left, top, right, bottom, width, height, bpp, flags); rdp_protocol_error("TS_BITMAP_DATA, unsafe size of bitmap data received from server", &packet); } if (flags == 0) { /* read uncompressed bitmap data */ int y; bmpdata = (uint8 *) xmalloc(width * height * Bpp); for (y = 0; y < height; y++) { in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp); } ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); xfree(bmpdata); return; } if (flags & NO_BITMAP_COMPRESSION_HDR) { size = bufsize; } else { /* Read TS_CD_HEADER */ in_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */ in_uint16_le(s, size); /* cbCompMainBodySize */ in_uint8s(s, 2); /* skip cbScanWidth */ in_uint8s(s, 2); /* skip cbUncompressedSize */ } /* read compressed bitmap data */ if (!s_check_rem(s, size)) { rdp_protocol_error("process_bitmap_data(), consume of bitmap data from stream would overrun", &packet); } in_uint8p(s, data, size); bmpdata = (uint8 *) xmalloc(width * height * Bpp); if (bitmap_decompress(bmpdata, width, height, data, size, Bpp)) { ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata); } else { logger(Protocol, Warning, "%s(), failed to decompress bitmap", __func__); } xfree(bmpdata); } /* Process TS_UPDATE_BITMAP_DATA */ void process_bitmap_updates(STREAM s) { int i; uint16 num_updates; in_uint16_le(s, num_updates); /* rectangles */ for (i = 0; i < num_updates; i++) { process_bitmap_data(s); } }
169,802
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static const char *parse_number( cJSON *item, const char *num ) { int64_t i = 0; double f = 0; int isint = 1; int sign = 1, scale = 0, subscale = 0, signsubscale = 1; /* Could use sscanf for this? */ if ( *num == '-' ) { /* Has sign. */ sign = -1; ++num; } if ( *num == '0' ) /* Is zero. */ ++num; if ( *num >= '1' && *num<='9' ) { /* Number. */ do { i = ( i * 10 ) + ( *num - '0' ); f = ( f * 10.0 ) + ( *num - '0' ); ++num; } while ( *num >= '0' && *num <= '9' ); } if ( *num == '.' && num[1] >= '0' && num[1] <= '9' ) { /* Fractional part. */ isint = 0; ++num; do { f = ( f * 10.0 ) + ( *num++ - '0' ); scale--; } while ( *num >= '0' && *num <= '9' ); } if ( *num == 'e' || *num == 'E' ) { /* Exponent. */ isint = 0; ++num; if ( *num == '+' ) ++num; else if ( *num == '-' ) { /* With sign. */ signsubscale = -1; ++num; } while ( *num >= '0' && *num <= '9' ) subscale = ( subscale * 10 ) + ( *num++ - '0' ); } /* Put it together. */ if ( isint ) { /* Int: number = +/- number */ i = sign * i; item->valueint = i; item->valuefloat = i; } else { /* Float: number = +/- number.fraction * 10^+/- exponent */ f = sign * f * ipow( 10.0, scale + subscale * signsubscale ); item->valueint = f; item->valuefloat = f; } item->type = cJSON_Number; return num; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <bmah@es.net> CWE ID: CWE-119
static const char *parse_number( cJSON *item, const char *num ) static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; } typedef struct {char *buffer; int length; int offset; } printbuffer; static char* ensure(printbuffer *p,int needed) { char *newbuffer;int newsize; if (!p || !p->buffer) return 0; needed+=p->offset; if (needed<=p->length) return p->buffer+p->offset; newsize=pow2gt(needed); newbuffer=(char*)cJSON_malloc(newsize); if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;} if (newbuffer) memcpy(newbuffer,p->buffer,p->length); cJSON_free(p->buffer); p->length=newsize; p->buffer=newbuffer; return newbuffer+p->offset; }
167,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) { goto end; } if (IPV4_GET_HLEN(reassembled) != 20) { goto end; } if (IPV4_GET_IPLEN(reassembled) != 39) { goto end; } /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') { goto end; } } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') { goto end; } } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
DefragInOrderSimpleTest(void) { Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; Packet *reassembled = NULL; int id = 12; int i; int ret = 0; DefragInit(); p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8); if (p1 == NULL) goto end; p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8); if (p2 == NULL) goto end; p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3); if (p3 == NULL) goto end; if (Defrag(NULL, NULL, p1, NULL) != NULL) goto end; if (Defrag(NULL, NULL, p2, NULL) != NULL) goto end; reassembled = Defrag(NULL, NULL, p3, NULL); if (reassembled == NULL) { goto end; } if (IPV4_GET_HLEN(reassembled) != 20) { goto end; } if (IPV4_GET_IPLEN(reassembled) != 39) { goto end; } /* 20 bytes in we should find 8 bytes of A. */ for (i = 20; i < 20 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'A') { goto end; } } /* 28 bytes in we should find 8 bytes of B. */ for (i = 28; i < 28 + 8; i++) { if (GET_PKT_DATA(reassembled)[i] != 'B') { goto end; } } /* And 36 bytes in we should find 3 bytes of C. */ for (i = 36; i < 36 + 3; i++) { if (GET_PKT_DATA(reassembled)[i] != 'C') goto end; } ret = 1; end: if (p1 != NULL) SCFree(p1); if (p2 != NULL) SCFree(p2); if (p3 != NULL) SCFree(p3); if (reassembled != NULL) SCFree(reassembled); DefragDestroy(); return ret; }
168,298
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg) { if (pp != NULL) png_error(pp, msg); /* Else we have to do it ourselves. png_error eventually calls store_log, * above. store_log accepts a NULL png_structp - it just changes what gets * output by store_message. */ store_log(ps, pp, msg, 1 /* error */); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg) store_pool_error(png_store *ps, png_const_structp pp, const char *msg) { if (pp != NULL) png_error(pp, msg); /* Else we have to do it ourselves. png_error eventually calls store_log, * above. store_log accepts a NULL png_structp - it just changes what gets * output by store_message. */ store_log(ps, pp, msg, 1 /* error */); }
173,708
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t AMRSource::read( MediaBuffer **out, const ReadOptions *options) { *out = NULL; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (options && options->getSeekTo(&seekTimeUs, &mode)) { size_t size; int64_t seekFrame = seekTimeUs / 20000ll; // 20ms per frame. mCurrentTimeUs = seekFrame * 20000ll; size_t index = seekFrame < 0 ? 0 : seekFrame / 50; if (index >= mOffsetTableLength) { index = mOffsetTableLength - 1; } mOffset = mOffsetTable[index] + (mIsWide ? 9 : 6); for (size_t i = 0; i< seekFrame - index * 50; i++) { status_t err; if ((err = getFrameSizeByOffset(mDataSource, mOffset, mIsWide, &size)) != OK) { return err; } mOffset += size; } } uint8_t header; ssize_t n = mDataSource->readAt(mOffset, &header, 1); if (n < 1) { return ERROR_END_OF_STREAM; } if (header & 0x83) { ALOGE("padding bits must be 0, header is 0x%02x", header); return ERROR_MALFORMED; } unsigned FT = (header >> 3) & 0x0f; size_t frameSize = getFrameSize(mIsWide, FT); if (frameSize == 0) { return ERROR_MALFORMED; } MediaBuffer *buffer; status_t err = mGroup->acquire_buffer(&buffer); if (err != OK) { return err; } n = mDataSource->readAt(mOffset, buffer->data(), frameSize); if (n != (ssize_t)frameSize) { buffer->release(); buffer = NULL; if (n < 0) { return ERROR_IO; } else { mOffset += n; return ERROR_END_OF_STREAM; } } buffer->set_range(0, frameSize); buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs); buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); mOffset += frameSize; mCurrentTimeUs += 20000; // Each frame is 20ms *out = buffer; return OK; } Commit Message: Fix integer overflow and divide-by-zero Bug: 35763994 Test: ran CTS with and without fix Change-Id: If835e97ce578d4fa567e33e349e48fb7b2559e0e (cherry picked from commit 8538a603ef992e75f29336499cb783f3ec19f18c) CWE ID: CWE-190
status_t AMRSource::read( MediaBuffer **out, const ReadOptions *options) { *out = NULL; int64_t seekTimeUs; ReadOptions::SeekMode mode; if (mOffsetTableLength > 0 && options && options->getSeekTo(&seekTimeUs, &mode)) { size_t size; int64_t seekFrame = seekTimeUs / 20000ll; // 20ms per frame. mCurrentTimeUs = seekFrame * 20000ll; size_t index = seekFrame < 0 ? 0 : seekFrame / 50; if (index >= mOffsetTableLength) { index = mOffsetTableLength - 1; } mOffset = mOffsetTable[index] + (mIsWide ? 9 : 6); for (size_t i = 0; i< seekFrame - index * 50; i++) { status_t err; if ((err = getFrameSizeByOffset(mDataSource, mOffset, mIsWide, &size)) != OK) { return err; } mOffset += size; } } uint8_t header; ssize_t n = mDataSource->readAt(mOffset, &header, 1); if (n < 1) { return ERROR_END_OF_STREAM; } if (header & 0x83) { ALOGE("padding bits must be 0, header is 0x%02x", header); return ERROR_MALFORMED; } unsigned FT = (header >> 3) & 0x0f; size_t frameSize = getFrameSize(mIsWide, FT); if (frameSize == 0) { return ERROR_MALFORMED; } MediaBuffer *buffer; status_t err = mGroup->acquire_buffer(&buffer); if (err != OK) { return err; } n = mDataSource->readAt(mOffset, buffer->data(), frameSize); if (n != (ssize_t)frameSize) { buffer->release(); buffer = NULL; if (n < 0) { return ERROR_IO; } else { mOffset += n; return ERROR_END_OF_STREAM; } } buffer->set_range(0, frameSize); buffer->meta_data()->setInt64(kKeyTime, mCurrentTimeUs); buffer->meta_data()->setInt32(kKeyIsSyncFrame, 1); mOffset += frameSize; mCurrentTimeUs += 20000; // Each frame is 20ms *out = buffer; return OK; }
174,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 V8ContextNativeHandler::RunWithNativesEnabledModuleSystem( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsFunction()); v8::Local<v8::Value> call_with_args[] = { context()->module_system()->NewInstance()}; ModuleSystem::NativesEnabledScope natives_enabled(context()->module_system()); context()->CallFunction(v8::Local<v8::Function>::Cast(args[0]), 1, call_with_args); } Commit Message: Add a test that getModuleSystem() doesn't work cross origin BUG=504011 R=kalman@chromium.org TBR=fukino@chromium.org Review URL: https://codereview.chromium.org/1241443004 Cr-Commit-Position: refs/heads/master@{#338663} CWE ID: CWE-79
void V8ContextNativeHandler::RunWithNativesEnabledModuleSystem( void V8ContextNativeHandler::RunWithNativesEnabled( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK_EQ(args.Length(), 1); CHECK(args[0]->IsFunction()); ModuleSystem::NativesEnabledScope natives_enabled(context()->module_system()); context()->CallFunction(v8::Local<v8::Function>::Cast(args[0])); }
171,948
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CreateAuthenticatorFactory() { DCHECK(context_->network_task_runner()->BelongsToCurrentThread()); std::string local_certificate = key_pair_.GenerateCertificate(); if (local_certificate.empty()) { LOG(ERROR) << "Failed to generate host certificate."; Shutdown(kHostInitializationFailed); return; } scoped_ptr<protocol::AuthenticatorFactory> factory( new protocol::Me2MeHostAuthenticatorFactory( local_certificate, *key_pair_.private_key(), host_secret_hash_)); host_->SetAuthenticatorFactory(factory.Pass()); } Commit Message: Fix crash in CreateAuthenticatorFactory(). CreateAuthenticatorFactory() is called asynchronously, but it didn't handle the case when it's called after host object is destroyed. BUG=150644 Review URL: https://codereview.chromium.org/11090036 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161077 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void CreateAuthenticatorFactory() { DCHECK(context_->network_task_runner()->BelongsToCurrentThread()); if (!host_ || shutting_down_) return; std::string local_certificate = key_pair_.GenerateCertificate(); if (local_certificate.empty()) { LOG(ERROR) << "Failed to generate host certificate."; Shutdown(kHostInitializationFailed); return; } scoped_ptr<protocol::AuthenticatorFactory> factory( new protocol::Me2MeHostAuthenticatorFactory( local_certificate, *key_pair_.private_key(), host_secret_hash_)); host_->SetAuthenticatorFactory(factory.Pass()); }
171,338
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TabLifecycleUnitSource::TabLifecycleUnit::CanDiscard( DiscardReason reason, DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!tab_strip_model_) return false; const LifecycleUnitState target_state = reason == DiscardReason::kProactive && GetState() != LifecycleUnitState::FROZEN ? LifecycleUnitState::PENDING_DISCARD : LifecycleUnitState::DISCARDED; if (!IsValidStateChange(GetState(), target_state, DiscardReasonToStateChangeReason(reason))) { return false; } if (GetWebContents()->IsCrashed()) return false; if (!GetWebContents()->GetLastCommittedURL().is_valid() || GetWebContents()->GetLastCommittedURL().is_empty()) { return false; } if (discard_count_ > 0) { #if defined(OS_CHROMEOS) if (reason != DiscardReason::kUrgent) return false; #else return false; #endif // defined(OS_CHROMEOS) } #if defined(OS_CHROMEOS) if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #else if (tab_strip_model_->GetActiveWebContents() == GetWebContents()) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #endif // defined(OS_CHROMEOS) if (GetWebContents()->GetPageImportanceSignals().had_form_interaction) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_FORM_ENTRY); IsMediaTabImpl(decision_details); if (GetWebContents()->GetContentsMimeType() == "application/pdf") decision_details->AddReason(DecisionFailureReason::LIVE_STATE_IS_PDF); if (!IsAutoDiscardable()) { decision_details->AddReason( DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED); } if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); } Commit Message: Connect the LocalDB to TabManager. Bug: 773382 Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099 Reviewed-on: https://chromium-review.googlesource.com/1118611 Commit-Queue: Sébastien Marchand <sebmarchand@chromium.org> Reviewed-by: François Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#572871} CWE ID:
bool TabLifecycleUnitSource::TabLifecycleUnit::CanDiscard( DiscardReason reason, DecisionDetails* decision_details) const { DCHECK(decision_details->reasons().empty()); if (!tab_strip_model_) return false; const LifecycleUnitState target_state = reason == DiscardReason::kProactive && GetState() != LifecycleUnitState::FROZEN ? LifecycleUnitState::PENDING_DISCARD : LifecycleUnitState::DISCARDED; if (!IsValidStateChange(GetState(), target_state, DiscardReasonToStateChangeReason(reason))) { return false; } if (GetWebContents()->IsCrashed()) return false; if (!GetWebContents()->GetLastCommittedURL().is_valid() || GetWebContents()->GetLastCommittedURL().is_empty()) { return false; } if (discard_count_ > 0) { #if defined(OS_CHROMEOS) if (reason != DiscardReason::kUrgent) return false; #else return false; #endif // defined(OS_CHROMEOS) } #if defined(OS_CHROMEOS) if (GetWebContents()->GetVisibility() == content::Visibility::VISIBLE) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #else if (tab_strip_model_->GetActiveWebContents() == GetWebContents()) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_VISIBLE); #endif // defined(OS_CHROMEOS) if (GetWebContents()->GetPageImportanceSignals().had_form_interaction) decision_details->AddReason(DecisionFailureReason::LIVE_STATE_FORM_ENTRY); IsMediaTabImpl(decision_details); if (GetWebContents()->GetContentsMimeType() == "application/pdf") decision_details->AddReason(DecisionFailureReason::LIVE_STATE_IS_PDF); if (!IsAutoDiscardable()) { decision_details->AddReason( DecisionFailureReason::LIVE_STATE_EXTENSION_DISALLOWED); } // Consult the local database to see if this tab could try to communicate with // the user while in background (don't check for the visibility here as // there's already a check for that above). if (reason != DiscardReason::kUrgent) { CheckIfTabCanCommunicateWithUserWhileInBackground(GetWebContents(), decision_details); } if (decision_details->reasons().empty()) { decision_details->AddReason( DecisionSuccessReason::HEURISTIC_OBSERVED_TO_BE_SAFE); DCHECK(decision_details->IsPositive()); } return decision_details->IsPositive(); }
172,218
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uipc_read_task(void *arg) { int ch_id; int result; UNUSED(arg); prctl(PR_SET_NAME, (unsigned long)"uipc-main", 0, 0, 0); raise_priority_a2dp(TASK_UIPC_READ); while (uipc_main.running) { uipc_main.read_set = uipc_main.active_set; result = select(uipc_main.max_fd+1, &uipc_main.read_set, NULL, NULL, NULL); if (result == 0) { BTIF_TRACE_EVENT("select timeout"); continue; } else if (result < 0) { BTIF_TRACE_EVENT("select failed %s", strerror(errno)); continue; } UIPC_LOCK(); /* clear any wakeup interrupt */ uipc_check_interrupt_locked(); /* check pending task events */ uipc_check_task_flags_locked(); /* make sure we service audio channel first */ uipc_check_fd_locked(UIPC_CH_ID_AV_AUDIO); /* check for other connections */ for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++) { if (ch_id != UIPC_CH_ID_AV_AUDIO) uipc_check_fd_locked(ch_id); } UIPC_UNLOCK(); } BTIF_TRACE_EVENT("UIPC READ THREAD EXITING"); uipc_main_cleanup(); uipc_main.tid = 0; BTIF_TRACE_EVENT("UIPC READ THREAD DONE"); } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void uipc_read_task(void *arg) { int ch_id; int result; UNUSED(arg); prctl(PR_SET_NAME, (unsigned long)"uipc-main", 0, 0, 0); raise_priority_a2dp(TASK_UIPC_READ); while (uipc_main.running) { uipc_main.read_set = uipc_main.active_set; result = TEMP_FAILURE_RETRY(select(uipc_main.max_fd+1, &uipc_main.read_set, NULL, NULL, NULL)); if (result == 0) { BTIF_TRACE_EVENT("select timeout"); continue; } else if (result < 0) { BTIF_TRACE_EVENT("select failed %s", strerror(errno)); continue; } UIPC_LOCK(); /* clear any wakeup interrupt */ uipc_check_interrupt_locked(); /* check pending task events */ uipc_check_task_flags_locked(); /* make sure we service audio channel first */ uipc_check_fd_locked(UIPC_CH_ID_AV_AUDIO); /* check for other connections */ for (ch_id = 0; ch_id < UIPC_CH_NUM; ch_id++) { if (ch_id != UIPC_CH_ID_AV_AUDIO) uipc_check_fd_locked(ch_id); } UIPC_UNLOCK(); } BTIF_TRACE_EVENT("UIPC READ THREAD EXITING"); uipc_main_cleanup(); uipc_main.tid = 0; BTIF_TRACE_EVENT("UIPC READ THREAD DONE"); }
173,498
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gplotAddPlot(GPLOT *gplot, NUMA *nax, NUMA *nay, l_int32 plotstyle, const char *plottitle) { char buf[L_BUF_SIZE]; char emptystring[] = ""; char *datastr, *title; l_int32 n, i; l_float32 valx, valy, startx, delx; SARRAY *sa; PROCNAME("gplotAddPlot"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); if (!nay) return ERROR_INT("nay not defined", procName, 1); if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES) return ERROR_INT("invalid plotstyle", procName, 1); if ((n = numaGetCount(nay)) == 0) return ERROR_INT("no points to plot", procName, 1); if (nax && (n != numaGetCount(nax))) return ERROR_INT("nax and nay sizes differ", procName, 1); if (n == 1 && plotstyle == GPLOT_LINES) { L_INFO("only 1 pt; changing style to points\n", procName); plotstyle = GPLOT_POINTS; } /* Save plotstyle and plottitle */ numaGetParameters(nay, &startx, &delx); numaAddNumber(gplot->plotstyles, plotstyle); if (plottitle) { title = stringNew(plottitle); sarrayAddString(gplot->plottitles, title, L_INSERT); } else { sarrayAddString(gplot->plottitles, emptystring, L_COPY); } /* Generate and save data filename */ gplot->nplots++; snprintf(buf, L_BUF_SIZE, "%s.data.%d", gplot->rootname, gplot->nplots); sarrayAddString(gplot->datanames, buf, L_COPY); /* Generate data and save as a string */ sa = sarrayCreate(n); for (i = 0; i < n; i++) { if (nax) numaGetFValue(nax, i, &valx); else valx = startx + i * delx; numaGetFValue(nay, i, &valy); snprintf(buf, L_BUF_SIZE, "%f %f\n", valx, valy); sarrayAddString(sa, buf, L_COPY); } datastr = sarrayToString(sa, 0); sarrayAddString(gplot->plotdata, datastr, L_INSERT); sarrayDestroy(&sa); return 0; } Commit Message: Security fixes: expect final changes for release 1.75.3. * Fixed a debian security issue with fscanf() reading a string with possible buffer overflow. * There were also a few similar situations with sscanf(). CWE ID: CWE-119
gplotAddPlot(GPLOT *gplot, NUMA *nax, NUMA *nay, l_int32 plotstyle, const char *plottitle) { char buf[L_BUFSIZE]; char emptystring[] = ""; char *datastr, *title; l_int32 n, i; l_float32 valx, valy, startx, delx; SARRAY *sa; PROCNAME("gplotAddPlot"); if (!gplot) return ERROR_INT("gplot not defined", procName, 1); if (!nay) return ERROR_INT("nay not defined", procName, 1); if (plotstyle < 0 || plotstyle >= NUM_GPLOT_STYLES) return ERROR_INT("invalid plotstyle", procName, 1); if ((n = numaGetCount(nay)) == 0) return ERROR_INT("no points to plot", procName, 1); if (nax && (n != numaGetCount(nax))) return ERROR_INT("nax and nay sizes differ", procName, 1); if (n == 1 && plotstyle == GPLOT_LINES) { L_INFO("only 1 pt; changing style to points\n", procName); plotstyle = GPLOT_POINTS; } /* Save plotstyle and plottitle */ numaGetParameters(nay, &startx, &delx); numaAddNumber(gplot->plotstyles, plotstyle); if (plottitle) { title = stringNew(plottitle); sarrayAddString(gplot->plottitles, title, L_INSERT); } else { sarrayAddString(gplot->plottitles, emptystring, L_COPY); } /* Generate and save data filename */ gplot->nplots++; snprintf(buf, L_BUFSIZE, "%s.data.%d", gplot->rootname, gplot->nplots); sarrayAddString(gplot->datanames, buf, L_COPY); /* Generate data and save as a string */ sa = sarrayCreate(n); for (i = 0; i < n; i++) { if (nax) numaGetFValue(nax, i, &valx); else valx = startx + i * delx; numaGetFValue(nay, i, &valy); snprintf(buf, L_BUFSIZE, "%f %f\n", valx, valy); sarrayAddString(sa, buf, L_COPY); } datastr = sarrayToString(sa, 0); sarrayAddString(gplot->plotdata, datastr, L_INSERT); sarrayDestroy(&sa); return 0; }
169,323
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GpuProcessHost::OnProcessLaunched() { base::ProcessHandle child_handle = in_process_ ? base::GetCurrentProcessHandle() : process_->GetData().handle; #if defined(OS_WIN) DuplicateHandle(base::GetCurrentProcessHandle(), child_handle, base::GetCurrentProcessHandle(), &gpu_process_, PROCESS_DUP_HANDLE, FALSE, 0); #else gpu_process_ = child_handle; #endif UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); } 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:
void GpuProcessHost::OnProcessLaunched() { UMA_HISTOGRAM_TIMES("GPU.GPUProcessLaunchTime", base::TimeTicks::Now() - init_start_time_); }
170,923
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DevToolsWindow::InspectedContentsClosing() { web_contents_->GetRenderViewHost()->ClosePage(); } Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception This patch fixes the crash which happenes under the following conditions: 1. DevTools window is in undocked state 2. DevTools renderer is unresponsive 3. User attempts to close inspected page BUG=322380 Review URL: https://codereview.chromium.org/84883002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void DevToolsWindow::InspectedContentsClosing() { intercepted_page_beforeunload_ = false; web_contents_->GetRenderViewHost()->ClosePage(); }
171,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_transform_set_end(PNG_CONST image_transform *this, transform_display *that, png_structp pp, png_infop pi) { UNUSED(this) UNUSED(that) UNUSED(pp) UNUSED(pi) } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_set_end(PNG_CONST image_transform *this, image_transform_set_end(const image_transform *this, transform_display *that, png_structp pp, png_infop pi) { UNUSED(this) UNUSED(that) UNUSED(pp) UNUSED(pi) }
173,657
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DefragTrackerReuseTest(void) { int ret = 0; int id = 1; Packet *p1 = NULL; DefragTracker *tracker1 = NULL, *tracker2 = NULL; DefragInit(); /* Build a packet, its not a fragment but shouldn't matter for * this test. */ p1 = BuildTestPacket(id, 0, 0, 'A', 8); if (p1 == NULL) { goto end; } /* Get a tracker. It shouldn't look like its already in use. */ tracker1 = DefragGetTracker(NULL, NULL, p1); if (tracker1 == NULL) { goto end; } if (tracker1->seen_last) { goto end; } if (tracker1->remove) { goto end; } DefragTrackerRelease(tracker1); /* Get a tracker again, it should be the same one. */ tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 != tracker1) { goto end; } DefragTrackerRelease(tracker1); /* Now mark the tracker for removal. It should not be returned * when we get a tracker for a packet that may have the same * attributes. */ tracker1->remove = 1; tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 == tracker1) { goto end; } if (tracker2->remove) { goto end; } ret = 1; end: if (p1 != NULL) { SCFree(p1); } DefragDestroy(); return ret; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
static int DefragTrackerReuseTest(void) { int ret = 0; int id = 1; Packet *p1 = NULL; DefragTracker *tracker1 = NULL, *tracker2 = NULL; DefragInit(); /* Build a packet, its not a fragment but shouldn't matter for * this test. */ p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 0, 'A', 8); if (p1 == NULL) { goto end; } /* Get a tracker. It shouldn't look like its already in use. */ tracker1 = DefragGetTracker(NULL, NULL, p1); if (tracker1 == NULL) { goto end; } if (tracker1->seen_last) { goto end; } if (tracker1->remove) { goto end; } DefragTrackerRelease(tracker1); /* Get a tracker again, it should be the same one. */ tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 != tracker1) { goto end; } DefragTrackerRelease(tracker1); /* Now mark the tracker for removal. It should not be returned * when we get a tracker for a packet that may have the same * attributes. */ tracker1->remove = 1; tracker2 = DefragGetTracker(NULL, NULL, p1); if (tracker2 == NULL) { goto end; } if (tracker2 == tracker1) { goto end; } if (tracker2->remove) { goto end; } ret = 1; end: if (p1 != NULL) { SCFree(p1); } DefragDestroy(); return ret; }
168,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 LockContentsView::OnUsersChanged( const std::vector<mojom::LoginUserInfoPtr>& users) { main_view_->RemoveAllChildViews(true /*delete_children*/); opt_secondary_big_view_ = nullptr; users_list_ = nullptr; rotation_actions_.clear(); users_.clear(); if (users.empty()) { LOG_IF(FATAL, screen_type_ != LockScreen::ScreenType::kLogin) << "Empty user list received"; Shell::Get()->login_screen_controller()->ShowGaiaSignin( false /*can_close*/, base::nullopt /*prefilled_account*/); return; } for (const mojom::LoginUserInfoPtr& user : users) { UserState state(user->basic_user_info->account_id); state.fingerprint_state = user->allow_fingerprint_unlock ? mojom::FingerprintUnlockState::AVAILABLE : mojom::FingerprintUnlockState::UNAVAILABLE; users_.push_back(std::move(state)); } auto box_layout = std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal); main_layout_ = box_layout.get(); main_layout_->set_main_axis_alignment( views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); main_layout_->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); main_view_->SetLayoutManager(std::move(box_layout)); primary_big_view_ = AllocateLoginBigUserView(users[0], true /*is_primary*/); main_view_->AddChildView(primary_big_view_); if (users.size() == 2) CreateLowDensityLayout(users); else if (users.size() >= 3 && users.size() <= 6) CreateMediumDensityLayout(users); else if (users.size() >= 7) CreateHighDensityLayout(users); LayoutAuth(primary_big_view_, opt_secondary_big_view_, false /*animate*/); OnBigUserChanged(); PreferredSizeChanged(); Layout(); } Commit Message: cros: Check initial auth type when showing views login. Bug: 859611 Change-Id: I0298db9bbf4aed6bd40600aef2e1c5794e8cd058 Reviewed-on: https://chromium-review.googlesource.com/1123056 Reviewed-by: Xiaoyin Hu <xiaoyinh@chromium.org> Commit-Queue: Jacob Dufault <jdufault@chromium.org> Cr-Commit-Position: refs/heads/master@{#572224} CWE ID:
void LockContentsView::OnUsersChanged( const std::vector<mojom::LoginUserInfoPtr>& users) { main_view_->RemoveAllChildViews(true /*delete_children*/); opt_secondary_big_view_ = nullptr; users_list_ = nullptr; rotation_actions_.clear(); users_.clear(); if (users.empty()) { LOG_IF(FATAL, screen_type_ != LockScreen::ScreenType::kLogin) << "Empty user list received"; Shell::Get()->login_screen_controller()->ShowGaiaSignin( false /*can_close*/, base::nullopt /*prefilled_account*/); return; } for (const mojom::LoginUserInfoPtr& user : users) users_.push_back(UserState(user)); auto box_layout = std::make_unique<views::BoxLayout>(views::BoxLayout::kHorizontal); main_layout_ = box_layout.get(); main_layout_->set_main_axis_alignment( views::BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); main_layout_->set_cross_axis_alignment( views::BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); main_view_->SetLayoutManager(std::move(box_layout)); primary_big_view_ = AllocateLoginBigUserView(users[0], true /*is_primary*/); main_view_->AddChildView(primary_big_view_); if (users.size() == 2) CreateLowDensityLayout(users); else if (users.size() >= 3 && users.size() <= 6) CreateMediumDensityLayout(users); else if (users.size() >= 7) CreateHighDensityLayout(users); LayoutAuth(primary_big_view_, opt_secondary_big_view_, false /*animate*/); OnBigUserChanged(); PreferredSizeChanged(); Layout(); }
172,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (is_swapped_out_) { if (request.url() != GURL("about:swappedout")) return WebKit::WebNavigationPolicyIgnore; return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (frame_url.GetOrigin() != url.GetOrigin()) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_top_level_requests = renderer_preferences_.browser_handles_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (browser_handles_top_level_requests || renderer_preferences_.browser_handles_all_requests) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool should_fork = content::GetContentClient()->HasWebUIScheme(url) || (cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || frame->isViewSourceModeEnabled(); if (!should_fork) { if (request.httpMethod() == "GET") { bool is_initial_navigation = page_id_ == -1; should_fork = content::GetContentClient()->renderer()->ShouldFork( frame, url, is_initial_navigation, &send_referrer); } } if (should_fork) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; } Commit Message: Use a new scheme for swapping out RenderViews. BUG=118664 TEST=none Review URL: http://codereview.chromium.org/9720004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation( WebFrame* frame, const WebURLRequest& request, WebNavigationType type, const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) { if (is_swapped_out_) { if (request.url() != GURL(chrome::kSwappedOutURL)) return WebKit::WebNavigationPolicyIgnore; // Allow chrome::kSwappedOutURL to complete. return default_policy; } const GURL& url = request.url(); bool is_content_initiated = DocumentState::FromDataSource(frame->provisionalDataSource())-> navigation_state()->is_content_initiated(); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) && !frame->parent() && (is_content_initiated || is_redirect)) { WebString origin_str = frame->document().securityOrigin().toString(); GURL frame_url(origin_str.utf8().data()); if (frame_url.GetOrigin() != url.GetOrigin()) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; } } if (is_content_initiated) { bool browser_handles_top_level_requests = renderer_preferences_.browser_handles_top_level_requests && IsNonLocalTopLevelNavigation(url, frame, type); if (browser_handles_top_level_requests || renderer_preferences_.browser_handles_all_requests) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); page_id_ = -1; last_page_id_sent_to_browser_ = -1; OpenURL(frame, url, referrer, default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } if (!frame->parent() && is_content_initiated && !url.SchemeIs(chrome::kAboutScheme)) { bool send_referrer = false; int cumulative_bindings = RenderProcess::current()->GetEnabledBindings(); bool should_fork = content::GetContentClient()->HasWebUIScheme(url) || (cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) || url.SchemeIs(chrome::kViewSourceScheme) || frame->isViewSourceModeEnabled(); if (!should_fork) { if (request.httpMethod() == "GET") { bool is_initial_navigation = page_id_ == -1; should_fork = content::GetContentClient()->renderer()->ShouldFork( frame, url, is_initial_navigation, &send_referrer); } } if (should_fork) { Referrer referrer( GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))), GetReferrerPolicyFromRequest(request)); OpenURL( frame, url, send_referrer ? referrer : Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; // Suppress the load here. } } GURL old_url(frame->dataSource()->request().url()); bool is_fork = old_url == GURL(chrome::kAboutBlankURL) && historyBackListCount() < 1 && historyForwardListCount() < 1 && frame->opener() == NULL && frame->parent() == NULL && is_content_initiated && default_policy == WebKit::WebNavigationPolicyCurrentTab && type == WebKit::WebNavigationTypeOther; if (is_fork) { OpenURL(frame, url, Referrer(), default_policy); return WebKit::WebNavigationPolicyIgnore; } return default_policy; }
171,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: void RenderParamsFromPrintSettings(const PrintSettings& settings, PrintMsg_Print_Params* params) { params->page_size = settings.page_setup_device_units().physical_size(); params->content_size.SetSize( settings.page_setup_device_units().content_area().width(), settings.page_setup_device_units().content_area().height()); params->printable_area.SetRect( settings.page_setup_device_units().printable_area().x(), settings.page_setup_device_units().printable_area().y(), settings.page_setup_device_units().printable_area().width(), settings.page_setup_device_units().printable_area().height()); params->margin_top = settings.page_setup_device_units().content_area().y(); params->margin_left = settings.page_setup_device_units().content_area().x(); params->dpi = settings.dpi(); params->scale_factor = settings.scale_factor(); params->rasterize_pdf = settings.rasterize_pdf(); params->document_cookie = 0; params->selection_only = settings.selection_only(); params->supports_alpha_blend = settings.supports_alpha_blend(); params->should_print_backgrounds = settings.should_print_backgrounds(); params->display_header_footer = settings.display_header_footer(); params->title = settings.title(); params->url = settings.url(); params->printed_doc_type = SkiaDocumentType::PDF; } 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
void RenderParamsFromPrintSettings(const PrintSettings& settings, PrintMsg_Print_Params* params) { params->page_size = settings.page_setup_device_units().physical_size(); params->content_size.SetSize( settings.page_setup_device_units().content_area().width(), settings.page_setup_device_units().content_area().height()); params->printable_area.SetRect( settings.page_setup_device_units().printable_area().x(), settings.page_setup_device_units().printable_area().y(), settings.page_setup_device_units().printable_area().width(), settings.page_setup_device_units().printable_area().height()); params->margin_top = settings.page_setup_device_units().content_area().y(); params->margin_left = settings.page_setup_device_units().content_area().x(); params->dpi = settings.dpi(); params->scale_factor = settings.scale_factor(); params->rasterize_pdf = settings.rasterize_pdf(); params->document_cookie = 0; params->selection_only = settings.selection_only(); params->supports_alpha_blend = settings.supports_alpha_blend(); params->should_print_backgrounds = settings.should_print_backgrounds(); params->display_header_footer = settings.display_header_footer(); params->title = settings.title(); params->url = settings.url(); params->printed_doc_type = IsOopifEnabled() ? SkiaDocumentType::MSKP : SkiaDocumentType::PDF; }
171,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool( ResourceProvider* resource_provider, ContextProvider* context_provider, size_t num_threads, size_t max_transfer_buffer_usage_bytes) : RasterWorkerPool(resource_provider, context_provider, num_threads), shutdown_(false), scheduled_raster_task_count_(0), bytes_pending_upload_(0), max_bytes_pending_upload_(max_transfer_buffer_usage_bytes), has_performed_uploads_since_last_flush_(false), check_for_completed_raster_tasks_pending_(false), should_notify_client_if_no_tasks_are_pending_(false), should_notify_client_if_no_tasks_required_for_activation_are_pending_( false) { } Commit Message: cc: Simplify raster task completion notification logic (Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/) Previously the pixel buffer raster worker pool used a combination of polling and explicit notifications from the raster worker pool to decide when to tell the client about the completion of 1) all tasks or 2) the subset of tasks required for activation. This patch simplifies the logic by only triggering the notification based on the OnRasterTasksFinished and OnRasterTasksRequiredForActivationFinished calls from the worker pool. BUG=307841,331534 Review URL: https://codereview.chromium.org/99873007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
PixelBufferRasterWorkerPool::PixelBufferRasterWorkerPool( ResourceProvider* resource_provider, ContextProvider* context_provider, size_t num_threads, size_t max_transfer_buffer_usage_bytes) : RasterWorkerPool(resource_provider, context_provider, num_threads), shutdown_(false), scheduled_raster_task_count_(0), bytes_pending_upload_(0), max_bytes_pending_upload_(max_transfer_buffer_usage_bytes), has_performed_uploads_since_last_flush_(false), check_for_completed_raster_tasks_pending_(false), should_notify_client_if_no_tasks_are_pending_(false), should_notify_client_if_no_tasks_required_for_activation_are_pending_( false), raster_finished_task_pending_(false), raster_required_for_activation_finished_task_pending_(false) { }
171,262
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uhid_write(int fd, const struct uhid_event *ev) { ssize_t ret = write(fd, ev, sizeof(*ev)); if (ret < 0){ int rtn = -errno; APPL_TRACE_ERROR("%s: Cannot write to uhid:%s", __FUNCTION__, strerror(errno)); return rtn; } else if (ret != (ssize_t)sizeof(*ev)) { APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu", __FUNCTION__, ret, sizeof(*ev)); return -EFAULT; } return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int uhid_write(int fd, const struct uhid_event *ev) { ssize_t ret = TEMP_FAILURE_RETRY(write(fd, ev, sizeof(*ev))); if (ret < 0){ int rtn = -errno; APPL_TRACE_ERROR("%s: Cannot write to uhid:%s", __FUNCTION__, strerror(errno)); return rtn; } else if (ret != (ssize_t)sizeof(*ev)) { APPL_TRACE_ERROR("%s: Wrong size written to uhid: %zd != %zu", __FUNCTION__, ret, sizeof(*ev)); return -EFAULT; } return 0; }
173,433
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_ecb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_ecb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); }
167,108
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 main(int argc, char *argv[]) { struct mschm_decompressor *chmd; struct mschmd_header *chm; struct mschmd_file *file, **f; unsigned int numf, i; setbuf(stdout, NULL); setbuf(stderr, NULL); user_umask = umask(0); umask(user_umask); MSPACK_SYS_SELFTEST(i); if (i) return 0; if ((chmd = mspack_create_chm_decompressor(NULL))) { for (argv++; *argv; argv++) { printf("%s\n", *argv); if ((chm = chmd->open(chmd, *argv))) { /* build an ordered list of files for maximum extraction speed */ for (numf=0, file=chm->files; file; file = file->next) numf++; if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) { for (i=0, file=chm->files; file; file = file->next) f[i++] = file; qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc); for (i = 0; i < numf; i++) { char *outname = create_output_name((unsigned char *)f[i]->filename,NULL,0,1,0); printf("Extracting %s\n", outname); ensure_filepath(outname); if (chmd->extract(chmd, f[i], outname)) { printf("%s: extract error on \"%s\": %s\n", *argv, f[i]->filename, ERROR(chmd)); } free(outname); } free(f); } chmd->close(chmd, chm); } else { printf("%s: can't open -- %s\n", *argv, ERROR(chmd)); } } mspack_destroy_chm_decompressor(chmd); } return 0; } Commit Message: add anti "../" and leading slash protection to chmextract CWE ID: CWE-22
int main(int argc, char *argv[]) { struct mschm_decompressor *chmd; struct mschmd_header *chm; struct mschmd_file *file, **f; unsigned int numf, i; setbuf(stdout, NULL); setbuf(stderr, NULL); user_umask = umask(0); umask(user_umask); MSPACK_SYS_SELFTEST(i); if (i) return 0; if ((chmd = mspack_create_chm_decompressor(NULL))) { for (argv++; *argv; argv++) { printf("%s\n", *argv); if ((chm = chmd->open(chmd, *argv))) { /* build an ordered list of files for maximum extraction speed */ for (numf=0, file=chm->files; file; file = file->next) numf++; if ((f = (struct mschmd_file **) calloc(numf, sizeof(struct mschmd_file *)))) { for (i=0, file=chm->files; file; file = file->next) f[i++] = file; qsort(f, numf, sizeof(struct mschmd_file *), &sortfunc); for (i = 0; i < numf; i++) { char *outname = create_output_name(f[i]->filename); printf("Extracting %s\n", outname); ensure_filepath(outname); if (chmd->extract(chmd, f[i], outname)) { printf("%s: extract error on \"%s\": %s\n", *argv, f[i]->filename, ERROR(chmd)); } free(outname); } free(f); } chmd->close(chmd, chm); } else { printf("%s: can't open -- %s\n", *argv, ERROR(chmd)); } } mspack_destroy_chm_decompressor(chmd); } return 0; }
169,002
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SelectionInDOMTree ConvertToSelectionInDOMTree( const SelectionInFlatTree& selection_in_flat_tree) { return SelectionInDOMTree::Builder() .SetAffinity(selection_in_flat_tree.Affinity()) .SetBaseAndExtent(ToPositionInDOMTree(selection_in_flat_tree.Base()), ToPositionInDOMTree(selection_in_flat_tree.Extent())) .SetIsDirectional(selection_in_flat_tree.IsDirectional()) .SetIsHandleVisible(selection_in_flat_tree.IsHandleVisible()) .Build(); } 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
SelectionInDOMTree ConvertToSelectionInDOMTree( const SelectionInFlatTree& selection_in_flat_tree) { return SelectionInDOMTree::Builder() .SetAffinity(selection_in_flat_tree.Affinity()) .SetBaseAndExtent(ToPositionInDOMTree(selection_in_flat_tree.Base()), ToPositionInDOMTree(selection_in_flat_tree.Extent())) .SetIsDirectional(selection_in_flat_tree.IsDirectional()) .Build(); }
171,762
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CrosLibrary::TestApi::SetScreenLockLibrary( ScreenLockLibrary* library, bool own) { library_->screen_lock_lib_.SetImpl(library, own); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
void CrosLibrary::TestApi::SetScreenLockLibrary(
170,644
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() { return keyboard_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
KeyboardLibrary* CrosLibrary::GetKeyboardLibrary() {
170,624
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev1_sig_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len _U_, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi _U_, uint32_t proto _U_, int depth _U_) { struct isakmp_gen e; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_SIG))); ND_TCHECK(*ext); UNALIGNED_MEMCPY(&e, ext, sizeof(e)); ND_PRINT((ndo," len=%d", ntohs(e.len) - 4)); if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4)) goto trunc; } return (const u_char *)ext + ntohs(e.len); trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_SIG))); return NULL; }
167,793
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Response StorageHandler::UntrackIndexedDBForOrigin(const std::string& origin) { if (!process_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::UntrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); } 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
Response StorageHandler::UntrackIndexedDBForOrigin(const std::string& origin) { if (!storage_partition_) return Response::InternalError(); GURL origin_url(origin); if (!origin_url.is_valid()) return Response::InvalidParams(origin + " is not a valid URL"); GetIndexedDBObserver()->TaskRunner()->PostTask( FROM_HERE, base::BindOnce(&IndexedDBObserver::UntrackOriginOnIDBThread, base::Unretained(GetIndexedDBObserver()), url::Origin::Create(origin_url))); return Response::OK(); }
172,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: g_NPN_GetValue(NPP instance, NPNVariable variable, void *value) { D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable))); if (!thread_check()) { npw_printf("WARNING: NPN_GetValue not called from the main thread\n"); return NPERR_INVALID_INSTANCE_ERROR; } PluginInstance *plugin = NULL; if (instance) plugin = PLUGIN_INSTANCE(instance); switch (variable) { case NPNVxDisplay: *(void **)value = x_display; break; case NPNVxtAppContext: *(void **)value = XtDisplayToApplicationContext(x_display); break; case NPNVToolkit: *(NPNToolkitType *)value = NPW_TOOLKIT; break; #if USE_XPCOM case NPNVserviceManager: { nsIServiceManager *sm; int ret = NS_GetServiceManager(&sm); if (NS_FAILED(ret)) { npw_printf("WARNING: NS_GetServiceManager failed\n"); return NPERR_GENERIC_ERROR; } *(nsIServiceManager **)value = sm; break; } case NPNVDOMWindow: case NPNVDOMElement: npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable)); return NPERR_INVALID_PARAM; #endif case NPNVnetscapeWindow: if (plugin == NULL) { npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n"); return NPERR_INVALID_INSTANCE_ERROR; } if (plugin->browser_toplevel == NULL) { GdkNativeWindow netscape_xid = None; NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid); if (error != NPERR_NO_ERROR) return error; if (netscape_xid == None) return NPERR_GENERIC_ERROR; plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid); if (plugin->browser_toplevel == NULL) return NPERR_GENERIC_ERROR; } *((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel); break; #if ALLOW_WINDOWLESS_PLUGINS case NPNVSupportsWindowless: #endif case NPNVSupportsXEmbedBool: case NPNVWindowNPObject: case NPNVPluginElementNPObject: return g_NPN_GetValue_real(instance, variable, value); default: switch (variable & 0xff) { case 13: /* NPNVToolkit */ if (NPW_TOOLKIT == NPNVGtk2) { *(NPNToolkitType *)value = NPW_TOOLKIT; return NPERR_NO_ERROR; } break; } D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable))); return NPERR_INVALID_PARAM; } return NPERR_NO_ERROR; } Commit Message: Support all the new variables added CWE ID: CWE-264
g_NPN_GetValue(NPP instance, NPNVariable variable, void *value) { D(bug("NPN_GetValue instance=%p, variable=%d [%s]\n", instance, variable, string_of_NPNVariable(variable))); if (!thread_check()) { npw_printf("WARNING: NPN_GetValue not called from the main thread\n"); return NPERR_INVALID_INSTANCE_ERROR; } PluginInstance *plugin = NULL; if (instance) plugin = PLUGIN_INSTANCE(instance); switch (variable) { case NPNVxDisplay: *(void **)value = x_display; break; case NPNVxtAppContext: *(void **)value = XtDisplayToApplicationContext(x_display); break; case NPNVToolkit: *(NPNToolkitType *)value = NPW_TOOLKIT; break; #if USE_XPCOM case NPNVserviceManager: { nsIServiceManager *sm; int ret = NS_GetServiceManager(&sm); if (NS_FAILED(ret)) { npw_printf("WARNING: NS_GetServiceManager failed\n"); return NPERR_GENERIC_ERROR; } *(nsIServiceManager **)value = sm; break; } case NPNVDOMWindow: case NPNVDOMElement: npw_printf("WARNING: %s is not supported by NPN_GetValue()\n", string_of_NPNVariable(variable)); return NPERR_INVALID_PARAM; #endif case NPNVnetscapeWindow: if (plugin == NULL) { npw_printf("ERROR: NPNVnetscapeWindow requires a non NULL instance\n"); return NPERR_INVALID_INSTANCE_ERROR; } if (plugin->browser_toplevel == NULL) { GdkNativeWindow netscape_xid = None; NPError error = g_NPN_GetValue_real(instance, variable, &netscape_xid); if (error != NPERR_NO_ERROR) return error; if (netscape_xid == None) return NPERR_GENERIC_ERROR; plugin->browser_toplevel = gdk_window_foreign_new(netscape_xid); if (plugin->browser_toplevel == NULL) return NPERR_GENERIC_ERROR; } *((GdkNativeWindow *)value) = GDK_WINDOW_XWINDOW(plugin->browser_toplevel); break; #if ALLOW_WINDOWLESS_PLUGINS case NPNVSupportsWindowless: #endif case NPNVSupportsXEmbedBool: case NPNVWindowNPObject: case NPNVPluginElementNPObject: case NPNVprivateModeBool: case NPNVsupportsAdvancedKeyHandling: return g_NPN_GetValue_real(instance, variable, value); default: switch (variable & 0xff) { case 13: /* NPNVToolkit */ if (NPW_TOOLKIT == NPNVGtk2) { *(NPNToolkitType *)value = NPW_TOOLKIT; return NPERR_NO_ERROR; } break; } D(bug("WARNING: unhandled variable %d (%s) in NPN_GetValue()\n", variable, string_of_NPNVariable(variable))); return NPERR_INVALID_PARAM; } return NPERR_NO_ERROR; }
165,864
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Track::Info::Copy(Info& dst) const { if (&dst == this) return 0; dst.type = type; dst.number = number; dst.defaultDuration = defaultDuration; dst.codecDelay = codecDelay; dst.seekPreRoll = seekPreRoll; dst.uid = uid; dst.lacing = lacing; dst.settings = settings; if (int status = CopyStr(&Info::nameAsUTF8, dst)) return status; if (int status = CopyStr(&Info::language, dst)) return status; if (int status = CopyStr(&Info::codecId, dst)) return status; if (int status = CopyStr(&Info::codecNameAsUTF8, dst)) return status; if (codecPrivateSize > 0) { if (codecPrivate == NULL) return -1; if (dst.codecPrivate) return -1; if (dst.codecPrivateSize != 0) return -1; dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize]; if (dst.codecPrivate == NULL) return -1; memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize); dst.codecPrivateSize = codecPrivateSize; } return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
int Track::Info::Copy(Info& dst) const { if (&dst == this) return 0; dst.type = type; dst.number = number; dst.defaultDuration = defaultDuration; dst.codecDelay = codecDelay; dst.seekPreRoll = seekPreRoll; dst.uid = uid; dst.lacing = lacing; dst.settings = settings; if (int status = CopyStr(&Info::nameAsUTF8, dst)) return status; if (int status = CopyStr(&Info::language, dst)) return status; if (int status = CopyStr(&Info::codecId, dst)) return status; if (int status = CopyStr(&Info::codecNameAsUTF8, dst)) return status; if (codecPrivateSize > 0) { if (codecPrivate == NULL) return -1; if (dst.codecPrivate) return -1; if (dst.codecPrivateSize != 0) return -1; dst.codecPrivate = SafeArrayAlloc<unsigned char>(1, codecPrivateSize); if (dst.codecPrivate == NULL) return -1; memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize); dst.codecPrivateSize = codecPrivateSize; } return 0; }
173,802
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BufferMeta(size_t size, OMX_U32 portIndex) : mSize(size), mIsBackup(false), mPortIndex(portIndex) { } Commit Message: DO NOT MERGE: IOMX: work against metadata buffer spoofing - Prohibit direct set/getParam/Settings for extensions meant for OMXNodeInstance alone. This disallows enabling metadata mode without the knowledge of OMXNodeInstance. - Use a backup buffer for metadata mode buffers and do not directly share with clients. - Disallow setting up metadata mode/tunneling/input surface after first sendCommand. - Disallow store-meta for input cross process. - Disallow emptyBuffer for surface input (via IOMX). - Fix checking for input surface. Bug: 29422020 Change-Id: I801c77b80e703903f62e42d76fd2e76a34e4bc8e (cherry picked from commit 7c3c2fa3e233c656fc8c2fc2a6634b3ecf8a23e8) CWE ID: CWE-200
BufferMeta(size_t size, OMX_U32 portIndex) : mSize(size), mCopyFromOmx(false), mCopyToOmx(false), mPortIndex(portIndex), mBackup(NULL) { }
174,125
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; upperdentry = ovl_dentry_upper(dentry); if (upperdentry) { mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } else { err = ovl_copy_up_last(dentry, attr, false); } ovl_drop_write(dentry); out: return err; } Commit Message: ovl: fix permission checking for setattr [Al Viro] The bug is in being too enthusiastic about optimizing ->setattr() away - instead of "copy verbatim with metadata" + "chmod/chown/utimes" (with the former being always safe and the latter failing in case of insufficient permissions) it tries to combine these two. Note that copyup itself will have to do ->setattr() anyway; _that_ is where the elevated capabilities are right. Having these two ->setattr() (one to set verbatim copy of metadata, another to do what overlayfs ->setattr() had been asked to do in the first place) combined is where it breaks. Signed-off-by: Miklos Szeredi <miklos@szeredi.hu> Cc: <stable@vger.kernel.org> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-264
int ovl_setattr(struct dentry *dentry, struct iattr *attr) { int err; struct dentry *upperdentry; err = ovl_want_write(dentry); if (err) goto out; err = ovl_copy_up(dentry); if (!err) { upperdentry = ovl_dentry_upper(dentry); mutex_lock(&upperdentry->d_inode->i_mutex); err = notify_change(upperdentry, attr, NULL); mutex_unlock(&upperdentry->d_inode->i_mutex); } ovl_drop_write(dentry); out: return err; }
166,559
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); pitch_ = 16; fwd_txfm_ref = fdct16x16_ref; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void SetUp() { fwd_txfm_ = GET_PARAM(0); inv_txfm_ = GET_PARAM(1); tx_type_ = GET_PARAM(2); bit_depth_ = GET_PARAM(3); pitch_ = 16; fwd_txfm_ref = fdct16x16_ref; inv_txfm_ref = idct16x16_ref; mask_ = (1 << bit_depth_) - 1; #if CONFIG_VP9_HIGHBITDEPTH switch (bit_depth_) { case VPX_BITS_10: inv_txfm_ref = idct16x16_10_ref; break; case VPX_BITS_12: inv_txfm_ref = idct16x16_12_ref; break; default: inv_txfm_ref = idct16x16_ref; break; } #else inv_txfm_ref = idct16x16_ref; #endif }
174,527
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 insert_pin( sc_pkcs15_card_t *p15card, const char *path, unsigned char id, unsigned char auth_id, unsigned char pin_reference, int min_length, const char *label, int pin_flags ){ sc_card_t *card=p15card->card; sc_context_t *ctx=p15card->card->ctx; sc_file_t *f; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; int r; memset(&pin_info, 0, sizeof(pin_info)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = id; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = pin_reference; pin_info.attrs.pin.flags = pin_flags; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = min_length; pin_info.attrs.pin.stored_length = 16; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.logged_in = SC_PIN_STATE_UNKNOWN; sc_format_path(path, &pin_info.path); memset(&pin_obj, 0, sizeof(pin_obj)); strlcpy(pin_obj.label, label, sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE; pin_obj.auth_id.len = auth_id ? 0 : 1; pin_obj.auth_id.value[0] = auth_id; if(card->type==SC_CARD_TYPE_TCOS_V3){ unsigned char buf[256]; int i, rec_no=0; if(pin_info.path.len>=2) pin_info.path.len-=2; sc_append_file_id(&pin_info.path, 0x5049); if(sc_select_file(card, &pin_info.path, NULL)!=SC_SUCCESS){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Select(%s) failed\n", sc_print_path(&pin_info.path)); return 1; } sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Searching for PIN-Ref %02X\n", pin_reference); while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){ int found=0, fbz=-1; if(buf[0]!=0xA0) continue; for(i=2;i<buf[1]+2;i+=2+buf[i+1]){ if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==pin_reference) ++found; if(buf[i]==0x90) fbz=buf[i+1+buf[i+1]]; } if(found) pin_info.tries_left=fbz; if(found) break; } if(r<=0){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_PWDD-Record found\n"); return 1; } } else { if(sc_select_file(card, &pin_info.path, &f)!=SC_SUCCESS){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"Select(%s) failed\n", path); return 1; } pin_info.tries_left=f->prop_attr[3]; sc_file_free(f); } r=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if(r!=SC_SUCCESS){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_pin_obj(%s) failed\n", path); return 4; } sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, FBZ=%d\n", path, pin_info.tries_left); return 0; } Commit Message: fixed out of bounds reads Thanks to Eric Sesterhenn from X41 D-SEC GmbH for reporting and suggesting security fixes. CWE ID: CWE-125
static int insert_pin( sc_pkcs15_card_t *p15card, const char *path, unsigned char id, unsigned char auth_id, unsigned char pin_reference, int min_length, const char *label, int pin_flags ){ sc_card_t *card=p15card->card; sc_context_t *ctx=p15card->card->ctx; sc_file_t *f; struct sc_pkcs15_auth_info pin_info; struct sc_pkcs15_object pin_obj; int r; memset(&pin_info, 0, sizeof(pin_info)); pin_info.auth_id.len = 1; pin_info.auth_id.value[0] = id; pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN; pin_info.attrs.pin.reference = pin_reference; pin_info.attrs.pin.flags = pin_flags; pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC; pin_info.attrs.pin.min_length = min_length; pin_info.attrs.pin.stored_length = 16; pin_info.attrs.pin.max_length = 16; pin_info.attrs.pin.pad_char = '\0'; pin_info.logged_in = SC_PIN_STATE_UNKNOWN; sc_format_path(path, &pin_info.path); memset(&pin_obj, 0, sizeof(pin_obj)); strlcpy(pin_obj.label, label, sizeof(pin_obj.label)); pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE; pin_obj.auth_id.len = auth_id ? 0 : 1; pin_obj.auth_id.value[0] = auth_id; if(card->type==SC_CARD_TYPE_TCOS_V3){ unsigned char buf[256]; int i, rec_no=0; if(pin_info.path.len>=2) pin_info.path.len-=2; sc_append_file_id(&pin_info.path, 0x5049); if(sc_select_file(card, &pin_info.path, NULL)!=SC_SUCCESS){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Select(%s) failed\n", sc_print_path(&pin_info.path)); return 1; } sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "Searching for PIN-Ref %02X\n", pin_reference); while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){ int found=0, fbz=-1; if(buf[0]!=0xA0) continue; for(i=2;i<buf[1]+2;i+=2+buf[i+1]){ if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==pin_reference) ++found; if(buf[i]==0x90) fbz=buf[i+1+buf[i+1]]; } if(found) pin_info.tries_left=fbz; if(found) break; } if(r<=0){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_PWDD-Record found\n"); return 1; } } else { if(sc_select_file(card, &pin_info.path, &f)!=SC_SUCCESS || !f->prop_attr || f->prop_attr_len < 4){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"Select(%s) failed\n", path); return 1; } pin_info.tries_left=f->prop_attr[3]; sc_file_free(f); } r=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info); if(r!=SC_SUCCESS){ sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_pin_obj(%s) failed\n", path); return 4; } sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, FBZ=%d\n", path, pin_info.tries_left); return 0; }
169,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; mrb_value value; fiber_check_cfunc(mrb, c); if (resume && c->status == MRB_FIBER_TRANSFERRED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)"); } if (c->status == MRB_FIBER_TERMINATED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); } mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); if (c->status == MRB_FIBER_CREATED) { mrb_value *b, *e; if (len >= c->stend - c->stack) { mrb_raise(mrb, E_FIBER_ERROR, "too many arguments to fiber"); } b = c->stack+1; e = b + len; while (b<e) { *b++ = *a++; } c->cibase->argc = (int)len; value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); } fiber_switch_context(mrb, c); if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; } Commit Message: Extend stack when pushing arguments that does not fit in; fix #4038 CWE ID: CWE-125
fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec) { struct mrb_context *c = fiber_check(mrb, self); struct mrb_context *old_c = mrb->c; enum mrb_fiber_state status; mrb_value value; fiber_check_cfunc(mrb, c); status = c->status; if (resume && status == MRB_FIBER_TRANSFERRED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber"); } if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) { mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)"); } if (status == MRB_FIBER_TERMINATED) { mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber"); } old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED; c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c); fiber_switch_context(mrb, c); if (status == MRB_FIBER_CREATED) { mrb_value *b, *e; mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */ b = c->stack+1; e = b + len; while (b<e) { *b++ = *a++; } c->cibase->argc = (int)len; value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0]; } else { value = fiber_result(mrb, a, len); } if (vmexec) { c->vmexec = TRUE; value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc); mrb->c = old_c; } else { MARK_CONTEXT_MODIFY(c); } return value; }
169,201
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; uid_t check_ruid; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) { rc = -EPERM; printk(KERN_ERR "Mount of device (uid: %d) not owned by " "requested user (uid: %d)\n", i_uid_read(path.dentry->d_inode), from_kuid(&init_user_ns, current_uid())); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); /** * Set the POSIX ACL flag based on whether they're enabled in the lower * mount. Force a read-only eCryptfs mount if the lower mount is ro. * Allow a ro eCryptfs mount even when the lower mount is rw. */ s->s_flags = flags & ~MS_POSIXACL; s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_make_root(inode); if (!s->s_root) { rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); root_info->lower_path = path; s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); } Commit Message: fs: limit filesystem stacking depth Add a simple read-only counter to super_block that indicates how deep this is in the stack of filesystems. Previously ecryptfs was the only stackable filesystem and it explicitly disallowed multiple layers of itself. Overlayfs, however, can be stacked recursively and also may be stacked on top of ecryptfs or vice versa. To limit the kernel stack usage we must limit the depth of the filesystem stack. Initially the limit is set to 2. Signed-off-by: Miklos Szeredi <mszeredi@suse.cz> CWE ID: CWE-264
static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; uid_t check_ruid; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) { rc = -EPERM; printk(KERN_ERR "Mount of device (uid: %d) not owned by " "requested user (uid: %d)\n", i_uid_read(path.dentry->d_inode), from_kuid(&init_user_ns, current_uid())); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); /** * Set the POSIX ACL flag based on whether they're enabled in the lower * mount. Force a read-only eCryptfs mount if the lower mount is ro. * Allow a ro eCryptfs mount even when the lower mount is rw. */ s->s_flags = flags & ~MS_POSIXACL; s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; s->s_stack_depth = path.dentry->d_sb->s_stack_depth + 1; rc = -EINVAL; if (s->s_stack_depth > FILESYSTEM_MAX_STACK_DEPTH) { pr_err("eCryptfs: maximum fs stacking depth exceeded\n"); goto out_free; } inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_make_root(inode); if (!s->s_root) { rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); root_info->lower_path = path; s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); }
168,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PepperRendererConnection::OnMsgDidDeleteInProcessInstance( PP_Instance instance) { in_process_host_->DeleteInstance(instance); } Commit Message: Validate in-process plugin instance messages. Bug: 733548, 733549 Cq-Include-Trybots: master.tryserver.chromium.linux:linux_site_isolation Change-Id: Ie5572c7bcafa05399b09c44425ddd5ce9b9e4cba Reviewed-on: https://chromium-review.googlesource.com/538908 Commit-Queue: Bill Budge <bbudge@chromium.org> Reviewed-by: Raymes Khoury <raymes@chromium.org> Cr-Commit-Position: refs/heads/master@{#480696} CWE ID: CWE-20
void PepperRendererConnection::OnMsgDidDeleteInProcessInstance( PP_Instance instance) { // 'instance' is possibly invalid. The host must be careful not to trust it. in_process_host_->DeleteInstance(instance); }
172,312
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->partitioned_frame = 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; } Commit Message: avcodec/mpeg4videodec: Clear interlaced_dct for studio profile Fixes: Out of array access Fixes: 13090/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_MPEG4_fuzzer-5408668986638336 Found-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg Reviewed-by: Kieran Kunhya <kierank@obe.tv> Signed-off-by: Michael Niedermayer <michael@niedermayer.cc> CWE ID: CWE-125
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) { MpegEncContext *s = &ctx->m; if (get_bits_left(gb) <= 32) return 0; s->partitioned_frame = 0; s->interlaced_dct = 0; s->decode_mb = mpeg4_decode_studio_mb; decode_smpte_tc(ctx, gb); skip_bits(gb, 10); /* temporal_reference */ skip_bits(gb, 2); /* vop_structure */ s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */ if (get_bits1(gb)) { /* vop_coded */ skip_bits1(gb); /* top_field_first */ skip_bits1(gb); /* repeat_first_field */ s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */ } if (s->pict_type == AV_PICTURE_TYPE_I) { if (get_bits1(gb)) reset_studio_dc_predictors(s); } if (ctx->shape != BIN_ONLY_SHAPE) { s->alternate_scan = get_bits1(gb); s->frame_pred_frame_dct = get_bits1(gb); s->dct_precision = get_bits(gb, 2); s->intra_dc_precision = get_bits(gb, 2); s->q_scale_type = get_bits1(gb); } if (s->alternate_scan) { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } else { ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct); ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan); ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan); } mpeg4_load_default_matrices(s); next_start_code_studio(gb); extension_and_user_data(s, gb, 4); return 0; }
170,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::Rect ShellWindowFrameView::GetBoundsForClientView() const { if (frame_->IsFullscreen()) return bounds(); return gfx::Rect(0, kCaptionHeight, width(), std::max(0, height() - kCaptionHeight)); } Commit Message: [views] Remove header bar on shell windows created with {frame: none}. BUG=130182 R=ben@chromium.org Review URL: https://chromiumcodereview.appspot.com/10597003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-79
gfx::Rect ShellWindowFrameView::GetBoundsForClientView() const { if (is_frameless_ || frame_->IsFullscreen()) return bounds(); return gfx::Rect(0, kCaptionHeight, width(), std::max(0, height() - kCaptionHeight)); }
170,711
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TaskService::UnbindInstance() { { base::AutoLock lock(lock_); if (bound_instance_id_ == kInvalidInstanceId) return false; bound_instance_id_ = kInvalidInstanceId; DCHECK(default_task_runner_); default_task_runner_ = nullptr; } base::subtle::AutoWriteLock task_lock(task_lock_); return true; } Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService There are non-trivial performance implications of using shared SRWLocking on Windows as more state has to be checked. Since there are only two uses of the ReadWriteLock in Chromium after over 1 year, the decision is to remove it. BUG=758721 Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80 Reviewed-on: https://chromium-review.googlesource.com/634423 Commit-Queue: Robert Liao <robliao@chromium.org> Reviewed-by: Takashi Toyoshima <toyoshim@chromium.org> Reviewed-by: Francois Doray <fdoray@chromium.org> Cr-Commit-Position: refs/heads/master@{#497632} CWE ID: CWE-20
bool TaskService::UnbindInstance() { { base::AutoLock lock(lock_); if (bound_instance_id_ == kInvalidInstanceId) return false; bound_instance_id_ = kInvalidInstanceId; DCHECK(default_task_runner_); default_task_runner_ = nullptr; } // But invoked tasks might be still running here. To ensure no task runs on // quitting this method, wait for all tasks to complete. base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_); while (tasks_in_flight_ > 0) no_tasks_in_flight_cv_.Wait(); return true; }
172,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint32 ResourceTracker::GetLiveObjectsForInstance( PP_Instance instance) const { InstanceMap::const_iterator found = instance_map_.find(instance); if (found == instance_map_.end()) return 0; return static_cast<uint32>(found->second->resources.size() + found->second->object_vars.size()); } 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
uint32 ResourceTracker::GetLiveObjectsForInstance( PP_Instance instance) const { InstanceMap::const_iterator found = instance_map_.find(instance); if (found == instance_map_.end()) return 0; return static_cast<uint32>(found->second->ref_resources.size() + found->second->object_vars.size()); }
170,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); dst->data = realloc(newItems, newItems->size); if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); } Commit Message: Fixed #5645: realloc return handling CWE ID: CWE-772
BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) { REGION16_DATA* data; REGION16_DATA* newItems; const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; RECTANGLE_16* dstPtr; UINT32 nbRects, usedRects; RECTANGLE_16 common, newExtents; assert(src); assert(src->data); srcPtr = region16_rects(src, &nbRects); if (!nbRects) { region16_clear(dst); return TRUE; } srcExtents = region16_extents(src); if (nbRects == 1) { BOOL intersects = rectangles_intersection(srcExtents, rect, &common); region16_clear(dst); if (intersects) return region16_union_rect(dst, dst, &common); return TRUE; } newItems = allocateRegion(nbRects); if (!newItems) return FALSE; dstPtr = (RECTANGLE_16*)(&newItems[1]); usedRects = 0; ZeroMemory(&newExtents, sizeof(newExtents)); /* accumulate intersecting rectangles, the final region16_simplify_bands() will * do all the bad job to recreate correct rectangles */ for (endPtr = srcPtr + nbRects; (srcPtr < endPtr) && (rect->bottom > srcPtr->top); srcPtr++) { if (rectangles_intersection(srcPtr, rect, &common)) { *dstPtr = common; usedRects++; dstPtr++; if (rectangle_is_empty(&newExtents)) { /* Check if the existing newExtents is empty. If it is empty, use * new common directly. We do not need to check common rectangle * because the rectangles_intersection() ensures that it is not empty. */ newExtents = common; } else { newExtents.top = MIN(common.top, newExtents.top); newExtents.left = MIN(common.left, newExtents.left); newExtents.bottom = MAX(common.bottom, newExtents.bottom); newExtents.right = MAX(common.right, newExtents.right); } } } newItems->nbRects = usedRects; newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); if ((dst->data->size > 0) && (dst->data != &empty_region)) free(dst->data); data = realloc(newItems, newItems->size); if (!data) free(dst->data); dst->data = data; if (!dst->data) { free(newItems); return FALSE; } dst->extents = newExtents; return region16_simplify_bands(dst); }
169,496
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: display_sigset( const char *msg, sigset_t *mask ) { int signo; NameTableIterator next_sig( SigNames ); if( msg ) { dprintf( D_ALWAYS, msg ); } while( (signo = next_sig()) != -1 ) { if( sigismember(mask,signo) ) { dprintf( D_ALWAYS | D_NOHEADER, "%s ", SigNames.get_name(signo) ); } } dprintf( D_ALWAYS | D_NOHEADER, "\n" ); } Commit Message: CWE ID: CWE-134
display_sigset( const char *msg, sigset_t *mask ) { int signo; NameTableIterator next_sig( SigNames ); if( msg ) { dprintf( D_ALWAYS, "%s", msg ); } while( (signo = next_sig()) != -1 ) { if( sigismember(mask,signo) ) { dprintf( D_ALWAYS | D_NOHEADER, "%s ", SigNames.get_name(signo) ); } } dprintf( D_ALWAYS | D_NOHEADER, "\n" ); }
165,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GLES2DecoderImpl::ClearUnclearedAttachments( GLenum target, Framebuffer* framebuffer) { if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer->service_id()); } GLbitfield clear_bits = 0; if (framebuffer->HasUnclearedAttachment(GL_COLOR_ATTACHMENT0)) { glClearColor( 0.0f, 0.0f, 0.0f, (GLES2Util::GetChannelsForFormat( framebuffer->GetColorAttachmentFormat()) & 0x0008) != 0 ? 0.0f : 1.0f); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); clear_bits |= GL_COLOR_BUFFER_BIT; } if (framebuffer->HasUnclearedAttachment(GL_STENCIL_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); clear_bits |= GL_STENCIL_BUFFER_BIT; } if (framebuffer->HasUnclearedAttachment(GL_DEPTH_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); clear_bits |= GL_DEPTH_BUFFER_BIT; } state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); glClear(clear_bits); framebuffer_manager()->MarkAttachmentsAsCleared( framebuffer, renderbuffer_manager(), texture_manager()); RestoreClearState(); if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer->service_id()); Framebuffer* draw_framebuffer = GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT); GLuint service_id = draw_framebuffer ? draw_framebuffer->service_id() : GetBackbufferServiceId(); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, service_id); } } Commit Message: Framebuffer clear() needs to consider the situation some draw buffers are disabled. This is when we expose DrawBuffers extension. BUG=376951 TEST=the attached test case, webgl conformance R=kbr@chromium.org,bajones@chromium.org Review URL: https://codereview.chromium.org/315283002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@275338 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void GLES2DecoderImpl::ClearUnclearedAttachments( GLenum target, Framebuffer* framebuffer) { if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, framebuffer->service_id()); } GLbitfield clear_bits = 0; if (framebuffer->HasUnclearedColorAttachments()) { glClearColor( 0.0f, 0.0f, 0.0f, (GLES2Util::GetChannelsForFormat( framebuffer->GetColorAttachmentFormat()) & 0x0008) != 0 ? 0.0f : 1.0f); state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); clear_bits |= GL_COLOR_BUFFER_BIT; framebuffer->PrepareDrawBuffersForClear(); } if (framebuffer->HasUnclearedAttachment(GL_STENCIL_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearStencil(0); state_.SetDeviceStencilMaskSeparate(GL_FRONT, -1); state_.SetDeviceStencilMaskSeparate(GL_BACK, -1); clear_bits |= GL_STENCIL_BUFFER_BIT; } if (framebuffer->HasUnclearedAttachment(GL_DEPTH_ATTACHMENT) || framebuffer->HasUnclearedAttachment(GL_DEPTH_STENCIL_ATTACHMENT)) { glClearDepth(1.0f); state_.SetDeviceDepthMask(GL_TRUE); clear_bits |= GL_DEPTH_BUFFER_BIT; } state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); glClear(clear_bits); if ((clear_bits | GL_COLOR_BUFFER_BIT) != 0) framebuffer->RestoreDrawBuffersAfterClear(); framebuffer_manager()->MarkAttachmentsAsCleared( framebuffer, renderbuffer_manager(), texture_manager()); RestoreClearState(); if (target == GL_READ_FRAMEBUFFER_EXT) { glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, framebuffer->service_id()); Framebuffer* draw_framebuffer = GetFramebufferInfoForTarget(GL_DRAW_FRAMEBUFFER_EXT); GLuint service_id = draw_framebuffer ? draw_framebuffer->service_id() : GetBackbufferServiceId(); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, service_id); } }
171,658
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; } Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks. Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2() and provide the correct length. While we're at it, remove the blank line between some checks and the UNALIGNED_MEMCPY()s they protect. Also, note the places where we print the entire payload. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
ikev1_cert_print(netdissect_options *ndo, u_char tpay _U_, const struct isakmp_gen *ext, u_int item_len, const u_char *ep _U_, uint32_t phase _U_, uint32_t doi0 _U_, uint32_t proto0 _U_, int depth _U_) { const struct ikev1_pl_cert *p; struct ikev1_pl_cert cert; static const char *certstr[] = { "none", "pkcs7", "pgp", "dns", "x509sign", "x509ke", "kerberos", "crl", "arl", "spki", "x509attr", }; ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_CERT))); p = (const struct ikev1_pl_cert *)ext; ND_TCHECK(*p); UNALIGNED_MEMCPY(&cert, ext, sizeof(cert)); ND_PRINT((ndo," len=%d", item_len - 4)); ND_PRINT((ndo," type=%s", STR_OR_ID((cert.encode), certstr))); if (2 < ndo->ndo_vflag && 4 < item_len) { /* Print the entire payload in hex */ ND_PRINT((ndo," ")); if (!rawprint(ndo, (const uint8_t *)(ext + 1), item_len - 4)) goto trunc; } return (const u_char *)ext + item_len; trunc: ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_CERT))); return NULL; }
167,789
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_error_quark (void) { static GQuark quark = 0; if (!quark) quark = g_quark_from_static_string ("my_object_error"); return quark; } Commit Message: CWE ID: CWE-264
my_object_error_quark (void)
165,098
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE( "[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb\\u30fc]"), status); kana_letters_exceptions_.freeze(); DCHECK(U_SUCCESS(status)); } Commit Message: Block domain labels made of Cyrillic letters that look alike Latin Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф. BUG=683314 TEST=components_unittests --gtest_filter=U*IDN* Review-Url: https://codereview.chromium.org/2683793010 Cr-Commit-Position: refs/heads/master@{#459226} CWE ID: CWE-20
IDNSpoofChecker::IDNSpoofChecker() { UErrorCode status = U_ZERO_ERROR; checker_ = uspoof_open(&status); if (U_FAILURE(status)) { checker_ = nullptr; return; } uspoof_setRestrictionLevel(checker_, USPOOF_MODERATELY_RESTRICTIVE); SetAllowedUnicodeSet(&status); int32_t checks = uspoof_getChecks(checker_, &status) | USPOOF_AUX_INFO; uspoof_setChecks(checker_, checks, &status); deviation_characters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[\\u00df\\u03c2\\u200c\\u200d]"), status); deviation_characters_.freeze(); non_ascii_latin_letters_ = icu::UnicodeSet( UNICODE_STRING_SIMPLE("[[:Latin:] - [a-zA-Z]]"), status); non_ascii_latin_letters_.freeze(); kana_letters_exceptions_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE( "[\\u3078-\\u307a\\u30d8-\\u30da\\u30fb\\u30fc]"), status); kana_letters_exceptions_.freeze(); // These Cyrillic letters look like Latin. A domain label entirely made of // these letters is blocked as a simpliified whole-script-spoofable. cyrillic_letters_latin_alike_ = icu::UnicodeSet(icu::UnicodeString("[асԁеһіјӏорԛѕԝхуъЬҽпгѵѡ]"), status); cyrillic_letters_latin_alike_.freeze(); cyrillic_letters_ = icu::UnicodeSet(UNICODE_STRING_SIMPLE("[[:Cyrl:]]"), status); cyrillic_letters_.freeze(); DCHECK(U_SUCCESS(status)); }
172,389
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitIdentity *ret; guint32 uid; ret = NULL; if (POLKIT_IS_UNIX_PROCESS (subject)) { uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)); if ((gint) uid == -1) { g_set_error (error, POLKIT_ERROR, g_set_error (error, "Unix process subject does not have uid set"); goto out; } ret = polkit_unix_user_new (uid); } else if (POLKIT_IS_SYSTEM_BUS_NAME (subject)) { ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error); } else if (POLKIT_IS_UNIX_SESSION (subject)) { if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0) { polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitUnixProcess *tmp_process = NULL; } ret = polkit_unix_user_new (uid); } out: return ret; } if (!tmp_process) goto out; process = tmp_process; } Commit Message: CWE ID: CWE-200
polkit_backend_session_monitor_get_user_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, gboolean *result_matches, GError **error) { PolkitIdentity *ret; gboolean matches; ret = NULL; matches = FALSE; if (POLKIT_IS_UNIX_PROCESS (subject)) { gint subject_uid, current_uid; GError *local_error; subject_uid = polkit_unix_process_get_uid (POLKIT_UNIX_PROCESS (subject)); if (subject_uid == -1) { g_set_error (error, POLKIT_ERROR, g_set_error (error, "Unix process subject does not have uid set"); goto out; } local_error = NULL; current_uid = polkit_unix_process_get_racy_uid__ (POLKIT_UNIX_PROCESS (subject), &local_error); if (local_error != NULL) { g_propagate_error (error, local_error); goto out; } ret = polkit_unix_user_new (subject_uid); matches = (subject_uid == current_uid); } else if (POLKIT_IS_SYSTEM_BUS_NAME (subject)) { ret = (PolkitIdentity*)polkit_system_bus_name_get_user_sync (POLKIT_SYSTEM_BUS_NAME (subject), NULL, error); matches = TRUE; } else if (POLKIT_IS_UNIX_SESSION (subject)) { uid_t uid; if (sd_session_get_uid (polkit_unix_session_get_session_id (POLKIT_UNIX_SESSION (subject)), &uid) < 0) { polkit_backend_session_monitor_get_session_for_subject (PolkitBackendSessionMonitor *monitor, PolkitSubject *subject, GError **error) { PolkitUnixProcess *tmp_process = NULL; } ret = polkit_unix_user_new (uid); matches = TRUE; } out: if (result_matches != NULL) { *result_matches = matches; } return ret; } if (!tmp_process) goto out; process = tmp_process; }
165,289
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftGSM::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nFilledLen > kMaxNumSamplesPerFrame) { ALOGE("input buffer too large (%d).", inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; } if(((inHeader->nFilledLen / kMSGSMFrameSize) * kMSGSMFrameSize) != inHeader->nFilledLen) { ALOGE("input buffer not multiple of %d (%d).", kMSGSMFrameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; } uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset; int n = mSignalledError ? 0 : DecodeGSM(mGsm, reinterpret_cast<int16_t *>(outHeader->pBuffer), inputptr, inHeader->nFilledLen); outHeader->nTimeStamp = inHeader->nTimeStamp; outHeader->nOffset = 0; outHeader->nFilledLen = n * sizeof(int16_t); outHeader->nFlags = 0; inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } } Commit Message: codecs: check OMX buffer size before use in (gsm|g711)dec Bug: 27793163 Bug: 27793367 Change-Id: Iec3de8a237ee2379d87a8371c13e543878c6652c CWE ID: CWE-119
void SoftGSM::onQueueFilled(OMX_U32 /* portIndex */) { if (mSignalledError) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } if (inHeader->nFilledLen > kMaxNumSamplesPerFrame) { ALOGE("input buffer too large (%d).", inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; } if(((inHeader->nFilledLen / kMSGSMFrameSize) * kMSGSMFrameSize) != inHeader->nFilledLen) { ALOGE("input buffer not multiple of %d (%d).", kMSGSMFrameSize, inHeader->nFilledLen); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; } if (outHeader->nAllocLen < (inHeader->nFilledLen / kMSGSMFrameSize) * 320) { ALOGE("output buffer is not large enough (%d).", outHeader->nAllocLen); android_errorWriteLog(0x534e4554, "27793367"); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); mSignalledError = true; return; } uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset; int n = mSignalledError ? 0 : DecodeGSM(mGsm, reinterpret_cast<int16_t *>(outHeader->pBuffer), inputptr, inHeader->nFilledLen); outHeader->nTimeStamp = inHeader->nTimeStamp; outHeader->nOffset = 0; outHeader->nFilledLen = n * sizeof(int16_t); outHeader->nFlags = 0; inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } }
173,779
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *str, *padding, *alignment, *ret; int str_l, padding_l; if ((nargs < 2) || (nargs > 3)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 3) alignment = xmlXPathPopString(ctxt); else alignment = NULL; padding = xmlXPathPopString(ctxt); str = xmlXPathPopString(ctxt); str_l = xmlUTF8Strlen (str); padding_l = xmlUTF8Strlen (padding); if (str_l == padding_l) { xmlXPathReturnString (ctxt, str); xmlFree(padding); xmlFree(alignment); return; } if (str_l > padding_l) { ret = xmlUTF8Strndup (str, padding_l); } else { if (xmlStrEqual(alignment, (const xmlChar *) "right")) { ret = xmlUTF8Strndup (padding, padding_l - str_l); ret = xmlStrcat (ret, str); } else if (xmlStrEqual(alignment, (const xmlChar *) "center")) { int left = (padding_l - str_l) / 2; int right_start; ret = xmlUTF8Strndup (padding, left); ret = xmlStrcat (ret, str); right_start = xmlUTF8Strsize (padding, left + str_l); ret = xmlStrcat (ret, padding + right_start); } else { int str_s; str_s = xmlStrlen (str); ret = xmlStrdup (str); ret = xmlStrcat (ret, padding + str_s); } } xmlXPathReturnString (ctxt, ret); xmlFree(str); xmlFree(padding); xmlFree(alignment); } Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7 BUG=583156,583171 Review URL: https://codereview.chromium.org/1853083002 Cr-Commit-Position: refs/heads/master@{#385338} CWE ID: CWE-119
exsltStrAlignFunction (xmlXPathParserContextPtr ctxt, int nargs) { xmlChar *str, *padding, *alignment, *ret; int str_l, padding_l; if ((nargs < 2) || (nargs > 3)) { xmlXPathSetArityError(ctxt); return; } if (nargs == 3) alignment = xmlXPathPopString(ctxt); else alignment = NULL; padding = xmlXPathPopString(ctxt); str = xmlXPathPopString(ctxt); str_l = xmlUTF8Strlen (str); padding_l = xmlUTF8Strlen (padding); if (str_l == padding_l) { xmlXPathReturnString (ctxt, str); xmlFree(padding); xmlFree(alignment); return; } if (str_l > padding_l) { ret = xmlUTF8Strndup (str, padding_l); } else { if (xmlStrEqual(alignment, (const xmlChar *) "right")) { ret = xmlUTF8Strndup (padding, padding_l - str_l); ret = xmlStrcat (ret, str); } else if (xmlStrEqual(alignment, (const xmlChar *) "center")) { int left = (padding_l - str_l) / 2; int right_start; ret = xmlUTF8Strndup (padding, left); ret = xmlStrcat (ret, str); right_start = xmlUTF8Strsize (padding, left + str_l); ret = xmlStrcat (ret, padding + right_start); } else { int str_s; str_s = xmlUTF8Strsize(padding, str_l); ret = xmlStrdup (str); ret = xmlStrcat (ret, padding + str_s); } } xmlXPathReturnString (ctxt, ret); xmlFree(str); xmlFree(padding); xmlFree(alignment); }
173,295
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 print_maps(struct pid_info_t* info) { FILE *maps; size_t offset; char device[10]; long int inode; char file[PATH_MAX]; strlcat(info->path, "maps", sizeof(info->path)); maps = fopen(info->path, "r"); if (!maps) goto out; while (fscanf(maps, "%*x-%*x %*s %zx %s %ld %s\n", &offset, device, &inode, file) == 4) { if (inode == 0 || !strcmp(device, "00:00")) continue; printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n", info->cmdline, info->pid, info->user, "mem", "???", device, offset, inode, file); } fclose(maps); out: info->path[info->parent_length] = '\0'; } Commit Message: Fix scanf %s in lsof. Bug: http://b/28175237 Change-Id: Ief0ba299b09693ad9afc0e3d17a8f664c2fbb8c2 CWE ID: CWE-20
static void print_maps(struct pid_info_t* info) { FILE *maps; size_t offset; char device[10]; long int inode; char file[1024]; strlcat(info->path, "maps", sizeof(info->path)); maps = fopen(info->path, "r"); if (!maps) goto out; while (fscanf(maps, "%*x-%*x %*s %zx %5s %ld %1023s\n", &offset, device, &inode, file) == 4) { if (inode == 0 || !strcmp(device, "00:00")) continue; printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n", info->cmdline, info->pid, info->user, "mem", "???", device, offset, inode, file); } fclose(maps); out: info->path[info->parent_length] = '\0'; }
173,560
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); } Commit Message: (for 4.9.3) CVE-2018-14464/LMP: Add a missing bounds check In lmp_print_data_link_subobjs(). This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
lmp_print_data_link_subobjs(netdissect_options *ndo, const u_char *obj_tptr, int total_subobj_len, int offset) { int hexdump = FALSE; int subobj_type, subobj_len; union { /* int to float conversion buffer */ float f; uint32_t i; } bw; while (total_subobj_len > 0 && hexdump == FALSE ) { subobj_type = EXTRACT_8BITS(obj_tptr + offset); subobj_len = EXTRACT_8BITS(obj_tptr + offset + 1); ND_PRINT((ndo, "\n\t Subobject, Type: %s (%u), Length: %u", tok2str(lmp_data_link_subobj, "Unknown", subobj_type), subobj_type, subobj_len)); if (subobj_len < 4) { ND_PRINT((ndo, " (too short)")); break; } if ((subobj_len % 4) != 0) { ND_PRINT((ndo, " (not a multiple of 4)")); break; } if (total_subobj_len < subobj_len) { ND_PRINT((ndo, " (goes past the end of the object)")); break; } switch(subobj_type) { case INT_SWITCHING_TYPE_SUBOBJ: ND_PRINT((ndo, "\n\t Switching Type: %s (%u)", tok2str(gmpls_switch_cap_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 2)), EXTRACT_8BITS(obj_tptr + offset + 2))); ND_PRINT((ndo, "\n\t Encoding Type: %s (%u)", tok2str(gmpls_encoding_values, "Unknown", EXTRACT_8BITS(obj_tptr + offset + 3)), EXTRACT_8BITS(obj_tptr + offset + 3))); ND_TCHECK_32BITS(obj_tptr + offset + 4); bw.i = EXTRACT_32BITS(obj_tptr+offset+4); ND_PRINT((ndo, "\n\t Min Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); bw.i = EXTRACT_32BITS(obj_tptr+offset+8); ND_PRINT((ndo, "\n\t Max Reservable Bandwidth: %.3f Mbps", bw.f*8/1000000)); break; case WAVELENGTH_SUBOBJ: ND_PRINT((ndo, "\n\t Wavelength: %u", EXTRACT_32BITS(obj_tptr+offset+4))); break; default: /* Any Unknown Subobject ==> Exit loop */ hexdump=TRUE; break; } total_subobj_len-=subobj_len; offset+=subobj_len; } return (hexdump); trunc: return -1; }
169,849
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HistogramsCallback() { MockHistogramsCallback(); QuitMessageLoop(); } Commit Message: Migrate ServiceProcessControl tests off of QuitCurrent*Deprecated(). Bug: 844016 Change-Id: I9403b850456c8ee06cd2539f7cec9599302e81a0 Reviewed-on: https://chromium-review.googlesource.com/1126576 Commit-Queue: Wez <wez@chromium.org> Reviewed-by: Avi Drissman <avi@chromium.org> Cr-Commit-Position: refs/heads/master@{#573131} CWE ID: CWE-94
void HistogramsCallback() { void HistogramsCallback(base::RepeatingClosure on_done) { MockHistogramsCallback(); on_done.Run(); }
172,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_METHOD(Phar, mount) { char *fname, *arch = NULL, *entry = NULL, *path, *actual; int fname_len, arch_len, entry_len; size_t path_len, actual_len; phar_archive_data *pphar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &path, &path_len, &actual, &actual_len) == FAILURE) { return; } fname = (char*)zend_get_executed_filename(); fname_len = strlen(fname); #ifdef PHP_WIN32 phar_unixify_path_separators(fname, fname_len); #endif if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { efree(entry); entry = NULL; if (path_len > 7 && !memcmp(path, "phar://", 7)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path); efree(arch); return; } carry_on2: if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) { if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } } zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch); if (arch) { efree(arch); } return; } carry_on: if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch); if (path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } if (entry && path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } else if (PHAR_G(phar_fname_map.u.flags) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) { goto carry_on; } else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } goto carry_on; } else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { path = entry; path_len = entry_len; goto carry_on2; } zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual); } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, mount) { char *fname, *arch = NULL, *entry = NULL, *path, *actual; int fname_len, arch_len, entry_len; size_t path_len, actual_len; phar_archive_data *pphar; if (zend_parse_parameters(ZEND_NUM_ARGS(), "pp", &path, &path_len, &actual, &actual_len) == FAILURE) { return; } fname = (char*)zend_get_executed_filename(); fname_len = strlen(fname); #ifdef PHP_WIN32 phar_unixify_path_separators(fname, fname_len); #endif if (fname_len > 7 && !memcmp(fname, "phar://", 7) && SUCCESS == phar_split_fname(fname, fname_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { efree(entry); entry = NULL; if (path_len > 7 && !memcmp(path, "phar://", 7)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Can only mount internal paths within a phar archive, use a relative path instead of \"%s\"", path); efree(arch); return; } carry_on2: if (NULL == (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), arch, arch_len))) { if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, arch, arch_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } } zend_throw_exception_ex(phar_ce_PharException, 0, "%s is not a phar archive, cannot mount", arch); if (arch) { efree(arch); } return; } carry_on: if (SUCCESS != phar_mount_entry(pphar, actual, actual_len, path, path_len)) { zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s within phar %s failed", path, actual, arch); if (path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } if (entry && path && path == entry) { efree(entry); } if (arch) { efree(arch); } return; } else if (PHAR_G(phar_fname_map.u.flags) && NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), fname, fname_len))) { goto carry_on; } else if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, fname, fname_len))) { if (SUCCESS == phar_copy_on_write(&pphar)) { goto carry_on; } goto carry_on; } else if (SUCCESS == phar_split_fname(path, path_len, &arch, &arch_len, &entry, &entry_len, 2, 0)) { path = entry; path_len = entry_len; goto carry_on2; } zend_throw_exception_ex(phar_ce_PharException, 0, "Mounting of %s to %s failed", path, actual); }
165,056
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PageHandler::SetRenderer(RenderProcessHost* process_host, RenderFrameHostImpl* frame_host) { if (host_ == frame_host) return; RenderWidgetHostImpl* widget_host = host_ ? host_->GetRenderWidgetHost() : nullptr; if (widget_host) { registrar_.Remove( this, content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, content::Source<RenderWidgetHost>(widget_host)); } host_ = frame_host; widget_host = host_ ? host_->GetRenderWidgetHost() : nullptr; if (widget_host) { registrar_.Add( this, content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, content::Source<RenderWidgetHost>(widget_host)); } } 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 PageHandler::SetRenderer(RenderProcessHost* process_host, void PageHandler::SetRenderer(int process_host_id, RenderFrameHostImpl* frame_host) { if (host_ == frame_host) return; RenderWidgetHostImpl* widget_host = host_ ? host_->GetRenderWidgetHost() : nullptr; if (widget_host) { registrar_.Remove( this, content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, content::Source<RenderWidgetHost>(widget_host)); } host_ = frame_host; widget_host = host_ ? host_->GetRenderWidgetHost() : nullptr; if (widget_host) { registrar_.Add( this, content::NOTIFICATION_RENDER_WIDGET_VISIBILITY_CHANGED, content::Source<RenderWidgetHost>(widget_host)); } }
172,764
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ThreadableBlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData) { if (isMainThread()) blobRegistry().registerBlobURL(url, blobData); else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData)); callOnMainThread(&registerBlobURLTask, context.leakPtr()); } } 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:
void ThreadableBlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData) void BlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData) { if (isMainThread()) { if (WebBlobRegistry* registry = blobRegistry()) { WebBlobData webBlobData(blobData); registry->registerBlobURL(url, webBlobData); } } else { OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData)); callOnMainThread(&registerBlobURLTask, context.leakPtr()); } }
170,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: static sk_sp<SkImage> premulSkImageToUnPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<size_t>(input->width()) * info.bytesPerPixel()); } Commit Message: Prevent bad casting in ImageBitmap when calling ArrayBuffer::createOrNull Currently when ImageBitmap's constructor is invoked, we check whether dstSize will overflow size_t or not. The problem comes when we call ArrayBuffer::createOrNull some times in the code. Both parameters of ArrayBuffer::createOrNull are unsigned. In ImageBitmap when we call this method, the first parameter is usually width * height. This could overflow unsigned even if it has been checked safe with size_t, the reason is that unsigned is a 32-bit value on 64-bit systems, while size_t is a 64-bit value. This CL makes a change such that we check whether the dstSize will overflow unsigned or not. In this case, we can guarantee that createOrNull will not have any crash. BUG=664139 Review-Url: https://codereview.chromium.org/2500493002 Cr-Commit-Position: refs/heads/master@{#431936} CWE ID: CWE-787
static sk_sp<SkImage> premulSkImageToUnPremul(SkImage* input) { SkImageInfo info = SkImageInfo::Make(input->width(), input->height(), kN32_SkColorType, kUnpremul_SkAlphaType); RefPtr<Uint8Array> dstPixels = copySkImageData(input, info); if (!dstPixels) return nullptr; return newSkImageFromRaster( info, std::move(dstPixels), static_cast<unsigned>(input->width()) * info.bytesPerPixel()); }
172,504
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: plan_a (char const *filename) { char const *s; char const *lim; char const **ptr; char *buffer; lin iline; size_t size = instat.st_size; /* Fail if the file size doesn't fit in a size_t, or if storage isn't available. */ if (! (size == instat.st_size && (buffer = malloc (size ? size : (size_t) 1)))) return false; /* Read the input file, but don't bother reading it if it's empty. When creating files, the files do not actually exist. */ if (size) { if (S_ISREG (instat.st_mode)) { int ifd = safe_open (filename, O_RDONLY|binary_transput, 0); size_t buffered = 0, n; if (ifd < 0) pfatal ("can't open file %s", quotearg (filename)); /* Some non-POSIX hosts exaggerate st_size in text mode; or the file may have shrunk! */ size = buffered; break; } if (n == (size_t) -1) { /* Perhaps size is too large for this host. */ close (ifd); free (buffer); return false; } buffered += n; } if (close (ifd) != 0) read_fatal (); } Commit Message: CWE ID: CWE-59
plan_a (char const *filename) { char const *s; char const *lim; char const **ptr; char *buffer; lin iline; size_t size = instat.st_size; /* Fail if the file size doesn't fit in a size_t, or if storage isn't available. */ if (! (size == instat.st_size && (buffer = malloc (size ? size : (size_t) 1)))) return false; /* Read the input file, but don't bother reading it if it's empty. When creating files, the files do not actually exist. */ if (size) { if (S_ISREG (instat.st_mode)) { int flags = O_RDONLY | binary_transput; size_t buffered = 0, n; int ifd; if (! follow_symlinks) flags |= O_NOFOLLOW; ifd = safe_open (filename, flags, 0); if (ifd < 0) pfatal ("can't open file %s", quotearg (filename)); /* Some non-POSIX hosts exaggerate st_size in text mode; or the file may have shrunk! */ size = buffered; break; } if (n == (size_t) -1) { /* Perhaps size is too large for this host. */ close (ifd); free (buffer); return false; } buffered += n; } if (close (ifd) != 0) read_fatal (); }
164,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void CameraSource::dataCallbackTimestamp(int64_t timestampUs, int32_t msgType __unused, const sp<IMemory> &data) { ALOGV("dataCallbackTimestamp: timestamp %lld us", (long long)timestampUs); Mutex::Autolock autoLock(mLock); if (!mStarted || (mNumFramesReceived == 0 && timestampUs < mStartTimeUs)) { ALOGV("Drop frame at %lld/%lld us", (long long)timestampUs, (long long)mStartTimeUs); releaseOneRecordingFrame(data); return; } if (skipCurrentFrame(timestampUs)) { releaseOneRecordingFrame(data); return; } if (mNumFramesReceived > 0) { if (timestampUs <= mLastFrameTimestampUs) { ALOGW("Dropping frame with backward timestamp %lld (last %lld)", (long long)timestampUs, (long long)mLastFrameTimestampUs); releaseOneRecordingFrame(data); return; } if (timestampUs - mLastFrameTimestampUs > mGlitchDurationThresholdUs) { ++mNumGlitches; } } mLastFrameTimestampUs = timestampUs; if (mNumFramesReceived == 0) { mFirstFrameTimeUs = timestampUs; if (mStartTimeUs > 0) { if (timestampUs < mStartTimeUs) { releaseOneRecordingFrame(data); return; } mStartTimeUs = timestampUs - mStartTimeUs; } } ++mNumFramesReceived; CHECK(data != NULL && data->size() > 0); mFramesReceived.push_back(data); int64_t timeUs = mStartTimeUs + (timestampUs - mFirstFrameTimeUs); mFrameTimes.push_back(timeUs); ALOGV("initial delay: %" PRId64 ", current time stamp: %" PRId64, mStartTimeUs, timeUs); mFrameAvailableCondition.signal(); } Commit Message: DO NOT MERGE: Camera: Adjust pointers to ANW buffers to avoid infoleak Subtract address of a random static object from pointers being routed through app process. Bug: 28466701 Change-Id: Idcbfe81e9507433769672f3dc6d67db5eeed4e04 CWE ID: CWE-200
void CameraSource::dataCallbackTimestamp(int64_t timestampUs, int32_t msgType __unused, const sp<IMemory> &data) { ALOGV("dataCallbackTimestamp: timestamp %lld us", (long long)timestampUs); Mutex::Autolock autoLock(mLock); if (!mStarted || (mNumFramesReceived == 0 && timestampUs < mStartTimeUs)) { ALOGV("Drop frame at %lld/%lld us", (long long)timestampUs, (long long)mStartTimeUs); releaseOneRecordingFrame(data); return; } if (skipCurrentFrame(timestampUs)) { releaseOneRecordingFrame(data); return; } if (mNumFramesReceived > 0) { if (timestampUs <= mLastFrameTimestampUs) { ALOGW("Dropping frame with backward timestamp %lld (last %lld)", (long long)timestampUs, (long long)mLastFrameTimestampUs); releaseOneRecordingFrame(data); return; } if (timestampUs - mLastFrameTimestampUs > mGlitchDurationThresholdUs) { ++mNumGlitches; } } mLastFrameTimestampUs = timestampUs; if (mNumFramesReceived == 0) { mFirstFrameTimeUs = timestampUs; if (mStartTimeUs > 0) { if (timestampUs < mStartTimeUs) { releaseOneRecordingFrame(data); return; } mStartTimeUs = timestampUs - mStartTimeUs; } } ++mNumFramesReceived; CHECK(data != NULL && data->size() > 0); // b/28466701 adjustIncomingANWBuffer(data.get()); mFramesReceived.push_back(data); int64_t timeUs = mStartTimeUs + (timestampUs - mFirstFrameTimeUs); mFrameTimes.push_back(timeUs); ALOGV("initial delay: %" PRId64 ", current time stamp: %" PRId64, mStartTimeUs, timeUs); mFrameAvailableCondition.signal(); }
173,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SecurityContext::SecurityContext() : m_mayDisplaySeamlesslyWithParent(false) , m_haveInitializedSecurityOrigin(false) , m_sandboxFlags(SandboxNone) { } Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document The member is used only in Document, thus no reason to stay in SecurityContext. TEST=none BUG=none R=haraken@chromium.org, abarth, haraken, hayato Review URL: https://codereview.chromium.org/27615003 git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-20
SecurityContext::SecurityContext() : m_haveInitializedSecurityOrigin(false) , m_sandboxFlags(SandboxNone) { }
170,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: PixarLogClose(TIFF* tif) { TIFFDirectory *td = &tif->tif_dir; /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer overflow on generation of PixarLog / LUV compressed files, with ColorMap, TransferFunction attached and nasty plays with bitspersample. The fix for LUV has not been tested, but suffers from the same kind of issue of PixarLog. Reported by Agostino Sarubbo. Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604 CWE ID: CWE-125
PixarLogClose(TIFF* tif) { PixarLogState* sp = (PixarLogState*) tif->tif_data; TIFFDirectory *td = &tif->tif_dir; assert(sp != 0); /* In a really sneaky (and really incorrect, and untruthful, and * troublesome, and error-prone) maneuver that completely goes against * the spirit of TIFF, and breaks TIFF, on close, we covertly * modify both bitspersample and sampleformat in the directory to * indicate 8-bit linear. This way, the decode "just works" even for * readers that don't know about PixarLog, or how to set * the PIXARLOGDATFMT pseudo-tag. */ if (sp->state&PLSTATE_INIT) { /* We test the state to avoid an issue such as in * http://bugzilla.maptools.org/show_bug.cgi?id=2604 * What appends in that case is that the bitspersample is 1 and * a TransferFunction is set. The size of the TransferFunction * depends on 1<<bitspersample. So if we increase it, an access * out of the buffer will happen at directory flushing. * Another option would be to clear those targs. */ td->td_bitspersample = 8; td->td_sampleformat = SAMPLEFORMAT_UINT; } }
168,466
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) (buffer[0] << 8); value|=buffer[1]; quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed) CWE ID: CWE-125
static inline signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); }
169,953
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 char* lookup_loc_range(const char* loc_range, HashTable* hash_arr, int canonicalize TSRMLS_DC) { int i = 0; int cur_arr_len = 0; int result = 0; char* lang_tag = NULL; zval** ele_value = NULL; char** cur_arr = NULL; char* cur_loc_range = NULL; char* can_loc_range = NULL; int saved_pos = 0; char* return_value = NULL; cur_arr = ecalloc(zend_hash_num_elements(hash_arr)*2, sizeof(char *)); /* convert the array to lowercase , also replace hyphens with the underscore and store it in cur_arr */ for(zend_hash_internal_pointer_reset(hash_arr); zend_hash_has_more_elements(hash_arr) == SUCCESS; zend_hash_move_forward(hash_arr)) { if (zend_hash_get_current_data(hash_arr, (void**)&ele_value) == FAILURE) { /* Should never actually fail since the key is known to exist.*/ continue; } if(Z_TYPE_PP(ele_value)!= IS_STRING) { /* element value is not a string */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: locale array element is not a string", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_PP(ele_value), Z_STRLEN_PP(ele_value)); result = strToMatch(Z_STRVAL_PP(ele_value), cur_arr[cur_arr_len*2]); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2+1] = Z_STRVAL_PP(ele_value); cur_arr_len++ ; } /* end of for */ /* Canonicalize array elements */ if(canonicalize) { for(i=0; i<cur_arr_len; i++) { lang_tag = get_icu_value_internal(cur_arr[i*2], LOC_CANONICALIZE_TAG, &result, 0); if(result != 1 || lang_tag == NULL || !lang_tag[0]) { if(lang_tag) { efree(lang_tag); } intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[i*2] = erealloc(cur_arr[i*2], strlen(lang_tag)+1); result = strToMatch(lang_tag, cur_arr[i*2]); efree(lang_tag); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } } } if(canonicalize) { /* Canonicalize the loc_range */ can_loc_range = get_icu_value_internal(loc_range, LOC_CANONICALIZE_TAG, &result , 0); if( result != 1 || can_loc_range == NULL || !can_loc_range[0]) { /* Error */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize loc_range" , 0 TSRMLS_CC ); if(can_loc_range) { efree(can_loc_range); } LOOKUP_CLEAN_RETURN(NULL); } else { loc_range = can_loc_range; } } cur_loc_range = ecalloc(1, strlen(loc_range)+1); /* convert to lower and replace hyphens */ result = strToMatch(loc_range, cur_loc_range); if(can_loc_range) { efree(can_loc_range); } if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } /* Lookup for the lang_tag match */ saved_pos = strlen(cur_loc_range); while(saved_pos > 0) { for(i=0; i< cur_arr_len; i++){ if(cur_arr[i*2] != NULL && strlen(cur_arr[i*2]) == saved_pos && strncmp(cur_loc_range, cur_arr[i*2], saved_pos) == 0) { /* Match found */ return_value = estrdup(canonicalize?cur_arr[i*2]:cur_arr[i*2+1]); efree(cur_loc_range); LOOKUP_CLEAN_RETURN(return_value); } } saved_pos = getStrrtokenPos(cur_loc_range, saved_pos); } /* Match not found */ efree(cur_loc_range); LOOKUP_CLEAN_RETURN(NULL); } Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read CWE ID: CWE-125
static char* lookup_loc_range(const char* loc_range, HashTable* hash_arr, int canonicalize TSRMLS_DC) { int i = 0; int cur_arr_len = 0; int result = 0; char* lang_tag = NULL; zval** ele_value = NULL; char** cur_arr = NULL; char* cur_loc_range = NULL; char* can_loc_range = NULL; int saved_pos = 0; char* return_value = NULL; cur_arr = ecalloc(zend_hash_num_elements(hash_arr)*2, sizeof(char *)); /* convert the array to lowercase , also replace hyphens with the underscore and store it in cur_arr */ for(zend_hash_internal_pointer_reset(hash_arr); zend_hash_has_more_elements(hash_arr) == SUCCESS; zend_hash_move_forward(hash_arr)) { if (zend_hash_get_current_data(hash_arr, (void**)&ele_value) == FAILURE) { /* Should never actually fail since the key is known to exist.*/ continue; } if(Z_TYPE_PP(ele_value)!= IS_STRING) { /* element value is not a string */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: locale array element is not a string", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2] = estrndup(Z_STRVAL_PP(ele_value), Z_STRLEN_PP(ele_value)); result = strToMatch(Z_STRVAL_PP(ele_value), cur_arr[cur_arr_len*2]); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag", 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[cur_arr_len*2+1] = Z_STRVAL_PP(ele_value); cur_arr_len++ ; } /* end of for */ /* Canonicalize array elements */ if(canonicalize) { for(i=0; i<cur_arr_len; i++) { lang_tag = get_icu_value_internal(cur_arr[i*2], LOC_CANONICALIZE_TAG, &result, 0); if(result != 1 || lang_tag == NULL || !lang_tag[0]) { if(lang_tag) { efree(lang_tag); } intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } cur_arr[i*2] = erealloc(cur_arr[i*2], strlen(lang_tag)+1); result = strToMatch(lang_tag, cur_arr[i*2]); efree(lang_tag); if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } } } if(canonicalize) { /* Canonicalize the loc_range */ can_loc_range = get_icu_value_internal(loc_range, LOC_CANONICALIZE_TAG, &result , 0); if( result != 1 || can_loc_range == NULL || !can_loc_range[0]) { /* Error */ intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize loc_range" , 0 TSRMLS_CC ); if(can_loc_range) { efree(can_loc_range); } LOOKUP_CLEAN_RETURN(NULL); } else { loc_range = can_loc_range; } } cur_loc_range = ecalloc(1, strlen(loc_range)+1); /* convert to lower and replace hyphens */ result = strToMatch(loc_range, cur_loc_range); if(can_loc_range) { efree(can_loc_range); } if(result == 0) { intl_error_set(NULL, U_ILLEGAL_ARGUMENT_ERROR, "lookup_loc_range: unable to canonicalize lang_tag" , 0 TSRMLS_CC); LOOKUP_CLEAN_RETURN(NULL); } /* Lookup for the lang_tag match */ saved_pos = strlen(cur_loc_range); while(saved_pos > 0) { for(i=0; i< cur_arr_len; i++){ if(cur_arr[i*2] != NULL && strlen(cur_arr[i*2]) == saved_pos && strncmp(cur_loc_range, cur_arr[i*2], saved_pos) == 0) { /* Match found */ return_value = estrdup(canonicalize?cur_arr[i*2]:cur_arr[i*2+1]); efree(cur_loc_range); LOOKUP_CLEAN_RETURN(return_value); } } saved_pos = getStrrtokenPos(cur_loc_range, saved_pos); } /* Match not found */ efree(cur_loc_range); LOOKUP_CLEAN_RETURN(NULL); }
167,208
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) { Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); Stream_Write_UINT32(s, header->MessageType); }
169,281
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } R_FREE (bb); } Commit Message: Fix #10293 - Use-after-free in r_anal_bb_free() CWE ID: CWE-416
R_API void r_anal_bb_free(RAnalBlock *bb) { if (!bb) { return; } r_anal_cond_free (bb->cond); R_FREE (bb->fingerprint); r_anal_diff_free (bb->diff); bb->diff = NULL; R_FREE (bb->op_bytes); r_anal_switch_op_free (bb->switch_op); bb->switch_op = NULL; bb->fingerprint = NULL; bb->cond = NULL; R_FREE (bb->label); R_FREE (bb->op_pos); R_FREE (bb->parent_reg_arena); if (bb->prev) { if (bb->prev->jumpbb == bb) { bb->prev->jumpbb = NULL; } if (bb->prev->failbb == bb) { bb->prev->failbb = NULL; } bb->prev = NULL; } if (bb->jumpbb) { bb->jumpbb->prev = NULL; bb->jumpbb = NULL; } if (bb->failbb) { bb->failbb->prev = NULL; bb->failbb = NULL; } if (bb->next) { // avoid double free bb->next->prev = NULL; } R_FREE (bb); // double free }
169,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: bool HTMLMediaElement::isAutoplayAllowedPerSettings() const { LocalFrame* frame = document().frame(); if (!frame) return false; FrameLoaderClient* frameLoaderClient = frame->loader().client(); return frameLoaderClient && frameLoaderClient->allowAutoplay(false); } Commit Message: [Blink>Media] Allow autoplay muted on Android by default There was a mistake causing autoplay muted is shipped on Android but it will be disabled if the chromium embedder doesn't specify content setting for "AllowAutoplay" preference. This CL makes the AllowAutoplay preference true by default so that it is allowed by embedders (including AndroidWebView) unless they explicitly disable it. Intent to ship: https://groups.google.com/a/chromium.org/d/msg/blink-dev/Q1cnzNI2GpI/AL_eyUNABgAJ BUG=689018 Review-Url: https://codereview.chromium.org/2677173002 Cr-Commit-Position: refs/heads/master@{#448423} CWE ID: CWE-119
bool HTMLMediaElement::isAutoplayAllowedPerSettings() const { LocalFrame* frame = document().frame(); if (!frame) return false; FrameLoaderClient* frameLoaderClient = frame->loader().client(); return frameLoaderClient && frameLoaderClient->allowAutoplay(true); }
172,016
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; if (intern->file_name) { efree(intern->file_name); } intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } if (intern->_path) { efree(intern->_path); } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; if (intern->file_name) { efree(intern->file_name); } intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } if (intern->_path) { efree(intern->_path); } intern->_path = estrndup(path, intern->_path_len); } /* }}} */
167,079
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const BlockEntry* Cluster::GetEntry( const Track* pTrack, long long time_ns) const { assert(pTrack); if (m_pSegment == NULL) //this is the special EOS cluster return pTrack->GetEOS(); #if 0 LoadBlockEntries(); if ((m_entries == NULL) || (m_entries_count <= 0)) return NULL; //return EOS here? const BlockEntry* pResult = pTrack->GetEOS(); BlockEntry** i = m_entries; assert(i); BlockEntry** const j = i + m_entries_count; while (i != j) { const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) continue; if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; pResult = pEntry; } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; } } return pResult; #else const BlockEntry* pResult = pTrack->GetEOS(); long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); assert(status >= 0); if (status > 0) //completely parsed, and no more entries return pResult; if (status < 0) //should never happen return 0; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) { ++index; continue; } if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; pResult = pEntry; //have a candidate } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; } ++index; } #endif } 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
const BlockEntry* Cluster::GetEntry( if (m_pSegment == NULL) // this is the special EOS cluster return pTrack->GetEOS(); #if 0 LoadBlockEntries(); if ((m_entries == NULL) || (m_entries_count <= 0)) return NULL; //return EOS here? const BlockEntry* pResult = pTrack->GetEOS(); BlockEntry** i = m_entries; assert(i); BlockEntry** const j = i + m_entries_count; while (i != j) { const BlockEntry* const pEntry = *i++; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) continue; if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) //just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; pResult = pEntry; } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) break; } } return pResult; #else const BlockEntry* pResult = pTrack->GetEOS(); long index = 0; for (;;) { if (index >= m_entries_count) { long long pos; long len; const long status = Parse(pos, len); assert(status >= 0); if (status > 0) // completely parsed, and no more entries return pResult; if (status < 0) // should never happen return 0; assert(m_entries); assert(index < m_entries_count); } const BlockEntry* const pEntry = m_entries[index]; assert(pEntry); assert(!pEntry->EOS()); const Block* const pBlock = pEntry->GetBlock(); assert(pBlock); if (pBlock->GetTrackNumber() != pTrack->GetNumber()) { ++index; continue; } if (pTrack->VetEntry(pEntry)) { if (time_ns < 0) // just want first candidate block return pEntry; const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; pResult = pEntry; // have a candidate } else if (time_ns >= 0) { const long long ns = pBlock->GetTime(this); if (ns > time_ns) return pResult; } ++index; } #endif }
174,315
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) { attributes->usage = (audio_usage_t) parcel.readInt32(); attributes->content_type = (audio_content_type_t) parcel.readInt32(); attributes->source = (audio_source_t) parcel.readInt32(); attributes->flags = (audio_flags_mask_t) parcel.readInt32(); const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); if (hasFlattenedTag) { String16 tags = parcel.readString16(); ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); if (realTagSize <= 0) { strcpy(attributes->tags, ""); } else { size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; utf16_to_utf8(tags.string(), tagSize, attributes->tags); } } else { ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); strcpy(attributes->tags, ""); } } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I3518416e89ed901021970958fb6005fd69129f7c (cherry picked from commit 1d3f4278b2666d1a145af2f54782c993aa07d1d9) CWE ID: CWE-119
void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) { attributes->usage = (audio_usage_t) parcel.readInt32(); attributes->content_type = (audio_content_type_t) parcel.readInt32(); attributes->source = (audio_source_t) parcel.readInt32(); attributes->flags = (audio_flags_mask_t) parcel.readInt32(); const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); if (hasFlattenedTag) { String16 tags = parcel.readString16(); ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); if (realTagSize <= 0) { strcpy(attributes->tags, ""); } else { size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; utf16_to_utf8(tags.string(), tagSize, attributes->tags, sizeof(attributes->tags) / sizeof(attributes->tags[0])); } } else { ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); strcpy(attributes->tags, ""); } }
174,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: PHP_FUNCTION(curl_unescape) { char *str = NULL, *out = NULL; size_t str_len = 0; int out_len; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (str_len > INT_MAX) { RETURN_FALSE; } if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) { RETVAL_STRINGL(out, out_len); curl_free(out); } else { RETURN_FALSE; } } Commit Message: Fix bug #72674 - check both curl_escape and curl_unescape CWE ID: CWE-119
PHP_FUNCTION(curl_unescape) { char *str = NULL, *out = NULL; size_t str_len = 0; int out_len; zval *zid; php_curl *ch; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &zid, &str, &str_len) == FAILURE) { return; } if ((ch = (php_curl*)zend_fetch_resource(Z_RES_P(zid), le_curl_name, le_curl)) == NULL) { RETURN_FALSE; } if (ZEND_SIZE_T_INT_OVFL(str_len)) { RETURN_FALSE; } if ((out = curl_easy_unescape(ch->cp, str, str_len, &out_len))) { RETVAL_STRINGL(out, out_len); curl_free(out); } else { RETURN_FALSE; } }
166,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 sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } Commit Message: bluetooth: Validate socket address length in sco_sock_bind(). Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-200
static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; if (addr_len < sizeof(struct sockaddr_sco)) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; }
167,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ftc_snode_load( FTC_SNode snode, FTC_Manager manager, FT_UInt gindex, FT_ULong *asize ) { FT_Error error; FTC_GNode gnode = FTC_GNODE( snode ); FTC_Family family = gnode->family; FT_Memory memory = manager->memory; FT_Face face; FTC_SBit sbit; FTC_SFamilyClass clazz; if ( (FT_UInt)(gindex - gnode->gindex) >= snode->count ) { FT_ERROR(( "ftc_snode_load: invalid glyph index" )); return FT_THROW( Invalid_Argument ); } sbit = snode->sbits + ( gindex - gnode->gindex ); clazz = (FTC_SFamilyClass)family->clazz; sbit->buffer = 0; error = clazz->family_load_glyph( family, gindex, manager, &face ); if ( error ) goto BadGlyph; { FT_Int temp; FT_GlyphSlot slot = face->glyph; FT_Bitmap* bitmap = &slot->bitmap; FT_Pos xadvance, yadvance; /* FT_GlyphSlot->advance.{x|y} */ if ( slot->format != FT_GLYPH_FORMAT_BITMAP ) { FT_TRACE0(( "ftc_snode_load:" " glyph loaded didn't return a bitmap\n" )); goto BadGlyph; } /* Check that our values fit into 8-bit containers! */ /* If this is not the case, our bitmap is too large */ /* and we will leave it as `missing' with sbit.buffer = 0 */ #define CHECK_CHAR( d ) ( temp = (FT_Char)d, temp == d ) #define CHECK_BYTE( d ) ( temp = (FT_Byte)d, temp == d ) /* horizontal advance in pixels */ xadvance = ( slot->advance.x + 32 ) >> 6; yadvance = ( slot->advance.y + 32 ) >> 6; if ( !CHECK_BYTE( bitmap->rows ) || !CHECK_BYTE( bitmap->width ) || !CHECK_CHAR( bitmap->pitch ) || !CHECK_CHAR( slot->bitmap_left ) || !CHECK_CHAR( slot->bitmap_top ) || !CHECK_CHAR( xadvance ) || !CHECK_CHAR( yadvance ) ) { FT_TRACE2(( "ftc_snode_load:" " glyph too large for small bitmap cache\n")); goto BadGlyph; } sbit->width = (FT_Byte)bitmap->width; sbit->height = (FT_Byte)bitmap->rows; sbit->pitch = (FT_Char)bitmap->pitch; sbit->left = (FT_Char)slot->bitmap_left; sbit->top = (FT_Char)slot->bitmap_top; sbit->xadvance = (FT_Char)xadvance; sbit->yadvance = (FT_Char)yadvance; sbit->format = (FT_Byte)bitmap->pixel_mode; sbit->max_grays = (FT_Byte)(bitmap->num_grays - 1); /* copy the bitmap into a new buffer -- ignore error */ error = ftc_sbit_copy_bitmap( sbit, bitmap, memory ); /* now, compute size */ if ( asize ) *asize = FT_ABS( sbit->pitch ) * sbit->height; } /* glyph loading successful */ /* ignore the errors that might have occurred -- */ /* we mark unloaded glyphs with `sbit.buffer == 0' */ /* and `width == 255', `height == 0' */ /* */ if ( error && FT_ERR_NEQ( error, Out_Of_Memory ) ) { BadGlyph: sbit->width = 255; sbit->height = 0; sbit->buffer = NULL; error = FT_Err_Ok; if ( asize ) *asize = 0; } return error; } Commit Message: CWE ID: CWE-119
ftc_snode_load( FTC_SNode snode, FTC_Manager manager, FT_UInt gindex, FT_ULong *asize ) { FT_Error error; FTC_GNode gnode = FTC_GNODE( snode ); FTC_Family family = gnode->family; FT_Memory memory = manager->memory; FT_Face face; FTC_SBit sbit; FTC_SFamilyClass clazz; if ( (FT_UInt)(gindex - gnode->gindex) >= snode->count ) { FT_ERROR(( "ftc_snode_load: invalid glyph index" )); return FT_THROW( Invalid_Argument ); } sbit = snode->sbits + ( gindex - gnode->gindex ); clazz = (FTC_SFamilyClass)family->clazz; sbit->buffer = 0; error = clazz->family_load_glyph( family, gindex, manager, &face ); if ( error ) goto BadGlyph; { FT_Int temp; FT_GlyphSlot slot = face->glyph; FT_Bitmap* bitmap = &slot->bitmap; FT_Pos xadvance, yadvance; /* FT_GlyphSlot->advance.{x|y} */ if ( slot->format != FT_GLYPH_FORMAT_BITMAP ) { FT_TRACE0(( "ftc_snode_load:" " glyph loaded didn't return a bitmap\n" )); goto BadGlyph; } /* Check whether our values fit into 8-bit containers! */ /* If this is not the case, our bitmap is too large */ /* and we will leave it as `missing' with sbit.buffer = 0 */ #define CHECK_CHAR( d ) ( temp = (FT_Char)d, (FT_Int) temp == (FT_Int) d ) #define CHECK_BYTE( d ) ( temp = (FT_Byte)d, (FT_UInt)temp == (FT_UInt)d ) /* horizontal advance in pixels */ xadvance = ( slot->advance.x + 32 ) >> 6; yadvance = ( slot->advance.y + 32 ) >> 6; if ( !CHECK_BYTE( bitmap->rows ) || !CHECK_BYTE( bitmap->width ) || !CHECK_CHAR( bitmap->pitch ) || !CHECK_CHAR( slot->bitmap_left ) || !CHECK_CHAR( slot->bitmap_top ) || !CHECK_CHAR( xadvance ) || !CHECK_CHAR( yadvance ) ) { FT_TRACE2(( "ftc_snode_load:" " glyph too large for small bitmap cache\n")); goto BadGlyph; } sbit->width = (FT_Byte)bitmap->width; sbit->height = (FT_Byte)bitmap->rows; sbit->pitch = (FT_Char)bitmap->pitch; sbit->left = (FT_Char)slot->bitmap_left; sbit->top = (FT_Char)slot->bitmap_top; sbit->xadvance = (FT_Char)xadvance; sbit->yadvance = (FT_Char)yadvance; sbit->format = (FT_Byte)bitmap->pixel_mode; sbit->max_grays = (FT_Byte)(bitmap->num_grays - 1); /* copy the bitmap into a new buffer -- ignore error */ error = ftc_sbit_copy_bitmap( sbit, bitmap, memory ); /* now, compute size */ if ( asize ) *asize = FT_ABS( sbit->pitch ) * sbit->height; } /* glyph loading successful */ /* ignore the errors that might have occurred -- */ /* we mark unloaded glyphs with `sbit.buffer == 0' */ /* and `width == 255', `height == 0' */ /* */ if ( error && FT_ERR_NEQ( error, Out_Of_Memory ) ) { BadGlyph: sbit->width = 255; sbit->height = 0; sbit->buffer = NULL; error = FT_Err_Ok; if ( asize ) *asize = 0; } return error; }
164,851
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if WRITE_COMPRESSED_STREAM ++out_frames_; if (pkt->data.frame.pts == 0) write_ivf_file_header(&cfg_, 0, outfile_); write_ivf_frame_header(pkt, outfile_); (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_); #endif } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if WRITE_COMPRESSED_STREAM virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { ++out_frames_; if (pkt->data.frame.pts == 0) write_ivf_file_header(&cfg_, 0, outfile_); write_ivf_frame_header(pkt, outfile_); (void)fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, outfile_); }
174,568
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bio *bio_map_user_iov(struct request_queue *q, const struct iov_iter *iter, gfp_t gfp_mask) { int j; int nr_pages = 0; struct page **pages; struct bio *bio; int cur_page = 0; int ret, offset; struct iov_iter i; struct iovec iov; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; /* * buffer must be aligned to at least logical block size for now */ if (uaddr & queue_dma_alignment(q)) return ERR_PTR(-EINVAL); } if (!nr_pages) return ERR_PTR(-EINVAL); bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); ret = -ENOMEM; pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask); if (!pages) goto out; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; const int local_nr_pages = end - start; const int page_limit = cur_page + local_nr_pages; ret = get_user_pages_fast(uaddr, local_nr_pages, (iter->type & WRITE) != WRITE, &pages[cur_page]); if (ret < local_nr_pages) { ret = -EFAULT; goto out_unmap; } offset = offset_in_page(uaddr); for (j = cur_page; j < page_limit; j++) { unsigned int bytes = PAGE_SIZE - offset; if (len <= 0) break; if (bytes > len) bytes = len; /* * sorry... */ if (bio_add_pc_page(q, bio, pages[j], bytes, offset) < bytes) break; len -= bytes; offset = 0; } cur_page = j; /* * release the pages we didn't map into the bio, if any */ while (j < page_limit) put_page(pages[j++]); } kfree(pages); bio_set_flag(bio, BIO_USER_MAPPED); /* * subtle -- if bio_map_user_iov() ended up bouncing a bio, * it would normally disappear when its bi_end_io is run. * however, we need it for the unmap, so grab an extra * reference to it */ bio_get(bio); return bio; out_unmap: for (j = 0; j < nr_pages; j++) { if (!pages[j]) break; put_page(pages[j]); } out: kfree(pages); bio_put(bio); return ERR_PTR(ret); } Commit Message: fix unbalanced page refcounting in bio_map_user_iov bio_map_user_iov and bio_unmap_user do unbalanced pages refcounting if IO vector has small consecutive buffers belonging to the same page. bio_add_pc_page merges them into one, but the page reference is never dropped. Cc: stable@vger.kernel.org Signed-off-by: Vitaly Mayatskikh <v.mayatskih@gmail.com> Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-772
struct bio *bio_map_user_iov(struct request_queue *q, const struct iov_iter *iter, gfp_t gfp_mask) { int j; int nr_pages = 0; struct page **pages; struct bio *bio; int cur_page = 0; int ret, offset; struct iov_iter i; struct iovec iov; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; /* * Overflow, abort */ if (end < start) return ERR_PTR(-EINVAL); nr_pages += end - start; /* * buffer must be aligned to at least logical block size for now */ if (uaddr & queue_dma_alignment(q)) return ERR_PTR(-EINVAL); } if (!nr_pages) return ERR_PTR(-EINVAL); bio = bio_kmalloc(gfp_mask, nr_pages); if (!bio) return ERR_PTR(-ENOMEM); ret = -ENOMEM; pages = kcalloc(nr_pages, sizeof(struct page *), gfp_mask); if (!pages) goto out; iov_for_each(iov, i, *iter) { unsigned long uaddr = (unsigned long) iov.iov_base; unsigned long len = iov.iov_len; unsigned long end = (uaddr + len + PAGE_SIZE - 1) >> PAGE_SHIFT; unsigned long start = uaddr >> PAGE_SHIFT; const int local_nr_pages = end - start; const int page_limit = cur_page + local_nr_pages; ret = get_user_pages_fast(uaddr, local_nr_pages, (iter->type & WRITE) != WRITE, &pages[cur_page]); if (ret < local_nr_pages) { ret = -EFAULT; goto out_unmap; } offset = offset_in_page(uaddr); for (j = cur_page; j < page_limit; j++) { unsigned int bytes = PAGE_SIZE - offset; unsigned short prev_bi_vcnt = bio->bi_vcnt; if (len <= 0) break; if (bytes > len) bytes = len; /* * sorry... */ if (bio_add_pc_page(q, bio, pages[j], bytes, offset) < bytes) break; /* * check if vector was merged with previous * drop page reference if needed */ if (bio->bi_vcnt == prev_bi_vcnt) put_page(pages[j]); len -= bytes; offset = 0; } cur_page = j; /* * release the pages we didn't map into the bio, if any */ while (j < page_limit) put_page(pages[j++]); } kfree(pages); bio_set_flag(bio, BIO_USER_MAPPED); /* * subtle -- if bio_map_user_iov() ended up bouncing a bio, * it would normally disappear when its bi_end_io is run. * however, we need it for the unmap, so grab an extra * reference to it */ bio_get(bio); return bio; out_unmap: for (j = 0; j < nr_pages; j++) { if (!pages[j]) break; put_page(pages[j]); } out: kfree(pages); bio_put(bio); return ERR_PTR(ret); }
167,988
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ProcessBackingStore(HeapObjectHeader* header) { EXPECT_TRUE(header->IsValid()); EXPECT_TRUE(header->IsMarked()); header->Unmark(); ThreadHeap::GcInfo(header->GcInfoIndex())->trace_(this, header->Payload()); } 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 ProcessBackingStore(HeapObjectHeader* header) { EXPECT_TRUE(header->IsValid()); EXPECT_TRUE(header->IsMarked()); header->Unmark(); GCInfoTable::Get() .GCInfoFromIndex(header->GcInfoIndex()) ->trace_(this, header->Payload()); }
173,140
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void handle_rx(struct vhost_net *net) { struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX]; struct vhost_virtqueue *vq = &nvq->vq; unsigned uninitialized_var(in), log; struct vhost_log *vq_log; struct msghdr msg = { .msg_name = NULL, .msg_namelen = 0, .msg_control = NULL, /* FIXME: get and handle RX aux data. */ .msg_controllen = 0, .msg_iov = vq->iov, .msg_flags = MSG_DONTWAIT, }; struct virtio_net_hdr_mrg_rxbuf hdr = { .hdr.flags = 0, .hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE }; size_t total_len = 0; int err, mergeable; s16 headcount; size_t vhost_hlen, sock_hlen; size_t vhost_len, sock_len; struct socket *sock; mutex_lock(&vq->mutex); sock = vq->private_data; if (!sock) goto out; vhost_disable_notify(&net->dev, vq); vhost_hlen = nvq->vhost_hlen; sock_hlen = nvq->sock_hlen; vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ? vq->log : NULL; mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF); while ((sock_len = peek_head_len(sock->sk))) { sock_len += sock_hlen; vhost_len = sock_len + vhost_hlen; headcount = get_rx_bufs(vq, vq->heads, vhost_len, &in, vq_log, &log, likely(mergeable) ? UIO_MAXIOV : 1); /* On error, stop handling until the next kick. */ if (unlikely(headcount < 0)) break; /* OK, now we need to know about added descriptors. */ if (!headcount) { if (unlikely(vhost_enable_notify(&net->dev, vq))) { /* They have slipped one in as we were * doing that: check again. */ vhost_disable_notify(&net->dev, vq); continue; } /* Nothing new? Wait for eventfd to tell us * they refilled. */ break; } /* We don't need to be notified again. */ if (unlikely((vhost_hlen))) /* Skip header. TODO: support TSO. */ move_iovec_hdr(vq->iov, nvq->hdr, vhost_hlen, in); else /* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF: * needed because recvmsg can modify msg_iov. */ copy_iovec_hdr(vq->iov, nvq->hdr, sock_hlen, in); msg.msg_iovlen = in; err = sock->ops->recvmsg(NULL, sock, &msg, sock_len, MSG_DONTWAIT | MSG_TRUNC); /* Userspace might have consumed the packet meanwhile: * it's not supposed to do this usually, but might be hard * to prevent. Discard data we got (if any) and keep going. */ if (unlikely(err != sock_len)) { pr_debug("Discarded rx packet: " " len %d, expected %zd\n", err, sock_len); vhost_discard_vq_desc(vq, headcount); continue; } if (unlikely(vhost_hlen) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&hdr, 0, vhost_hlen)) { vq_err(vq, "Unable to write vnet_hdr at addr %p\n", vq->iov->iov_base); break; } /* TODO: Should check and handle checksum. */ if (likely(mergeable) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&headcount, offsetof(typeof(hdr), num_buffers), sizeof hdr.num_buffers)) { vq_err(vq, "Failed num_buffers write"); vhost_discard_vq_desc(vq, headcount); break; } vhost_add_used_and_signal_n(&net->dev, vq, vq->heads, headcount); if (unlikely(vq_log)) vhost_log_write(vq, vq_log, log, vhost_len); total_len += vhost_len; if (unlikely(total_len >= VHOST_NET_WEIGHT)) { vhost_poll_queue(&vq->poll); break; } } out: mutex_unlock(&vq->mutex); } Commit Message: vhost: fix total length when packets are too short When mergeable buffers are disabled, and the incoming packet is too large for the rx buffer, get_rx_bufs returns success. This was intentional in order for make recvmsg truncate the packet and then handle_rx would detect err != sock_len and drop it. Unfortunately we pass the original sock_len to recvmsg - which means we use parts of iov not fully validated. Fix this up by detecting this overrun and doing packet drop immediately. CVE-2014-0077 Signed-off-by: Michael S. Tsirkin <mst@redhat.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
static void handle_rx(struct vhost_net *net) { struct vhost_net_virtqueue *nvq = &net->vqs[VHOST_NET_VQ_RX]; struct vhost_virtqueue *vq = &nvq->vq; unsigned uninitialized_var(in), log; struct vhost_log *vq_log; struct msghdr msg = { .msg_name = NULL, .msg_namelen = 0, .msg_control = NULL, /* FIXME: get and handle RX aux data. */ .msg_controllen = 0, .msg_iov = vq->iov, .msg_flags = MSG_DONTWAIT, }; struct virtio_net_hdr_mrg_rxbuf hdr = { .hdr.flags = 0, .hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE }; size_t total_len = 0; int err, mergeable; s16 headcount; size_t vhost_hlen, sock_hlen; size_t vhost_len, sock_len; struct socket *sock; mutex_lock(&vq->mutex); sock = vq->private_data; if (!sock) goto out; vhost_disable_notify(&net->dev, vq); vhost_hlen = nvq->vhost_hlen; sock_hlen = nvq->sock_hlen; vq_log = unlikely(vhost_has_feature(&net->dev, VHOST_F_LOG_ALL)) ? vq->log : NULL; mergeable = vhost_has_feature(&net->dev, VIRTIO_NET_F_MRG_RXBUF); while ((sock_len = peek_head_len(sock->sk))) { sock_len += sock_hlen; vhost_len = sock_len + vhost_hlen; headcount = get_rx_bufs(vq, vq->heads, vhost_len, &in, vq_log, &log, likely(mergeable) ? UIO_MAXIOV : 1); /* On error, stop handling until the next kick. */ if (unlikely(headcount < 0)) break; /* On overrun, truncate and discard */ if (unlikely(headcount > UIO_MAXIOV)) { msg.msg_iovlen = 1; err = sock->ops->recvmsg(NULL, sock, &msg, 1, MSG_DONTWAIT | MSG_TRUNC); pr_debug("Discarded rx packet: len %zd\n", sock_len); continue; } /* OK, now we need to know about added descriptors. */ if (!headcount) { if (unlikely(vhost_enable_notify(&net->dev, vq))) { /* They have slipped one in as we were * doing that: check again. */ vhost_disable_notify(&net->dev, vq); continue; } /* Nothing new? Wait for eventfd to tell us * they refilled. */ break; } /* We don't need to be notified again. */ if (unlikely((vhost_hlen))) /* Skip header. TODO: support TSO. */ move_iovec_hdr(vq->iov, nvq->hdr, vhost_hlen, in); else /* Copy the header for use in VIRTIO_NET_F_MRG_RXBUF: * needed because recvmsg can modify msg_iov. */ copy_iovec_hdr(vq->iov, nvq->hdr, sock_hlen, in); msg.msg_iovlen = in; err = sock->ops->recvmsg(NULL, sock, &msg, sock_len, MSG_DONTWAIT | MSG_TRUNC); /* Userspace might have consumed the packet meanwhile: * it's not supposed to do this usually, but might be hard * to prevent. Discard data we got (if any) and keep going. */ if (unlikely(err != sock_len)) { pr_debug("Discarded rx packet: " " len %d, expected %zd\n", err, sock_len); vhost_discard_vq_desc(vq, headcount); continue; } if (unlikely(vhost_hlen) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&hdr, 0, vhost_hlen)) { vq_err(vq, "Unable to write vnet_hdr at addr %p\n", vq->iov->iov_base); break; } /* TODO: Should check and handle checksum. */ if (likely(mergeable) && memcpy_toiovecend(nvq->hdr, (unsigned char *)&headcount, offsetof(typeof(hdr), num_buffers), sizeof hdr.num_buffers)) { vq_err(vq, "Failed num_buffers write"); vhost_discard_vq_desc(vq, headcount); break; } vhost_add_used_and_signal_n(&net->dev, vq, vq->heads, headcount); if (unlikely(vq_log)) vhost_log_write(vq, vq_log, log, vhost_len); total_len += vhost_len; if (unlikely(total_len >= VHOST_NET_WEIGHT)) { vhost_poll_queue(&vq->poll); break; } } out: mutex_unlock(&vq->mutex); }
166,461
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: my_object_init (MyObject *obj) { obj->val = 0; } Commit Message: CWE ID: CWE-264
my_object_init (MyObject *obj)
165,109