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: void P2PQuicStreamImpl::Finish() { DCHECK(!fin_sent()); quic::QuicStream::WriteOrBufferData("", /*fin=*/true, nullptr); } Commit Message: P2PQuicStream write functionality. This adds the P2PQuicStream::WriteData function and adds tests. It also adds the concept of a write buffered amount, enforcing this at the P2PQuicStreamImpl. Bug: 874296 Change-Id: Id02c8aa8d5368a87bb24a2e50dab5ef94bcae131 Reviewed-on: https://chromium-review.googlesource.com/c/1315534 Commit-Queue: Seth Hampson <shampson@chromium.org> Reviewed-by: Henrik Boström <hbos@chromium.org> Cr-Commit-Position: refs/heads/master@{#605766} CWE ID: CWE-284
void P2PQuicStreamImpl::Finish() { void P2PQuicStreamImpl::WriteData(std::vector<uint8_t> data, bool fin) { // It is up to the delegate to not write more data than the // |write_buffer_size_|. DCHECK_GE(write_buffer_size_, data.size() + write_buffered_amount_); write_buffered_amount_ += data.size(); QuicStream::WriteOrBufferData( quic::QuicStringPiece(reinterpret_cast<const char*>(data.data()), data.size()), fin, nullptr); }
172,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PluginChannel::PluginChannel() : renderer_handle_(0), renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()) { set_send_unblocking_only_during_unblock_dispatch(); ChildProcess::current()->AddRefProcess(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); } 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:
PluginChannel::PluginChannel() : renderer_id_(-1), in_send_(0), incognito_(false), filter_(new MessageFilter()) { set_send_unblocking_only_during_unblock_dispatch(); ChildProcess::current()->AddRefProcess(); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); }
170,950
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void InputDispatcher::enqueueDispatchEntryLocked( const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode) { int32_t inputTargetFlags = inputTarget->flags; if (!(inputTargetFlags & dispatchMode)) { return; } inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode; DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset, inputTarget->scaleFactor); switch (eventEntry->type) { case EventEntry::TYPE_KEY: { KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry); dispatchEntry->resolvedAction = keyEntry->action; dispatchEntry->resolvedFlags = keyEntry->flags; if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event", connection->getInputChannelName()); #endif delete dispatchEntry; return; // skip the inconsistent event } break; } case EventEntry::TYPE_MOTION: { MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry); if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN; } else { dispatchEntry->resolvedAction = motionEntry->action; } if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE && !connection->inputState.isHovering( motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event", connection->getInputChannelName()); #endif dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; } dispatchEntry->resolvedFlags = motionEntry->flags; if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) { dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED; } if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event", connection->getInputChannelName()); #endif delete dispatchEntry; return; // skip the inconsistent event } break; } } if (dispatchEntry->hasForegroundTarget()) { incrementPendingForegroundDispatchesLocked(eventEntry); } connection->outboundQueue.enqueueAtTail(dispatchEntry); traceOutboundQueueLengthLocked(connection); } Commit Message: Add new MotionEvent flag for partially obscured windows. Due to more complex window layouts resulting in lots of overlapping windows, the policy around FLAG_WINDOW_IS_OBSCURED has changed to only be set when the point at which the window was touched is obscured. Unfortunately, this doesn't prevent tapjacking attacks that overlay the dialog's text, making a potentially dangerous operation seem innocuous. To avoid this on particularly sensitive dialogs, introduce a new flag that really does tell you when your window is being even partially overlapped. We aren't exposing this as API since we plan on making the original flag more robust. This is really a workaround for system dialogs since we generally know their layout and screen position, and that they're unlikely to be overlapped by other applications. Bug: 26677796 Change-Id: I9e336afe90f262ba22015876769a9c510048fd47 CWE ID: CWE-264
void InputDispatcher::enqueueDispatchEntryLocked( const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget, int32_t dispatchMode) { int32_t inputTargetFlags = inputTarget->flags; if (!(inputTargetFlags & dispatchMode)) { return; } inputTargetFlags = (inputTargetFlags & ~InputTarget::FLAG_DISPATCH_MASK) | dispatchMode; DispatchEntry* dispatchEntry = new DispatchEntry(eventEntry, // increments ref inputTargetFlags, inputTarget->xOffset, inputTarget->yOffset, inputTarget->scaleFactor); switch (eventEntry->type) { case EventEntry::TYPE_KEY: { KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry); dispatchEntry->resolvedAction = keyEntry->action; dispatchEntry->resolvedFlags = keyEntry->flags; if (!connection->inputState.trackKey(keyEntry, dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent key event", connection->getInputChannelName()); #endif delete dispatchEntry; return; // skip the inconsistent event } break; } case EventEntry::TYPE_MOTION: { MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry); if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_OUTSIDE) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_OUTSIDE; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_EXIT; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_CANCEL; } else if (dispatchMode & InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER) { dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_DOWN; } else { dispatchEntry->resolvedAction = motionEntry->action; } if (dispatchEntry->resolvedAction == AMOTION_EVENT_ACTION_HOVER_MOVE && !connection->inputState.isHovering( motionEntry->deviceId, motionEntry->source, motionEntry->displayId)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: filling in missing hover enter event", connection->getInputChannelName()); #endif dispatchEntry->resolvedAction = AMOTION_EVENT_ACTION_HOVER_ENTER; } dispatchEntry->resolvedFlags = motionEntry->flags; if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_OBSCURED) { dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED; } if (dispatchEntry->targetFlags & InputTarget::FLAG_WINDOW_IS_PARTIALLY_OBSCURED) { dispatchEntry->resolvedFlags |= AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED; } if (!connection->inputState.trackMotion(motionEntry, dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags)) { #if DEBUG_DISPATCH_CYCLE ALOGD("channel '%s' ~ enqueueDispatchEntryLocked: skipping inconsistent motion event", connection->getInputChannelName()); #endif delete dispatchEntry; return; // skip the inconsistent event } break; } } if (dispatchEntry->hasForegroundTarget()) { incrementPendingForegroundDispatchesLocked(eventEntry); } connection->outboundQueue.enqueueAtTail(dispatchEntry); traceOutboundQueueLengthLocked(connection); }
174,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt, int newtype, struct ipv6_opt_hdr __user *newopt, int newoptlen) { int tot_len = 0; char *p; struct ipv6_txoptions *opt2; int err; if (opt) { if (newtype != IPV6_HOPOPTS && opt->hopopt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt)); if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt)); if (newtype != IPV6_RTHDR && opt->srcrt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt)); if (newtype != IPV6_DSTOPTS && opt->dst1opt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt)); } if (newopt && newoptlen) tot_len += CMSG_ALIGN(newoptlen); if (!tot_len) return NULL; tot_len += sizeof(*opt2); opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC); if (!opt2) return ERR_PTR(-ENOBUFS); memset(opt2, 0, tot_len); opt2->tot_len = tot_len; p = (char *)(opt2 + 1); err = ipv6_renew_option(opt ? opt->hopopt : NULL, newopt, newoptlen, newtype != IPV6_HOPOPTS, &opt2->hopopt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->dst0opt : NULL, newopt, newoptlen, newtype != IPV6_RTHDRDSTOPTS, &opt2->dst0opt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->srcrt : NULL, newopt, newoptlen, newtype != IPV6_RTHDR, (struct ipv6_opt_hdr **)&opt2->srcrt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->dst1opt : NULL, newopt, newoptlen, newtype != IPV6_DSTOPTS, &opt2->dst1opt, &p); if (err) goto out; opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) + (opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) + (opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0); opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0); return opt2; out: sock_kfree_s(sk, opt2, opt2->tot_len); return ERR_PTR(err); } Commit Message: ipv6: add complete rcu protection around np->opt This patch addresses multiple problems : UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions while socket is not locked : Other threads can change np->opt concurrently. Dmitry posted a syzkaller (http://github.com/google/syzkaller) program desmonstrating use-after-free. Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock() and dccp_v6_request_recv_sock() also need to use RCU protection to dereference np->opt once (before calling ipv6_dup_options()) This patch adds full RCU protection to np->opt Reported-by: Dmitry Vyukov <dvyukov@google.com> Signed-off-by: Eric Dumazet <edumazet@google.com> Acked-by: Hannes Frederic Sowa <hannes@stressinduktion.org> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-416
ipv6_renew_options(struct sock *sk, struct ipv6_txoptions *opt, int newtype, struct ipv6_opt_hdr __user *newopt, int newoptlen) { int tot_len = 0; char *p; struct ipv6_txoptions *opt2; int err; if (opt) { if (newtype != IPV6_HOPOPTS && opt->hopopt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->hopopt)); if (newtype != IPV6_RTHDRDSTOPTS && opt->dst0opt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst0opt)); if (newtype != IPV6_RTHDR && opt->srcrt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->srcrt)); if (newtype != IPV6_DSTOPTS && opt->dst1opt) tot_len += CMSG_ALIGN(ipv6_optlen(opt->dst1opt)); } if (newopt && newoptlen) tot_len += CMSG_ALIGN(newoptlen); if (!tot_len) return NULL; tot_len += sizeof(*opt2); opt2 = sock_kmalloc(sk, tot_len, GFP_ATOMIC); if (!opt2) return ERR_PTR(-ENOBUFS); memset(opt2, 0, tot_len); atomic_set(&opt2->refcnt, 1); opt2->tot_len = tot_len; p = (char *)(opt2 + 1); err = ipv6_renew_option(opt ? opt->hopopt : NULL, newopt, newoptlen, newtype != IPV6_HOPOPTS, &opt2->hopopt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->dst0opt : NULL, newopt, newoptlen, newtype != IPV6_RTHDRDSTOPTS, &opt2->dst0opt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->srcrt : NULL, newopt, newoptlen, newtype != IPV6_RTHDR, (struct ipv6_opt_hdr **)&opt2->srcrt, &p); if (err) goto out; err = ipv6_renew_option(opt ? opt->dst1opt : NULL, newopt, newoptlen, newtype != IPV6_DSTOPTS, &opt2->dst1opt, &p); if (err) goto out; opt2->opt_nflen = (opt2->hopopt ? ipv6_optlen(opt2->hopopt) : 0) + (opt2->dst0opt ? ipv6_optlen(opt2->dst0opt) : 0) + (opt2->srcrt ? ipv6_optlen(opt2->srcrt) : 0); opt2->opt_flen = (opt2->dst1opt ? ipv6_optlen(opt2->dst1opt) : 0); return opt2; out: sock_kfree_s(sk, opt2, opt2->tot_len); return ERR_PTR(err); }
167,331
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int32 CommandBufferProxyImpl::RegisterTransferBuffer( base::SharedMemory* shared_memory, size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer( route_id_, shared_memory->handle(), // Returns FileDescriptor with auto_close off. size, id_request, &id))) { return -1; } return id; } 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:
int32 CommandBufferProxyImpl::RegisterTransferBuffer( base::SharedMemory* shared_memory, size_t size, int32 id_request) { if (last_state_.error != gpu::error::kNoError) return -1; // Returns FileDescriptor with auto_close off. base::SharedMemoryHandle handle = shared_memory->handle(); #if defined(OS_WIN) // Windows needs to explicitly duplicate the handle out to another process. if (!sandbox::BrokerDuplicateHandle(handle, channel_->gpu_pid(), &handle, FILE_MAP_WRITE, 0)) { return -1; } #endif int32 id; if (!Send(new GpuCommandBufferMsg_RegisterTransferBuffer( route_id_, handle, size, id_request, &id))) { return -1; } return id; }
170,927
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; } Commit Message: CWE ID: CWE-264
x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Is this being called after the refusal deadline? */ if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) { verbose("Rejected X11 connection after ForwardX11Timeout " "expired"); return -1; } /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; }
164,666
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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* allocFromUTF32(const char32_t* in, size_t len) { if (len == 0) { return getEmptyString(); } const ssize_t bytes = utf32_to_utf8_length(in, len); if (bytes < 0) { return getEmptyString(); } SharedBuffer* buf = SharedBuffer::alloc(bytes+1); ALOG_ASSERT(buf, "Unable to allocate shared buffer"); if (!buf) { return getEmptyString(); } char* str = (char*) buf->data(); utf32_to_utf8(in, len, str); return str; } Commit Message: libutils/Unicode.cpp: Correct length computation and add checks for utf16->utf8 Inconsistent behaviour between utf16_to_utf8 and utf16_to_utf8_length is causing a heap overflow. Correcting the length computation and adding bound checks to the conversion functions. Test: ran libutils_tests Bug: 29250543 Change-Id: I6115e3357141ed245c63c6eb25fc0fd0a9a7a2bb (cherry picked from commit c4966a363e46d2e1074d1a365e232af0dcedd6a1) CWE ID: CWE-119
static char* allocFromUTF32(const char32_t* in, size_t len) { if (len == 0) { return getEmptyString(); } const ssize_t resultStrLen = utf32_to_utf8_length(in, len) + 1; if (resultStrLen < 1) { return getEmptyString(); } SharedBuffer* buf = SharedBuffer::alloc(resultStrLen); ALOG_ASSERT(buf, "Unable to allocate shared buffer"); if (!buf) { return getEmptyString(); } char* resultStr = (char*) buf->data(); utf32_to_utf8(in, len, resultStr, resultStrLen); return resultStr; }
173,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: BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio) { int i; BIO *out = NULL, *btmp = NULL; X509_ALGOR *xa = NULL; const EVP_CIPHER *evp_cipher = NULL; STACK_OF(X509_ALGOR) *md_sk = NULL; STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL; X509_ALGOR *xalg = NULL; PKCS7_RECIP_INFO *ri = NULL; ASN1_OCTET_STRING *os = NULL; i = OBJ_obj2nid(p7->type); p7->state = PKCS7_S_HEADER; if (evp_cipher == NULL) { PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED); goto err; } break; case NID_pkcs7_digest: xa = p7->d.digest->md; os = PKCS7_get_octet_string(p7->d.digest->contents); break; case NID_pkcs7_data: break; default: PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE); goto err; } Commit Message: CWE ID:
BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio) { int i; BIO *out = NULL, *btmp = NULL; X509_ALGOR *xa = NULL; const EVP_CIPHER *evp_cipher = NULL; STACK_OF(X509_ALGOR) *md_sk = NULL; STACK_OF(PKCS7_RECIP_INFO) *rsk = NULL; X509_ALGOR *xalg = NULL; PKCS7_RECIP_INFO *ri = NULL; ASN1_OCTET_STRING *os = NULL; if (p7 == NULL) { PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_INVALID_NULL_POINTER); return NULL; } /* * The content field in the PKCS7 ContentInfo is optional, but that really * only applies to inner content (precisely, detached signatures). * * When reading content, missing outer content is therefore treated as an * error. * * When creating content, PKCS7_content_new() must be called before * calling this method, so a NULL p7->d is always an error. */ if (p7->d.ptr == NULL) { PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_NO_CONTENT); return NULL; } i = OBJ_obj2nid(p7->type); p7->state = PKCS7_S_HEADER; if (evp_cipher == NULL) { PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_CIPHER_NOT_INITIALIZED); goto err; } break; case NID_pkcs7_digest: xa = p7->d.digest->md; os = PKCS7_get_octet_string(p7->d.digest->contents); break; case NID_pkcs7_data: break; default: PKCS7err(PKCS7_F_PKCS7_DATAINIT, PKCS7_R_UNSUPPORTED_CONTENT_TYPE); goto err; }
164,807
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(Array, unserialize) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pmembers, *pflags = NULL; HashTable *aht; long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { return; } aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (aht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pflags); if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { goto outexcept; } var_push_dtor(&var_hash, &pflags); --p; /* for ';' */ flags = Z_LVAL_P(pflags); /* flags needs to be verified and we also need to verify whether the next * thing we get is ';'. After that we require an 'm' or somethign else * where 'm' stands for members and anything else should be an array. If * neither 'a' or 'm' follows we have an error. */ if (*p != ';') { goto outexcept; } ++p; if (*p!='m') { if (*p!='a' && *p!='O' && *p!='C' && *p!='r') { goto outexcept; } intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; zval_ptr_dtor(&intern->array); ALLOC_INIT_ZVAL(intern->array); if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { goto outexcept; } var_push_dtor(&var_hash, &intern->array); } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) { zval_ptr_dtor(&pmembers); goto outexcept; } var_push_dtor(&var_hash, &pmembers); /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (pflags) { zval_ptr_dtor(&pflags); } return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (pflags) { zval_ptr_dtor(&pflags); } zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ /* {{{ arginfo and function table */ Commit Message: Fix bug #73029 - Missing type check when unserializing SplArray CWE ID: CWE-20
SPL_METHOD(Array, unserialize) { spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *buf; int buf_len; const unsigned char *p, *s; php_unserialize_data_t var_hash; zval *pmembers, *pflags = NULL; HashTable *aht; long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &buf, &buf_len) == FAILURE) { return; } if (buf_len == 0) { return; } aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); if (aht->nApplyCount > 0) { zend_error(E_WARNING, "Modification of ArrayObject during sorting is prohibited"); return; } /* storage */ s = p = (const unsigned char*)buf; PHP_VAR_UNSERIALIZE_INIT(var_hash); if (*p!= 'x' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pflags); if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { goto outexcept; } var_push_dtor(&var_hash, &pflags); --p; /* for ';' */ flags = Z_LVAL_P(pflags); /* flags needs to be verified and we also need to verify whether the next * thing we get is ';'. After that we require an 'm' or somethign else * where 'm' stands for members and anything else should be an array. If * neither 'a' or 'm' follows we have an error. */ if (*p != ';') { goto outexcept; } ++p; if (*p!='m') { if (*p!='a' && *p!='O' && *p!='C' && *p!='r') { goto outexcept; } intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; zval_ptr_dtor(&intern->array); ALLOC_INIT_ZVAL(intern->array); if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC) || (Z_TYPE_P(intern->array) != IS_ARRAY && Z_TYPE_P(intern->array) != IS_OBJECT)) { zval_ptr_dtor(&intern->array); goto outexcept; } var_push_dtor(&var_hash, &intern->array); } if (*p != ';') { goto outexcept; } ++p; /* members */ if (*p!= 'm' || *++p != ':') { goto outexcept; } ++p; ALLOC_INIT_ZVAL(pmembers); if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) { zval_ptr_dtor(&pmembers); goto outexcept; } var_push_dtor(&var_hash, &pmembers); /* copy members */ if (!intern->std.properties) { rebuild_object_properties(&intern->std); } zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); zval_ptr_dtor(&pmembers); /* done reading $serialized */ PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (pflags) { zval_ptr_dtor(&pflags); } return; outexcept: PHP_VAR_UNSERIALIZE_DESTROY(var_hash); if (pflags) { zval_ptr_dtor(&pflags); } zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Error at offset %ld of %d bytes", (long)((char*)p - buf), buf_len); return; } /* }}} */ /* {{{ arginfo and function table */
166,930
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass) { png_const_structp pp = ppIn; PNG_CONST standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); /* When handling interlacing some rows will be absent in each pass, the * callback still gets called, but with a NULL pointer. This is checked * in the 'else' clause below. We need our own 'cbRow', but we can't call * png_get_rowbytes because we got no info structure. */ if (new_row != NULL) { png_bytep row; /* In the case where the reader doesn't do the interlace it gives * us the y in the sub-image: */ if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7) { #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED /* Use this opportunity to validate the png 'current' APIs: */ if (y != png_get_current_row_number(pp)) png_error(pp, "png_get_current_row_number is broken"); if (pass != png_get_current_pass_number(pp)) png_error(pp, "png_get_current_pass_number is broken"); #endif y = PNG_ROW_FROM_PASS_ROW(y, pass); } /* Validate this just in case. */ if (y >= dp->h) png_error(pp, "invalid y to progressive row callback"); row = store_image_row(dp->ps, pp, 0, y); #ifdef PNG_READ_INTERLACING_SUPPORTED /* Combine the new row into the old: */ if (dp->do_interlace) { if (dp->interlace_type == PNG_INTERLACE_ADAM7) deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass); else row_copy(row, new_row, dp->pixel_size * dp->w); } else png_progressive_combine_row(pp, row, new_row); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } #ifdef PNG_READ_INTERLACING_SUPPORTED else if (dp->interlace_type == PNG_INTERLACE_ADAM7 && PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(dp->w, pass) > 0) png_error(pp, "missing row in progressive de-interlacing"); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass) { png_const_structp pp = ppIn; const standard_display *dp = voidcast(standard_display*, png_get_progressive_ptr(pp)); /* When handling interlacing some rows will be absent in each pass, the * callback still gets called, but with a NULL pointer. This is checked * in the 'else' clause below. We need our own 'cbRow', but we can't call * png_get_rowbytes because we got no info structure. */ if (new_row != NULL) { png_bytep row; /* In the case where the reader doesn't do the interlace it gives * us the y in the sub-image: */ if (dp->do_interlace && dp->interlace_type == PNG_INTERLACE_ADAM7) { #ifdef PNG_USER_TRANSFORM_INFO_SUPPORTED /* Use this opportunity to validate the png 'current' APIs: */ if (y != png_get_current_row_number(pp)) png_error(pp, "png_get_current_row_number is broken"); if (pass != png_get_current_pass_number(pp)) png_error(pp, "png_get_current_pass_number is broken"); #endif /* USER_TRANSFORM_INFO */ y = PNG_ROW_FROM_PASS_ROW(y, pass); } /* Validate this just in case. */ if (y >= dp->h) png_error(pp, "invalid y to progressive row callback"); row = store_image_row(dp->ps, pp, 0, y); /* Combine the new row into the old: */ #ifdef PNG_READ_INTERLACING_SUPPORTED if (dp->do_interlace) #endif /* READ_INTERLACING */ { if (dp->interlace_type == PNG_INTERLACE_ADAM7) deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass, dp->littleendian); else row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian); } #ifdef PNG_READ_INTERLACING_SUPPORTED else png_progressive_combine_row(pp, row, new_row); #endif /* PNG_READ_INTERLACING_SUPPORTED */ } else if (dp->interlace_type == PNG_INTERLACE_ADAM7 && PNG_ROW_IN_INTERLACE_PASS(y, pass) && PNG_PASS_COLS(dp->w, pass) > 0) png_error(pp, "missing row in progressive de-interlacing"); }
173,686
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { int closeButtonOffsetX = (kCaptionHeight - close_button_->height()) / 2; int header_width = close_button_->width() + closeButtonOffsetX * 2; return gfx::Rect(client_bounds.x(), std::max(0, client_bounds.y() - kCaptionHeight), std::max(header_width, client_bounds.width()), client_bounds.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::GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const { if (is_frameless_) return client_bounds; int closeButtonOffsetX = (kCaptionHeight - close_button_->height()) / 2; int header_width = close_button_->width() + closeButtonOffsetX * 2; return gfx::Rect(client_bounds.x(), std::max(0, client_bounds.y() - kCaptionHeight), std::max(header_width, client_bounds.width()), client_bounds.height() + kCaptionHeight); }
170,714
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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); version_ = GET_PARAM(2); // 0: high precision forward transform } 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); version_ = GET_PARAM(2); // 0: high precision forward transform bit_depth_ = GET_PARAM(3); mask_ = (1 << bit_depth_) - 1; }
174,531
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hashtable_init(hashtable_t *hashtable) { size_t i; hashtable->size = 0; hashtable->num_buckets = 0; /* index to primes[] */ hashtable->buckets = jsonp_malloc(num_buckets(hashtable) * sizeof(bucket_t)); if(!hashtable->buckets) return -1; list_init(&hashtable->list); for(i = 0; i < num_buckets(hashtable); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } return 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
int hashtable_init(hashtable_t *hashtable) { size_t i; hashtable->size = 0; hashtable->order = 3; hashtable->buckets = jsonp_malloc(hashsize(hashtable->order) * sizeof(bucket_t)); if(!hashtable->buckets) return -1; list_init(&hashtable->list); for(i = 0; i < hashsize(hashtable->order); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } return 0; }
166,531
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: vips_tracked_malloc( size_t size ) { void *buf; vips_tracked_init(); /* Need an extra sizeof(size_t) bytes to track * size of this block. Ask for an extra 16 to make sure we don't break * alignment rules. */ size += 16; if( !(buf = g_try_malloc( size )) ) { #ifdef DEBUG g_assert_not_reached(); #endif /*DEBUG*/ vips_error( "vips_tracked", _( "out of memory --- size == %dMB" ), (int) (size / (1024.0 * 1024.0)) ); g_warning( _( "out of memory --- size == %dMB" ), (int) (size / (1024.0 * 1024.0)) ); return( NULL ); } g_mutex_lock( vips_tracked_mutex ); *((size_t *)buf) = size; buf = (void *) ((char *)buf + 16); vips_tracked_mem += size; if( vips_tracked_mem > vips_tracked_mem_highwater ) vips_tracked_mem_highwater = vips_tracked_mem; vips_tracked_allocs += 1; #ifdef DEBUG_VERBOSE printf( "vips_tracked_malloc: %p, %zd bytes\n", buf, size ); #endif /*DEBUG_VERBOSE*/ g_mutex_unlock( vips_tracked_mutex ); VIPS_GATE_MALLOC( size ); return( buf ); } Commit Message: zero memory on malloc to prevent write of uninit memory under some error conditions thanks Balint CWE ID: CWE-200
vips_tracked_malloc( size_t size ) { void *buf; vips_tracked_init(); /* Need an extra sizeof(size_t) bytes to track * size of this block. Ask for an extra 16 to make sure we don't break * alignment rules. */ size += 16; if( !(buf = g_try_malloc0( size )) ) { #ifdef DEBUG g_assert_not_reached(); #endif /*DEBUG*/ vips_error( "vips_tracked", _( "out of memory --- size == %dMB" ), (int) (size / (1024.0 * 1024.0)) ); g_warning( _( "out of memory --- size == %dMB" ), (int) (size / (1024.0 * 1024.0)) ); return( NULL ); } g_mutex_lock( vips_tracked_mutex ); *((size_t *)buf) = size; buf = (void *) ((char *)buf + 16); vips_tracked_mem += size; if( vips_tracked_mem > vips_tracked_mem_highwater ) vips_tracked_mem_highwater = vips_tracked_mem; vips_tracked_allocs += 1; #ifdef DEBUG_VERBOSE printf( "vips_tracked_malloc: %p, %zd bytes\n", buf, size ); #endif /*DEBUG_VERBOSE*/ g_mutex_unlock( vips_tracked_mutex ); VIPS_GATE_MALLOC( size ); return( buf ); }
169,740
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, "\t%s (%d),", str, (31 - i)); } } } Commit Message: Fixed CVE-2018-8789 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-125
void ntlm_print_negotiate_flags(UINT32 flags) static void ntlm_print_negotiate_flags(UINT32 flags) { int i; const char* str; WLog_INFO(TAG, "negotiateFlags \"0x%08"PRIX32"\"", flags); for (i = 31; i >= 0; i--) { if ((flags >> i) & 1) { str = NTLM_NEGOTIATE_STRINGS[(31 - i)]; WLog_INFO(TAG, "\t%s (%d),", str, (31 - i)); } } }
169,275
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MaybeChangeCurrentKeyboardLayout(const std::string& section, const std::string& config_name, const ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value)) { ChangeCurrentInputMethodFromId(value.string_list_value[0]); } } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void MaybeChangeCurrentKeyboardLayout(const std::string& section, void MaybeChangeCurrentKeyboardLayout( const std::string& section, const std::string& config_name, const input_method::ImeConfigValue& value) { if (section == language_prefs::kGeneralSectionName && config_name == language_prefs::kPreloadEnginesConfigName && ContainOnlyOneKeyboardLayout(value)) { ChangeCurrentInputMethodFromId(value.string_list_value[0]); } }
170,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: bool MediaElementAudioSourceHandler::PassesCORSAccessCheck() { DCHECK(MediaElement()); return (MediaElement()->GetWebMediaPlayer() && MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) || passes_current_src_cors_access_check_; } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <rtoy@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Hongchan Choi <hongchan@chromium.org> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
bool MediaElementAudioSourceHandler::PassesCORSAccessCheck() {
173,147
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void uipc_flush_ch_locked(tUIPC_CH_ID ch_id) { char buf[UIPC_FLUSH_BUFFER_SIZE]; struct pollfd pfd; int ret; pfd.events = POLLIN; pfd.fd = uipc_main.ch[ch_id].fd; if (uipc_main.ch[ch_id].fd == UIPC_DISCONNECTED) { BTIF_TRACE_EVENT("%s() - fd disconnected. Exiting", __FUNCTION__); return; } while (1) { ret = poll(&pfd, 1, 1); BTIF_TRACE_VERBOSE("%s() - polling fd %d, revents: 0x%x, ret %d", __FUNCTION__, pfd.fd, pfd.revents, ret); if (pfd.revents & (POLLERR|POLLHUP)) { BTIF_TRACE_EVENT("%s() - POLLERR or POLLHUP. Exiting", __FUNCTION__); return; } if (ret <= 0) { BTIF_TRACE_EVENT("%s() - error (%d). Exiting", __FUNCTION__, ret); return; } /* read sufficiently large buffer to ensure flush empties socket faster than it is getting refilled */ read(pfd.fd, &buf, UIPC_FLUSH_BUFFER_SIZE); } } 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_flush_ch_locked(tUIPC_CH_ID ch_id) { char buf[UIPC_FLUSH_BUFFER_SIZE]; struct pollfd pfd; int ret; pfd.events = POLLIN; pfd.fd = uipc_main.ch[ch_id].fd; if (uipc_main.ch[ch_id].fd == UIPC_DISCONNECTED) { BTIF_TRACE_EVENT("%s() - fd disconnected. Exiting", __FUNCTION__); return; } while (1) { ret = TEMP_FAILURE_RETRY(poll(&pfd, 1, 1)); BTIF_TRACE_VERBOSE("%s() - polling fd %d, revents: 0x%x, ret %d", __FUNCTION__, pfd.fd, pfd.revents, ret); if (pfd.revents & (POLLERR|POLLHUP)) { BTIF_TRACE_EVENT("%s() - POLLERR or POLLHUP. Exiting", __FUNCTION__); return; } if (ret <= 0) { BTIF_TRACE_EVENT("%s() - error (%d). Exiting", __FUNCTION__, ret); return; } /* read sufficiently large buffer to ensure flush empties socket faster than it is getting refilled */ TEMP_FAILURE_RETRY(read(pfd.fd, &buf, UIPC_FLUSH_BUFFER_SIZE)); } }
173,497
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void EncoderTest::RunLoop(VideoSource *video) { vpx_codec_dec_cfg_t dec_cfg = {0}; stats_.Reset(); ASSERT_TRUE(passes_ == 1 || passes_ == 2); for (unsigned int pass = 0; pass < passes_; pass++) { last_pts_ = 0; if (passes_ == 1) cfg_.g_pass = VPX_RC_ONE_PASS; else if (pass == 0) cfg_.g_pass = VPX_RC_FIRST_PASS; else cfg_.g_pass = VPX_RC_LAST_PASS; BeginPassHook(pass); Encoder* const encoder = codec_->CreateEncoder(cfg_, deadline_, init_flags_, &stats_); ASSERT_TRUE(encoder != NULL); Decoder* const decoder = codec_->CreateDecoder(dec_cfg, 0); bool again; for (again = true, video->Begin(); again; video->Next()) { again = (video->img() != NULL); PreEncodeFrameHook(video); PreEncodeFrameHook(video, encoder); encoder->EncodeFrame(video, frame_flags_); CxDataIterator iter = encoder->GetCxData(); bool has_cxdata = false; bool has_dxdata = false; while (const vpx_codec_cx_pkt_t *pkt = iter.Next()) { pkt = MutateEncoderOutputHook(pkt); again = true; switch (pkt->kind) { case VPX_CODEC_CX_FRAME_PKT: has_cxdata = true; if (decoder && DoDecode()) { vpx_codec_err_t res_dec = decoder->DecodeFrame( (const uint8_t*)pkt->data.frame.buf, pkt->data.frame.sz); ASSERT_EQ(VPX_CODEC_OK, res_dec) << decoder->DecodeError(); has_dxdata = true; } ASSERT_GE(pkt->data.frame.pts, last_pts_); last_pts_ = pkt->data.frame.pts; FramePktHook(pkt); break; case VPX_CODEC_PSNR_PKT: PSNRPktHook(pkt); break; default: break; } } if (has_dxdata && has_cxdata) { const vpx_image_t *img_enc = encoder->GetPreviewFrame(); DxDataIterator dec_iter = decoder->GetDxData(); const vpx_image_t *img_dec = dec_iter.Next(); if (img_enc && img_dec) { const bool res = compare_img(img_enc, img_dec); if (!res) { // Mismatch MismatchHook(img_enc, img_dec); } } if (img_dec) DecompressedFrameHook(*img_dec, video->pts()); } if (!Continue()) break; } EndPassHook(); if (decoder) delete decoder; delete encoder; if (!Continue()) break; } } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void EncoderTest::RunLoop(VideoSource *video) { vpx_codec_dec_cfg_t dec_cfg = vpx_codec_dec_cfg_t(); stats_.Reset(); ASSERT_TRUE(passes_ == 1 || passes_ == 2); for (unsigned int pass = 0; pass < passes_; pass++) { last_pts_ = 0; if (passes_ == 1) cfg_.g_pass = VPX_RC_ONE_PASS; else if (pass == 0) cfg_.g_pass = VPX_RC_FIRST_PASS; else cfg_.g_pass = VPX_RC_LAST_PASS; BeginPassHook(pass); Encoder* const encoder = codec_->CreateEncoder(cfg_, deadline_, init_flags_, &stats_); ASSERT_TRUE(encoder != NULL); video->Begin(); encoder->InitEncoder(video); unsigned long dec_init_flags = 0; // NOLINT // Use fragment decoder if encoder outputs partitions. // NOTE: fragment decoder and partition encoder are only supported by VP8. if (init_flags_ & VPX_CODEC_USE_OUTPUT_PARTITION) dec_init_flags |= VPX_CODEC_USE_INPUT_FRAGMENTS; Decoder* const decoder = codec_->CreateDecoder(dec_cfg, dec_init_flags, 0); bool again; for (again = true; again; video->Next()) { again = (video->img() != NULL); PreEncodeFrameHook(video); PreEncodeFrameHook(video, encoder); encoder->EncodeFrame(video, frame_flags_); CxDataIterator iter = encoder->GetCxData(); bool has_cxdata = false; bool has_dxdata = false; while (const vpx_codec_cx_pkt_t *pkt = iter.Next()) { pkt = MutateEncoderOutputHook(pkt); again = true; switch (pkt->kind) { case VPX_CODEC_CX_FRAME_PKT: has_cxdata = true; if (decoder && DoDecode()) { vpx_codec_err_t res_dec = decoder->DecodeFrame( (const uint8_t*)pkt->data.frame.buf, pkt->data.frame.sz); if (!HandleDecodeResult(res_dec, *video, decoder)) break; has_dxdata = true; } ASSERT_GE(pkt->data.frame.pts, last_pts_); last_pts_ = pkt->data.frame.pts; FramePktHook(pkt); break; case VPX_CODEC_PSNR_PKT: PSNRPktHook(pkt); break; default: break; } } // Flush the decoder when there are no more fragments. if ((init_flags_ & VPX_CODEC_USE_OUTPUT_PARTITION) && has_dxdata) { const vpx_codec_err_t res_dec = decoder->DecodeFrame(NULL, 0); if (!HandleDecodeResult(res_dec, *video, decoder)) break; } if (has_dxdata && has_cxdata) { const vpx_image_t *img_enc = encoder->GetPreviewFrame(); DxDataIterator dec_iter = decoder->GetDxData(); const vpx_image_t *img_dec = dec_iter.Next(); if (img_enc && img_dec) { const bool res = compare_img(img_enc, img_dec); if (!res) { // Mismatch MismatchHook(img_enc, img_dec); } } if (img_dec) DecompressedFrameHook(*img_dec, video->pts()); } if (!Continue()) break; } EndPassHook(); if (decoder) delete decoder; delete encoder; if (!Continue()) break; } }
174,540
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ShouldUseNativeViews() { #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) return base::FeatureList::IsEnabled(kAutofillExpandedPopupViews) || base::FeatureList::IsEnabled(::features::kExperimentalUi); #else return false; #endif } Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature. Bug: 906135,831603 Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499 Reviewed-on: https://chromium-review.googlesource.com/c/1387124 Reviewed-by: Robert Kaplow <rkaplow@chromium.org> Reviewed-by: Vasilii Sukhanov <vasilii@chromium.org> Reviewed-by: Fabio Tirelo <ftirelo@chromium.org> Reviewed-by: Tommy Martino <tmartino@chromium.org> Commit-Queue: Mathieu Perreault <mathp@chromium.org> Cr-Commit-Position: refs/heads/master@{#621360} CWE ID: CWE-416
bool ShouldUseNativeViews() {
172,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: void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels, float source_sample_rate) { if (number_of_channels != source_number_of_channels_ || source_sample_rate != source_sample_rate_) { if (!number_of_channels || number_of_channels > BaseAudioContext::MaxNumberOfChannels() || !AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) { DLOG(ERROR) << "setFormat(" << number_of_channels << ", " << source_sample_rate << ") - unhandled format change"; Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = 0; source_sample_rate_ = 0; return; } Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = number_of_channels; source_sample_rate_ = source_sample_rate; if (source_sample_rate != Context()->sampleRate()) { double scale_factor = source_sample_rate / Context()->sampleRate(); multi_channel_resampler_ = std::make_unique<MultiChannelResampler>( scale_factor, number_of_channels); } else { multi_channel_resampler_.reset(); } { BaseAudioContext::GraphAutoLocker context_locker(Context()); Output(0).SetNumberOfChannels(number_of_channels); } } } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <rtoy@chromium.org> Reviewed-by: Yutaka Hirano <yhirano@chromium.org> Reviewed-by: Hongchan Choi <hongchan@chromium.org> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceHandler::SetFormat(size_t number_of_channels, float source_sample_rate) { bool is_tainted = WouldTaintOrigin(); if (is_tainted) { PrintCORSMessage(MediaElement()->currentSrc().GetString()); } if (number_of_channels != source_number_of_channels_ || source_sample_rate != source_sample_rate_) { if (!number_of_channels || number_of_channels > BaseAudioContext::MaxNumberOfChannels() || !AudioUtilities::IsValidAudioBufferSampleRate(source_sample_rate)) { DLOG(ERROR) << "setFormat(" << number_of_channels << ", " << source_sample_rate << ") - unhandled format change"; Locker<MediaElementAudioSourceHandler> locker(*this); source_number_of_channels_ = 0; source_sample_rate_ = 0; is_origin_tainted_ = is_tainted; return; } // Synchronize with process() to protect |source_number_of_channels_|, // |source_sample_rate_|, |multi_channel_resampler_|. and // |is_origin_tainted_|. Locker<MediaElementAudioSourceHandler> locker(*this); is_origin_tainted_ = is_tainted; source_number_of_channels_ = number_of_channels; source_sample_rate_ = source_sample_rate; if (source_sample_rate != Context()->sampleRate()) { double scale_factor = source_sample_rate / Context()->sampleRate(); multi_channel_resampler_ = std::make_unique<MultiChannelResampler>( scale_factor, number_of_channels); } else { multi_channel_resampler_.reset(); } { BaseAudioContext::GraphAutoLocker context_locker(Context()); Output(0).SetNumberOfChannels(number_of_channels); } } }
173,150
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */ { struct _store_object *obj; int failure = 0; if (!EG(objects_store).object_buckets) { return; } obj = &EG(objects_store).object_buckets[handle].bucket.obj; /* Make sure we hold a reference count during the destructor call otherwise, when the destructor ends the storage might be freed when the refcount reaches 0 a second time */ if (EG(objects_store).object_buckets[handle].valid) { if (obj->refcount == 1) { if (!EG(objects_store).object_buckets[handle].destructor_called) { EG(objects_store).object_buckets[handle].destructor_called = 1; if (obj->dtor) { if (handlers && !obj->handlers) { obj->handlers = handlers; } zend_try { obj->dtor(obj->object, handle TSRMLS_CC); } zend_catch { failure = 1; } zend_end_try(); } } /* re-read the object from the object store as the store might have been reallocated in the dtor */ obj = &EG(objects_store).object_buckets[handle].bucket.obj; if (obj->refcount == 1) { GC_REMOVE_ZOBJ_FROM_BUFFER(obj); if (obj->free_storage) { zend_try { obj->free_storage(obj->object TSRMLS_CC); } zend_catch { failure = 1; } zend_end_try(); } ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST(); } } } obj->refcount--; #if ZEND_DEBUG_OBJECTS if (obj->refcount == 0) { fprintf(stderr, "Deallocated object id #%d\n", handle); } else { fprintf(stderr, "Decreased refcount of object id #%d\n", handle); } #endif if (failure) { zend_bailout(); } } /* }}} */ Commit Message: Fix bug #73052 - Memory Corruption in During Deserialized-object Destruction CWE ID: CWE-119
ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */ { struct _store_object *obj; int failure = 0; if (!EG(objects_store).object_buckets) { return; } obj = &EG(objects_store).object_buckets[handle].bucket.obj; /* Make sure we hold a reference count during the destructor call otherwise, when the destructor ends the storage might be freed when the refcount reaches 0 a second time */ if (EG(objects_store).object_buckets[handle].valid) { if (obj->refcount == 1) { if (!EG(objects_store).object_buckets[handle].destructor_called) { EG(objects_store).object_buckets[handle].destructor_called = 1; if (obj->dtor) { if (handlers && !obj->handlers) { obj->handlers = handlers; } zend_try { obj->dtor(obj->object, handle TSRMLS_CC); } zend_catch { failure = 1; } zend_end_try(); } } /* re-read the object from the object store as the store might have been reallocated in the dtor */ obj = &EG(objects_store).object_buckets[handle].bucket.obj; if (obj->refcount == 1) { GC_REMOVE_ZOBJ_FROM_BUFFER(obj); if (obj->free_storage) { zend_try { obj->free_storage(obj->object TSRMLS_CC); } zend_catch { failure = 1; } zend_end_try(); } ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST(); } } } obj->refcount--; #if ZEND_DEBUG_OBJECTS if (obj->refcount == 0) { fprintf(stderr, "Deallocated object id #%d\n", handle); } else { fprintf(stderr, "Decreased refcount of object id #%d\n", handle); } #endif if (failure) { zend_bailout(); } } /* }}} */
166,939
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 XMLHttpRequest::didTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); clearResponse(); clearRequest(); m_error = true; m_exceptionCode = TimeoutError; if (!m_async) { m_state = DONE; m_exceptionCode = TimeoutError; return; } changeState(DONE); if (!m_uploadComplete) { m_uploadComplete = true; if (m_upload && m_uploadEventsAllowed) m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().timeoutEvent)); } Commit Message: Don't dispatch events when XHR is set to sync mode Any of readystatechange, progress, abort, error, timeout and loadend event are not specified to be dispatched in sync mode in the latest spec. Just an exception corresponding to the failure is thrown. Clean up for readability done in this CL - factor out dispatchEventAndLoadEnd calling code - make didTimeout() private - give error handling methods more descriptive names - set m_exceptionCode in failure type specific methods -- Note that for didFailRedirectCheck, m_exceptionCode was not set in networkError(), but was set at the end of createRequest() This CL is prep for fixing crbug.com/292422 BUG=292422 Review URL: https://chromiumcodereview.appspot.com/24225002 git-svn-id: svn://svn.chromium.org/blink/trunk@158046 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void XMLHttpRequest::didTimeout() void XMLHttpRequest::handleDidTimeout() { RefPtr<XMLHttpRequest> protect(this); internalAbort(); m_exceptionCode = TimeoutError; handleDidFailGeneric(); if (!m_async) { m_state = DONE; return; } changeState(DONE); dispatchEventAndLoadEnd(eventNames().timeoutEvent); }
171,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BufferQueueConsumer::dump(String8& result, const char* prefix) const { mCore->dump(result, prefix); } Commit Message: BQ: Add permission check to BufferQueueConsumer::dump Bug 27046057 Change-Id: Id7bd8cf95045b497943ea39dde49e877aa6f5c4e CWE ID: CWE-264
void BufferQueueConsumer::dump(String8& result, const char* prefix) const { const IPCThreadState* ipc = IPCThreadState::self(); const pid_t pid = ipc->getCallingPid(); const uid_t uid = ipc->getCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(String16( "android.permission.DUMP"), pid, uid)) { result.appendFormat("Permission Denial: can't dump BufferQueueConsumer " "from pid=%d, uid=%d\n", pid, uid); } else { mCore->dump(result, prefix); } }
174,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: static int decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-1]; } return 0; } Commit Message: Fix out of bounds access in codebook processing Bug: 62800140 Test: ran poc, CTS Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37 (cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0) CWE ID: CWE-200
static int decode_map(codebook *s, oggpack_buffer *b, ogg_int32_t *v, int point){ ogg_uint32_t entry = decode_packed_entry_number(s,b); int i; if(oggpack_eop(b))return(-1); /* 1 used by test file 0 */ /* according to decode type */ switch(s->dec_type){ case 1:{ /* packed vector of values */ int mask=(1<<s->q_bits)-1; for(i=0;i<s->dim;i++){ v[i]=entry&mask; entry>>=s->q_bits; } break; } case 2:{ /* packed vector of column offsets */ int mask=(1<<s->q_pack)-1; for(i=0;i<s->dim;i++){ if(s->q_bits<=8) v[i]=((unsigned char *)(s->q_val))[entry&mask]; else v[i]=((ogg_uint16_t *)(s->q_val))[entry&mask]; entry>>=s->q_pack; } break; } case 3:{ /* offset into array */ void *ptr=((char *)s->q_val)+entry*s->q_pack; if(s->q_bits<=8){ for(i=0;i<s->dim;i++) v[i]=((unsigned char *)ptr)[i]; }else{ for(i=0;i<s->dim;i++) v[i]=((ogg_uint16_t *)ptr)[i]; } break; } default: return -1; } /* we have the unpacked multiplicands; compute final vals */ { int shiftM = point-s->q_delp; ogg_int32_t add = point-s->q_minp; int mul = s->q_del; if(add>0) add= s->q_min >> add; else add= s->q_min << -add; if (shiftM<0) { mul <<= -shiftM; shiftM = 0; } add <<= shiftM; for(i=0;i<s->dim;i++) v[i]= ((add + v[i] * mul) >> shiftM); if(s->q_seq) for(i=1;i<s->dim;i++) v[i]+=v[i-1]; } return 0; }
173,983
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: _gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG (printf ("Reading gd2 header info\n")); for (i = 0; i < 4; i++) { ch = gdGetC (in); if (ch == EOF) { goto fail1; }; id[i] = ch; }; id[4] = 0; GD2_DBG (printf ("Got file code: %s\n", id)); /* Equiv. of 'magick'. */ if (strcmp (id, GD2_ID) != 0) { GD2_DBG (printf ("Not a valid gd2 file\n")); goto fail1; }; /* Version */ if (gdGetWord (vers, in) != 1) { goto fail1; }; GD2_DBG (printf ("Version: %d\n", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG (printf ("Bad version: %d\n", *vers)); goto fail1; }; /* Image Size */ if (!gdGetWord (sx, in)) { GD2_DBG (printf ("Could not get x-size\n")); goto fail1; } if (!gdGetWord (sy, in)) { GD2_DBG (printf ("Could not get y-size\n")); goto fail1; } GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord (cs, in) != 1) { goto fail1; }; GD2_DBG (printf ("ChunkSize: %d\n", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG (printf ("Bad chunk size: %d\n", *cs)); goto fail1; }; /* Data Format */ if (gdGetWord (fmt, in) != 1) { goto fail1; }; GD2_DBG (printf ("Format: %d\n", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG (printf ("Bad data format: %d\n", *fmt)); goto fail1; }; /* # of chunks wide */ if (gdGetWord (ncx, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks Wide\n", *ncx)); /* # of chunks high */ if (gdGetWord (ncy, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks vertically\n", *ncy)); if (gd2_compressed (*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG (printf ("Reading %d chunk index entries\n", nc)); sidx = sizeof (t_chunk_info) * nc; cidx = gdCalloc (sidx, 1); if (!cidx) { goto fail1; } for (i = 0; i < nc; i++) { if (gdGetInt (&cidx[i].offset, in) != 1) { goto fail2; }; if (gdGetInt (&cidx[i].size, in) != 1) { goto fail2; }; }; *chunkIdx = cidx; }; GD2_DBG (printf ("gd2 header complete\n")); return 1; fail2: gdFree(cidx); fail1: return 0; } Commit Message: gd2: handle corrupt images better (CVE-2016-3074) Make sure we do some range checking on corrupted chunks. Thanks to Hans Jerry Illikainen <hji@dyntopia.com> for indepth report and reproducer information. Made for easy test case writing :). CWE ID: CWE-189
_gd2GetHeader (gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) { int i; int ch; char id[5]; t_chunk_info *cidx; int sidx; int nc; GD2_DBG (printf ("Reading gd2 header info\n")); for (i = 0; i < 4; i++) { ch = gdGetC (in); if (ch == EOF) { goto fail1; }; id[i] = ch; }; id[4] = 0; GD2_DBG (printf ("Got file code: %s\n", id)); /* Equiv. of 'magick'. */ if (strcmp (id, GD2_ID) != 0) { GD2_DBG (printf ("Not a valid gd2 file\n")); goto fail1; }; /* Version */ if (gdGetWord (vers, in) != 1) { goto fail1; }; GD2_DBG (printf ("Version: %d\n", *vers)); if ((*vers != 1) && (*vers != 2)) { GD2_DBG (printf ("Bad version: %d\n", *vers)); goto fail1; }; /* Image Size */ if (!gdGetWord (sx, in)) { GD2_DBG (printf ("Could not get x-size\n")); goto fail1; } if (!gdGetWord (sy, in)) { GD2_DBG (printf ("Could not get y-size\n")); goto fail1; } GD2_DBG (printf ("Image is %dx%d\n", *sx, *sy)); /* Chunk Size (pixels, not bytes!) */ if (gdGetWord (cs, in) != 1) { goto fail1; }; GD2_DBG (printf ("ChunkSize: %d\n", *cs)); if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { GD2_DBG (printf ("Bad chunk size: %d\n", *cs)); goto fail1; }; /* Data Format */ if (gdGetWord (fmt, in) != 1) { goto fail1; }; GD2_DBG (printf ("Format: %d\n", *fmt)); if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { GD2_DBG (printf ("Bad data format: %d\n", *fmt)); goto fail1; }; /* # of chunks wide */ if (gdGetWord (ncx, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks Wide\n", *ncx)); /* # of chunks high */ if (gdGetWord (ncy, in) != 1) { goto fail1; }; GD2_DBG (printf ("%d Chunks vertically\n", *ncy)); if (gd2_compressed (*fmt)) { nc = (*ncx) * (*ncy); GD2_DBG (printf ("Reading %d chunk index entries\n", nc)); sidx = sizeof (t_chunk_info) * nc; cidx = gdCalloc (sidx, 1); if (!cidx) { goto fail1; } for (i = 0; i < nc; i++) { if (gdGetInt (&cidx[i].offset, in) != 1) { goto fail2; }; if (gdGetInt (&cidx[i].size, in) != 1) { goto fail2; }; if (cidx[i].offset < 0 || cidx[i].size < 0) goto fail2; }; *chunkIdx = cidx; }; GD2_DBG (printf ("gd2 header complete\n")); return 1; fail2: gdFree(cidx); fail1: return 0; }
167,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, const Extension* extension) { bool has_permission = extension && extension->HasAPIPermissionForTab( GetTabId(contents), APIPermission::kTab); return CreateTabValue(contents, tab_strip, tab_index, has_permission ? INCLUDE_PRIVACY_SENSITIVE_FIELDS : OMIT_PRIVACY_SENSITIVE_FIELDS); } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
DictionaryValue* ExtensionTabUtil::CreateTabValue( const WebContents* contents, TabStripModel* tab_strip, int tab_index, const Extension* extension) { DictionaryValue *result = CreateTabValue(contents, tab_strip, tab_index); ScrubTabValueForExtension(contents, extension, result); return result; }
171,454
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: lookup_bytestring(netdissect_options *ndo, register const u_char *bs, const unsigned int nlen) { struct enamemem *tp; register u_int i, j, k; if (nlen >= 6) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = (bs[4] << 8) | bs[5]; } else if (nlen >= 4) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = 0; } else i = j = k = 0; tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->e_nxt) if (tp->e_addr0 == i && tp->e_addr1 == j && tp->e_addr2 == k && memcmp((const char *)bs, (const char *)(tp->e_bs), nlen) == 0) return tp; else tp = tp->e_nxt; tp->e_addr0 = i; tp->e_addr1 = j; tp->e_addr2 = k; tp->e_bs = (u_char *) calloc(1, nlen + 1); if (tp->e_bs == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); memcpy(tp->e_bs, bs, nlen); tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp)); if (tp->e_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); return tp; } Commit Message: CVE-2017-12894/In lookup_bytestring(), take the length of the byte string into account. Otherwise, if, in our search of the hash table, we come across a byte string that's shorter than the string we're looking for, we'll search past the end of the string in the hash table. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
lookup_bytestring(netdissect_options *ndo, register const u_char *bs, const unsigned int nlen) { struct bsnamemem *tp; register u_int i, j, k; if (nlen >= 6) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = (bs[4] << 8) | bs[5]; } else if (nlen >= 4) { k = (bs[0] << 8) | bs[1]; j = (bs[2] << 8) | bs[3]; i = 0; } else i = j = k = 0; tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)]; while (tp->bs_nxt) if (nlen == tp->bs_nbytes && tp->bs_addr0 == i && tp->bs_addr1 == j && tp->bs_addr2 == k && memcmp((const char *)bs, (const char *)(tp->bs_bytes), nlen) == 0) return tp; else tp = tp->bs_nxt; tp->bs_addr0 = i; tp->bs_addr1 = j; tp->bs_addr2 = k; tp->bs_bytes = (u_char *) calloc(1, nlen + 1); if (tp->bs_bytes == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); memcpy(tp->bs_bytes, bs, nlen); tp->bs_nbytes = nlen; tp->bs_nxt = (struct bsnamemem *)calloc(1, sizeof(*tp)); if (tp->bs_nxt == NULL) (*ndo->ndo_error)(ndo, "lookup_bytestring: calloc"); return tp; }
167,960
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserNonClientFrameViewAura::NonClientTopBorderHeight( bool force_restored) const { if (frame()->widget_delegate() && frame()->widget_delegate()->ShouldShowWindowTitle()) { return close_button_->bounds().bottom(); } if (!frame()->IsMaximized() || force_restored) return kTabstripTopSpacingRestored; return kTabstripTopSpacingMaximized; } Commit Message: Ash: Fix fullscreen window bounds I was computing the non-client frame top border height incorrectly for fullscreen windows, so it was trying to draw a few pixels of transparent non-client border. BUG=118774 TEST=visual Review URL: http://codereview.chromium.org/9810014 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@128014 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
int BrowserNonClientFrameViewAura::NonClientTopBorderHeight( bool force_restored) const { if (force_restored) return kTabstripTopSpacingRestored; if (frame()->IsFullscreen()) return 0; if (frame()->IsMaximized()) return kTabstripTopSpacingMaximized; if (frame()->widget_delegate() && frame()->widget_delegate()->ShouldShowWindowTitle()) { return close_button_->bounds().bottom(); } return kTabstripTopSpacingRestored; }
171,004
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc, void* pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags) { wStream* data_in; if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) { return CHANNEL_RC_OK; } if (dataFlags & CHANNEL_FLAG_FIRST) { if (drdynvc->data_in) Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = Stream_New(NULL, totalLength); } if (!(data_in = drdynvc->data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } if (!Stream_EnsureRemainingCapacity(data_in, (int) dataLength)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = NULL; return ERROR_INTERNAL_ERROR; } Stream_Write(data_in, pData, dataLength); if (dataFlags & CHANNEL_FLAG_LAST) { if (Stream_Capacity(data_in) != Stream_GetPosition(data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error"); return ERROR_INVALID_DATA; } drdynvc->data_in = NULL; Stream_SealLength(data_in); Stream_SetPosition(data_in, 0); if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*) data_in, NULL)) { WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!"); return ERROR_INTERNAL_ERROR; } } return CHANNEL_RC_OK; } Commit Message: Fix for #4866: Added additional length checks CWE ID:
static UINT drdynvc_virtual_channel_event_data_received(drdynvcPlugin* drdynvc, void* pData, UINT32 dataLength, UINT32 totalLength, UINT32 dataFlags) { wStream* data_in; if ((dataFlags & CHANNEL_FLAG_SUSPEND) || (dataFlags & CHANNEL_FLAG_RESUME)) { return CHANNEL_RC_OK; } if (dataFlags & CHANNEL_FLAG_FIRST) { if (drdynvc->data_in) Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = Stream_New(NULL, totalLength); } if (!(data_in = drdynvc->data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_New failed!"); return CHANNEL_RC_NO_MEMORY; } if (!Stream_EnsureRemainingCapacity(data_in, dataLength)) { WLog_Print(drdynvc->log, WLOG_ERROR, "Stream_EnsureRemainingCapacity failed!"); Stream_Free(drdynvc->data_in, TRUE); drdynvc->data_in = NULL; return ERROR_INTERNAL_ERROR; } Stream_Write(data_in, pData, dataLength); if (dataFlags & CHANNEL_FLAG_LAST) { if (Stream_Capacity(data_in) != Stream_GetPosition(data_in)) { WLog_Print(drdynvc->log, WLOG_ERROR, "drdynvc_plugin_process_received: read error"); return ERROR_INVALID_DATA; } drdynvc->data_in = NULL; Stream_SealLength(data_in); Stream_SetPosition(data_in, 0); if (!MessageQueue_Post(drdynvc->queue, NULL, 0, (void*) data_in, NULL)) { WLog_Print(drdynvc->log, WLOG_ERROR, "MessageQueue_Post failed!"); return ERROR_INTERNAL_ERROR; } } return CHANNEL_RC_OK; }
168,939
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: choose_volume(struct archive_read *a, struct iso9660 *iso9660) { struct file_info *file; int64_t skipsize; struct vd *vd; const void *block; char seenJoliet; vd = &(iso9660->primary); if (!iso9660->opt_support_joliet) iso9660->seenJoliet = 0; if (iso9660->seenJoliet && vd->location > iso9660->joliet.location) /* This condition is unlikely; by way of caution. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * vd->location; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position = skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } /* * While reading Root Directory, flag seenJoliet must be zero to * avoid converting special name 0x00(Current Directory) and * next byte to UCS2. */ seenJoliet = iso9660->seenJoliet;/* Save flag. */ iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; /* * If the iso image has both RockRidge and Joliet, we preferentially * use RockRidge Extensions rather than Joliet ones. */ if (vd == &(iso9660->primary) && iso9660->seenRockridge && iso9660->seenJoliet) iso9660->seenJoliet = 0; if (vd == &(iso9660->primary) && !iso9660->seenRockridge && iso9660->seenJoliet) { /* Switch reading data from primary to joliet. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * vd->location; skipsize -= iso9660->current_position; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position += skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; } /* Store the root directory in the pending list. */ if (add_entry(a, iso9660, file) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->seenRockridge) { a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE; a->archive.archive_format_name = "ISO9660 with Rockridge extensions"; } return (ARCHIVE_OK); } Commit Message: Issue 717: Fix integer overflow when computing location of volume descriptor The multiplication here defaulted to 'int' but calculations of file positions should always use int64_t. A simple cast suffices to fix this since the base location is always 32 bits for ISO, so multiplying by the sector size will never overflow a 64-bit integer. CWE ID: CWE-190
choose_volume(struct archive_read *a, struct iso9660 *iso9660) { struct file_info *file; int64_t skipsize; struct vd *vd; const void *block; char seenJoliet; vd = &(iso9660->primary); if (!iso9660->opt_support_joliet) iso9660->seenJoliet = 0; if (iso9660->seenJoliet && vd->location > iso9660->joliet.location) /* This condition is unlikely; by way of caution. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position = skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } /* * While reading Root Directory, flag seenJoliet must be zero to * avoid converting special name 0x00(Current Directory) and * next byte to UCS2. */ seenJoliet = iso9660->seenJoliet;/* Save flag. */ iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; /* * If the iso image has both RockRidge and Joliet, we preferentially * use RockRidge Extensions rather than Joliet ones. */ if (vd == &(iso9660->primary) && iso9660->seenRockridge && iso9660->seenJoliet) iso9660->seenJoliet = 0; if (vd == &(iso9660->primary) && !iso9660->seenRockridge && iso9660->seenJoliet) { /* Switch reading data from primary to joliet. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; skipsize -= iso9660->current_position; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position += skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; } /* Store the root directory in the pending list. */ if (add_entry(a, iso9660, file) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->seenRockridge) { a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE; a->archive.archive_format_name = "ISO9660 with Rockridge extensions"; } return (ARCHIVE_OK); }
167,021
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void* H264SwDecMalloc(u32 size) { #if defined(CHECK_MEMORY_USAGE) /* Note that if the decoder has to free and reallocate some of the buffers * the total value will be invalid */ static u32 numBytes = 0; numBytes += size; DEBUG(("Allocated %d bytes, total %d\n", size, numBytes)); #endif return malloc(size); } Commit Message: h264dec: check for overflows when calculating allocation size. Bug: 27855419 Change-Id: Idabedca52913ec31ea5cb6a6109ab94e3fb2badd CWE ID: CWE-119
void* H264SwDecMalloc(u32 size) void* H264SwDecMalloc(u32 size, u32 num) { if (size > UINT32_MAX / num) { return NULL; } #if defined(CHECK_MEMORY_USAGE) /* Note that if the decoder has to free and reallocate some of the buffers * the total value will be invalid */ static u32 numBytes = 0; numBytes += size * num; DEBUG(("Allocated %d bytes, total %d\n", size, numBytes)); #endif return malloc(size * num); }
173,871
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ServiceWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); state_ = WORKER_TERMINATED; agent_ptr_.reset(); for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(nullptr, nullptr); } Commit Message: DevTools: speculative fix for crash in NetworkHandler::Disable This keeps BrowserContext* and StoragePartition* instead of RenderProcessHost* in an attemp to resolve UAF of RenderProcessHost upon closure of DevTools front-end. Bug: 801117, 783067, 780694 Change-Id: I6c2cca60cc0c29f0949d189cf918769059f80c1b Reviewed-on: https://chromium-review.googlesource.com/876657 Commit-Queue: Andrey Kosyakov <caseq@chromium.org> Reviewed-by: Dmitry Gozman <dgozman@chromium.org> Cr-Commit-Position: refs/heads/master@{#531157} CWE ID: CWE-20
void ServiceWorkerDevToolsAgentHost::WorkerDestroyed() { DCHECK_NE(WORKER_TERMINATED, state_); state_ = WORKER_TERMINATED; agent_ptr_.reset(); for (auto* inspector : protocol::InspectorHandler::ForAgentHost(this)) inspector->TargetCrashed(); for (DevToolsSession* session : sessions()) session->SetRenderer(-1, nullptr); }
172,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents); TabAttachedImpl(new_contents->web_contents()); } Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt. BUG=107201 TEST=no visible change Review URL: https://chromiumcodereview.appspot.com/11293205 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
void UnloadController::TabReplacedAt(TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { TabDetachedImpl(old_contents->web_contents()); TabAttachedImpl(new_contents->web_contents()); }
171,521
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BookmarksIOFunction::ShowSelectFileDialog( ui::SelectFileDialog::Type type, const base::FilePath& default_path) { AddRef(); WebContents* web_contents = dispatcher()->delegate()-> GetAssociatedWebContents(); select_file_dialog_ = ui::SelectFileDialog::Create( this, new ChromeSelectFilePolicy(web_contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html")); if (type == ui::SelectFileDialog::SELECT_OPEN_FILE) file_type_info.support_drive = true; select_file_dialog_->SelectFile(type, string16(), default_path, &file_type_info, 0, FILE_PATH_LITERAL(""), NULL, NULL); } Commit Message: Fix heap-use-after-free in BookmarksIOFunction::ShowSelectFileDialog. BUG=177410 Review URL: https://chromiumcodereview.appspot.com/12326086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@184586 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void BookmarksIOFunction::ShowSelectFileDialog( ui::SelectFileDialog::Type type, const base::FilePath& default_path) { if (!dispatcher()) return; // Extension was unloaded. AddRef(); WebContents* web_contents = dispatcher()->delegate()-> GetAssociatedWebContents(); select_file_dialog_ = ui::SelectFileDialog::Create( this, new ChromeSelectFilePolicy(web_contents)); ui::SelectFileDialog::FileTypeInfo file_type_info; file_type_info.extensions.resize(1); file_type_info.extensions[0].push_back(FILE_PATH_LITERAL("html")); if (type == ui::SelectFileDialog::SELECT_OPEN_FILE) file_type_info.support_drive = true; select_file_dialog_->SelectFile(type, string16(), default_path, &file_type_info, 0, FILE_PATH_LITERAL(""), NULL, NULL); }
171,435
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SetManualFallbacksForFilling(bool enabled) { if (enabled) { scoped_feature_list_.InitAndEnableFeature( password_manager::features::kEnableManualFallbacksFilling); } else { scoped_feature_list_.InitAndDisableFeature( password_manager::features::kEnableManualFallbacksFilling); } } Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature. Fixing names of password_manager kEnableManualFallbacksFilling feature as per the naming convention. Bug: 785953 Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03 Reviewed-on: https://chromium-review.googlesource.com/900566 Reviewed-by: Vaclav Brozek <vabr@chromium.org> Commit-Queue: NIKHIL SAHNI <nikhil.sahni@samsung.com> Cr-Commit-Position: refs/heads/master@{#534923} CWE ID: CWE-264
void SetManualFallbacksForFilling(bool enabled) { if (enabled) { scoped_feature_list_.InitAndEnableFeature( password_manager::features::kManualFallbacksFilling); } else { scoped_feature_list_.InitAndDisableFeature( password_manager::features::kManualFallbacksFilling); } }
171,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string &element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { *upload_required_ = USE_UPLOAD_RATES; if (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string &attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } } Commit Message: Add support for autofill server experiments BUG=none TEST=unit_tests --gtest_filter=AutoFillMetricsTest.QualityMetricsWithExperimentId:AutoFillQueryXmlParserTest.ParseExperimentId Review URL: http://codereview.chromium.org/6260027 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@73216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void AutoFillQueryXmlParser::StartElement(buzz::XmlParseContext* context, const char* name, const char** attrs) { buzz::QName qname = context->ResolveQName(name, false); const std::string& element = qname.LocalPart(); if (element.compare("autofillqueryresponse") == 0) { // We check for the upload required attribute below, but if it's not // present, we use the default upload rates. Likewise, by default we assume // an empty experiment id. *upload_required_ = USE_UPLOAD_RATES; *experiment_id_ = std::string(); // |attrs| is a NULL-terminated list of (attribute, value) pairs. while (*attrs) { buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("uploadrequired") == 0) { if (strcmp(attrs[1], "true") == 0) *upload_required_ = UPLOAD_REQUIRED; else if (strcmp(attrs[1], "false") == 0) *upload_required_ = UPLOAD_NOT_REQUIRED; } else if (attribute_name.compare("experimentid") == 0) { *experiment_id_ = attrs[1]; } // Advance to the next (attribute, value) pair. attrs += 2; } } else if (element.compare("field") == 0) { if (!attrs[0]) { context->RaiseError(XML_ERROR_ABORTED); return; } AutoFillFieldType field_type = UNKNOWN_TYPE; buzz::QName attribute_qname = context->ResolveQName(attrs[0], true); const std::string& attribute_name = attribute_qname.LocalPart(); if (attribute_name.compare("autofilltype") == 0) { int value = GetIntValue(context, attrs[1]); field_type = static_cast<AutoFillFieldType>(value); if (field_type < 0 || field_type > MAX_VALID_FIELD_TYPE) { field_type = NO_SERVER_DATA; } } field_types_->push_back(field_type); } }
170,654
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: size_t jsvGetString(const JsVar *v, char *str, size_t len) { assert(len>0); const char *s = jsvGetConstString(v); if (s) { /* don't use strncpy here because we don't * want to pad the entire buffer with zeros */ len--; int l = 0; while (*s && l<len) { str[l] = s[l]; l++; } str[l] = 0; return l; } else if (jsvIsInt(v)) { itostr(v->varData.integer, str, 10); return strlen(str); } else if (jsvIsFloat(v)) { ftoa_bounded(v->varData.floating, str, len); return strlen(str); } else if (jsvHasCharacterData(v)) { assert(!jsvIsStringExt(v)); size_t l = len; JsvStringIterator it; jsvStringIteratorNewConst(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { if (l--<=1) { *str = 0; jsvStringIteratorFree(&it); return len; } *(str++) = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); *str = 0; return len-l; } else { JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here if (stringVar) { size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var jsvUnLock(stringVar); return l; } else { str[0] = 0; jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string"); return 0; } } } Commit Message: fix jsvGetString regression CWE ID: CWE-119
size_t jsvGetString(const JsVar *v, char *str, size_t len) { assert(len>0); const char *s = jsvGetConstString(v); if (s) { /* don't use strncpy here because we don't * want to pad the entire buffer with zeros */ len--; int l = 0; while (s[l] && l<len) { str[l] = s[l]; l++; } str[l] = 0; return l; } else if (jsvIsInt(v)) { itostr(v->varData.integer, str, 10); return strlen(str); } else if (jsvIsFloat(v)) { ftoa_bounded(v->varData.floating, str, len); return strlen(str); } else if (jsvHasCharacterData(v)) { assert(!jsvIsStringExt(v)); size_t l = len; JsvStringIterator it; jsvStringIteratorNewConst(&it, v, 0); while (jsvStringIteratorHasChar(&it)) { if (l--<=1) { *str = 0; jsvStringIteratorFree(&it); return len; } *(str++) = jsvStringIteratorGetChar(&it); jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); *str = 0; return len-l; } else { JsVar *stringVar = jsvAsString((JsVar*)v, false); // we know we're casting to non-const here if (stringVar) { size_t l = jsvGetString(stringVar, str, len); // call again - but this time with converted var jsvUnLock(stringVar); return l; } else { str[0] = 0; jsExceptionHere(JSET_INTERNALERROR, "Variable type cannot be converted to string"); return 0; } } }
169,210
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() { RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame) : NULL; } Commit Message: Pepper: Access PepperMediaDeviceManager through a WeakPtr Its lifetime is scoped to the RenderFrame, and it might go away before the hosts that refer to it. BUG=423030 Review URL: https://codereview.chromium.org/653243003 Cr-Commit-Position: refs/heads/master@{#299897} CWE ID: CWE-399
PepperMediaDeviceManager* PepperPlatformVideoCapture::GetMediaDeviceManager() { RenderFrameImpl* const render_frame = RenderFrameImpl::FromRoutingID(render_frame_id_); return render_frame ? PepperMediaDeviceManager::GetForRenderFrame(render_frame).get() : NULL; }
171,610
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Core(const OAuthProviderInfo& info, net::URLRequestContextGetter* request_context_getter) : provider_info_(info), request_context_getter_(request_context_getter), delegate_(NULL) { } Commit Message: Remove UrlFetcher from remoting and use the one in net instead. BUG=133790 TEST=Stop and restart the Me2Me host. It should still work. Review URL: https://chromiumcodereview.appspot.com/10637008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143798 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
Core(const OAuthProviderInfo& info, net::URLRequestContextGetter* request_context_getter) : provider_info_(info), request_context_getter_(request_context_getter), delegate_(NULL), url_fetcher_type_(URL_FETCHER_NONE) { }
170,805
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size) { ssize_t ret; guint watch; assert(qemu_in_coroutine()); /* Negotiation are always in main loop. */ watch = qio_channel_add_watch(ioc, G_IO_OUT, nbd_negotiate_continue, qemu_coroutine_self(), NULL); ret = nbd_write(ioc, buffer, size, NULL); g_source_remove(watch); return ret; } Commit Message: CWE ID: CWE-20
static int nbd_negotiate_write(QIOChannel *ioc, const void *buffer, size_t size)
165,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: int btpan_tap_open() { struct ifreq ifr; int fd, err; const char *clonedev = "/dev/tun"; /* open the clone device */ if ((fd = open(clonedev, O_RDWR)) < 0) { BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ); /* try to create the device */ if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0) { BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno)); close(fd); return err; } if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0) { int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); return fd; } BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME); close(fd); return INVALID_FD; } 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 btpan_tap_open() { struct ifreq ifr; int fd, err; const char *clonedev = "/dev/tun"; /* open the clone device */ if ((fd = TEMP_FAILURE_RETRY(open(clonedev, O_RDWR))) < 0) { BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno); return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ); /* try to create the device */ if ((err = TEMP_FAILURE_RETRY(ioctl(fd, TUNSETIFF, (void *) &ifr))) < 0) { BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno)); close(fd); return err; } if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0) { int flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL, 0)); TEMP_FAILURE_RETRY(fcntl(fd, F_SETFL, flags | O_NONBLOCK)); return fd; } BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME); close(fd); return INVALID_FD; }
173,445
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: explicit MountState(DriveFsHost* host) : host_(host), mojo_connection_delegate_( host_->delegate_->CreateMojoConnectionDelegate()), pending_token_(base::UnguessableToken::Create()), binding_(this) { source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()}); std::string datadir_option = base::StrCat( {"datadir=", host_->profile_path_.Append(kDataPath) .Append(host_->delegate_->GetAccountId().GetAccountIdKey()) .value()}); chromeos::disks::DiskMountManager::GetInstance()->MountPath( source_path_, "", base::StrCat( {"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}), {datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE, chromeos::MOUNT_ACCESS_MODE_READ_WRITE); auto bootstrap = mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection()); mojom::DriveFsDelegatePtr delegate; binding_.Bind(mojo::MakeRequest(&delegate)); bootstrap->Init( {base::in_place, host_->delegate_->GetAccountId().GetUserEmail()}, mojo::MakeRequest(&drivefs_), std::move(delegate)); PendingConnectionManager::Get().ExpectOpenIpcChannel( pending_token_, base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection, base::Unretained(this))); } Commit Message: Add a fake DriveFS launcher client. Using DriveFS requires building and deploying ChromeOS. Add a client for the fake DriveFS launcher to allow the use of a real DriveFS from a ChromeOS chroot to be used with a target_os="chromeos" build of chrome. This connects to the fake DriveFS launcher using mojo over a unix domain socket named by a command-line flag, using the launcher to create DriveFS instances. Bug: 848126 Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1 Reviewed-on: https://chromium-review.googlesource.com/1098434 Reviewed-by: Xiyuan Xia <xiyuan@chromium.org> Commit-Queue: Sam McNally <sammc@chromium.org> Cr-Commit-Position: refs/heads/master@{#567513} CWE ID:
explicit MountState(DriveFsHost* host) : host_(host), mojo_connection_delegate_( host_->delegate_->CreateMojoConnectionDelegate()), pending_token_(base::UnguessableToken::Create()), binding_(this) { source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()}); std::string datadir_option = base::StrCat( {"datadir=", host_->profile_path_.Append(kDataPath) .Append(host_->delegate_->GetAccountId().GetAccountIdKey()) .value()}); auto bootstrap = mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection()); mojom::DriveFsDelegatePtr delegate; binding_.Bind(mojo::MakeRequest(&delegate)); bootstrap->Init( {base::in_place, host_->delegate_->GetAccountId().GetUserEmail()}, mojo::MakeRequest(&drivefs_), std::move(delegate)); PendingConnectionManager::Get().ExpectOpenIpcChannel( pending_token_, base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection, base::Unretained(this))); chromeos::disks::DiskMountManager::GetInstance()->MountPath( source_path_, "", base::StrCat( {"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}), {datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE, chromeos::MOUNT_ACCESS_MODE_READ_WRITE); }
171,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b = NULL; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey = NULL; size_t keylen, ivlen, maclen; int r; if ((newkey = calloc(1, sizeof(*newkey))) == NULL) { r = SSH_ERR_ALLOC_FAIL; goto out; } if ((r = sshbuf_froms(m, &b)) != 0) goto out; #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 || (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 || (r = sshbuf_get_u32(b, &enc->block_size)) != 0 || (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 || (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0) goto out; if ((r = mac_setup(mac, mac->name)) != 0) goto out; if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 || (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0) goto out; if (maclen > mac->key_len) { r = SSH_ERR_INVALID_FORMAT; goto out; } mac->key_len = maclen; } if ((r = sshbuf_get_u32(b, &comp->type)) != 0 || (r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 || (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0) goto out; if (enc->name == NULL || cipher_by_name(enc->name) != enc->cipher) { r = SSH_ERR_INVALID_FORMAT; goto out; } if (sshbuf_len(b) != 0) { r = SSH_ERR_INVALID_FORMAT; goto out; } enc->key_len = keylen; enc->iv_len = ivlen; ssh->kex->newkeys[mode] = newkey; newkey = NULL; r = 0; out: free(newkey); sshbuf_free(b); return r; } Commit Message: Remove support for pre-authentication compression. Doing compression early in the protocol probably seemed reasonable in the 1990s, but today it's clearly a bad idea in terms of both cryptography (cf. multiple compression oracle attacks in TLS) and attack surface. Moreover, to support it across privilege-separation zlib needed the assistance of a complex shared-memory manager that made the required attack surface considerably larger. Prompted by Guido Vranken pointing out a compiler-elided security check in the shared memory manager found by Stack (http://css.csail.mit.edu/stack/); ok deraadt@ markus@ NB. pre-auth authentication has been disabled by default in sshd for >10 years. CWE ID: CWE-119
newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode) { struct sshbuf *b = NULL; struct sshcomp *comp; struct sshenc *enc; struct sshmac *mac; struct newkeys *newkey = NULL; size_t keylen, ivlen, maclen; int r; if ((newkey = calloc(1, sizeof(*newkey))) == NULL) { r = SSH_ERR_ALLOC_FAIL; goto out; } if ((r = sshbuf_froms(m, &b)) != 0) goto out; #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif enc = &newkey->enc; mac = &newkey->mac; comp = &newkey->comp; if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 || (r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 || (r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 || (r = sshbuf_get_u32(b, &enc->block_size)) != 0 || (r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 || (r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0) goto out; if (cipher_authlen(enc->cipher) == 0) { if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0) goto out; if ((r = mac_setup(mac, mac->name)) != 0) goto out; if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 || (r = sshbuf_get_string(b, &mac->key, &maclen)) != 0) goto out; if (maclen > mac->key_len) { r = SSH_ERR_INVALID_FORMAT; goto out; } mac->key_len = maclen; } if ((r = sshbuf_get_u32(b, &comp->type)) != 0 || (r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0) goto out; if (enc->name == NULL || cipher_by_name(enc->name) != enc->cipher) { r = SSH_ERR_INVALID_FORMAT; goto out; } if (sshbuf_len(b) != 0) { r = SSH_ERR_INVALID_FORMAT; goto out; } enc->key_len = keylen; enc->iv_len = ivlen; ssh->kex->newkeys[mode] = newkey; newkey = NULL; r = 0; out: free(newkey); sshbuf_free(b); return r; }
168,650
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto( ContainerNode& insertion_point) { HTMLElement::InsertedInto(insertion_point); LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr); if (!insertion_point.isConnected()) return kInsertionDone; DCHECK(isConnected()); if (!ShouldLoadLink() && IsInShadowTree()) { String message = "HTML element <link> is ignored in shadow tree."; GetDocument().AddConsoleMessage(ConsoleMessage::Create( kJSMessageSource, kWarningMessageLevel, message)); return kInsertionDone; } GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this); Process(); if (link_) link_->OwnerInserted(); return kInsertionDone; } Commit Message: Avoid crash when setting rel=stylesheet on <link> in shadow root. Link elements in shadow roots without rel=stylesheet are currently not added as stylesheet candidates upon insertion. This causes a crash if rel=stylesheet is set (and then loaded) later. R=futhark@chromium.org Bug: 886753 Change-Id: Ia0de2c1edf43407950f973982ee1c262a909d220 Reviewed-on: https://chromium-review.googlesource.com/1242463 Commit-Queue: Anders Ruud <andruud@chromium.org> Reviewed-by: Rune Lillesveen <futhark@chromium.org> Cr-Commit-Position: refs/heads/master@{#593907} CWE ID: CWE-416
Node::InsertionNotificationRequest HTMLLinkElement::InsertedInto( ContainerNode& insertion_point) { HTMLElement::InsertedInto(insertion_point); LogAddElementIfIsolatedWorldAndInDocument("link", relAttr, hrefAttr); if (!insertion_point.isConnected()) return kInsertionDone; DCHECK(isConnected()); GetDocument().GetStyleEngine().AddStyleSheetCandidateNode(*this); if (!ShouldLoadLink() && IsInShadowTree()) { String message = "HTML element <link> is ignored in shadow tree."; GetDocument().AddConsoleMessage(ConsoleMessage::Create( kJSMessageSource, kWarningMessageLevel, message)); return kInsertionDone; } Process(); if (link_) link_->OwnerInserted(); return kInsertionDone; }
172,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: beep_print(netdissect_options *ndo, const u_char *bp, u_int length) { if (l_strnstart("MSG", 4, (const char *)bp, length)) /* A REQuest */ ND_PRINT((ndo, " BEEP MSG")); else if (l_strnstart("RPY ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP RPY")); else if (l_strnstart("ERR ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ERR")); else if (l_strnstart("ANS ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ANS")); else if (l_strnstart("NUL ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP NUL")); else if (l_strnstart("SEQ ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP SEQ")); else if (l_strnstart("END", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP END")); else ND_PRINT((ndo, " BEEP (payload or undecoded)")); } Commit Message: CVE-2017-13010/BEEP: Do bounds checking when comparing strings. This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
beep_print(netdissect_options *ndo, const u_char *bp, u_int length) { if (l_strnstart(ndo, "MSG", 4, (const char *)bp, length)) /* A REQuest */ ND_PRINT((ndo, " BEEP MSG")); else if (l_strnstart(ndo, "RPY ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP RPY")); else if (l_strnstart(ndo, "ERR ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ERR")); else if (l_strnstart(ndo, "ANS ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP ANS")); else if (l_strnstart(ndo, "NUL ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP NUL")); else if (l_strnstart(ndo, "SEQ ", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP SEQ")); else if (l_strnstart(ndo, "END", 4, (const char *)bp, length)) ND_PRINT((ndo, " BEEP END")); else ND_PRINT((ndo, " BEEP (payload or undecoded)")); }
167,884
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 module_load( YR_SCAN_CONTEXT* context, YR_OBJECT* module_object, void* module_data, size_t module_data_size) { set_integer(1, module_object, "constants.one"); set_integer(2, module_object, "constants.two"); set_string("foo", module_object, "constants.foo"); set_string("", module_object, "constants.empty"); set_integer(1, module_object, "struct_array[1].i"); set_integer(0, module_object, "integer_array[%i]", 0); set_integer(1, module_object, "integer_array[%i]", 1); set_integer(2, module_object, "integer_array[%i]", 2); set_string("foo", module_object, "string_array[%i]", 0); set_string("bar", module_object, "string_array[%i]", 1); set_string("baz", module_object, "string_array[%i]", 2); set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3); set_string("foo", module_object, "string_dict[%s]", "foo"); set_string("bar", module_object, "string_dict[\"bar\"]"); set_string("foo", module_object, "struct_dict[%s].s", "foo"); set_integer(1, module_object, "struct_dict[%s].i", "foo"); return ERROR_SUCCESS; } Commit Message: Fix heap overflow (reported by Jurriaan Bremer) When setting a new array item with yr_object_array_set_item() the array size is doubled if the index for the new item is larger than the already allocated ones. No further checks were made to ensure that the index fits into the array after doubling its capacity. If the array capacity was for example 64, and a new object is assigned to an index larger than 128 the overflow occurs. As yr_object_array_set_item() is usually invoked with indexes that increase monotonically by one, this bug never triggered before. But the new "dotnet" module has the potential to allow the exploitation of this bug by scanning a specially crafted .NET binary. CWE ID: CWE-119
int module_load( YR_SCAN_CONTEXT* context, YR_OBJECT* module_object, void* module_data, size_t module_data_size) { set_integer(1, module_object, "constants.one"); set_integer(2, module_object, "constants.two"); set_string("foo", module_object, "constants.foo"); set_string("", module_object, "constants.empty"); set_integer(1, module_object, "struct_array[1].i"); set_integer(0, module_object, "integer_array[%i]", 0); set_integer(1, module_object, "integer_array[%i]", 1); set_integer(2, module_object, "integer_array[%i]", 2); set_integer(256, module_object, "integer_array[%i]", 256); set_string("foo", module_object, "string_array[%i]", 0); set_string("bar", module_object, "string_array[%i]", 1); set_string("baz", module_object, "string_array[%i]", 2); set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3); set_string("foo", module_object, "string_dict[%s]", "foo"); set_string("bar", module_object, "string_dict[\"bar\"]"); set_string("foo", module_object, "struct_dict[%s].s", "foo"); set_integer(1, module_object, "struct_dict[%s].i", "foo"); return ERROR_SUCCESS; }
168,044
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PersistentHistogramAllocator::GetCreateHistogramResultHistogram() { constexpr subtle::AtomicWord kHistogramUnderConstruction = 1; static subtle::AtomicWord atomic_histogram_pointer = 0; subtle::AtomicWord histogram_value = subtle::Acquire_Load(&atomic_histogram_pointer); if (histogram_value == kHistogramUnderConstruction) return nullptr; if (histogram_value) return reinterpret_cast<HistogramBase*>(histogram_value); if (subtle::NoBarrier_CompareAndSwap(&atomic_histogram_pointer, 0, kHistogramUnderConstruction) != 0) { return nullptr; } if (GlobalHistogramAllocator::Get()) { DVLOG(1) << "Creating the results-histogram inside persistent" << " memory can cause future allocations to crash if" << " that memory is ever released (for testing)."; } HistogramBase* histogram_pointer = LinearHistogram::FactoryGet( kResultHistogram, 1, CREATE_HISTOGRAM_MAX, CREATE_HISTOGRAM_MAX + 1, HistogramBase::kUmaTargetedHistogramFlag); subtle::Release_Store( &atomic_histogram_pointer, reinterpret_cast<subtle::AtomicWord>(histogram_pointer)); return histogram_pointer; } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <bcwhite@chromium.org> Reviewed-by: Alexei Svitkine <asvitkine@chromium.org> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
PersistentHistogramAllocator::GetCreateHistogramResultHistogram() {
172,133
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 put_filp(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { security_file_free(file); file_sb_list_del(file); file_free(file); } } Commit Message: get rid of s_files and files_lock The only thing we need it for is alt-sysrq-r (emergency remount r/o) and these days we can do just as well without going through the list of files. Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-17
void put_filp(struct file *file) { if (atomic_long_dec_and_test(&file->f_count)) { security_file_free(file); file_free(file); } }
166,804
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Downmix_Reset(downmix_object_t *pDownmixer, bool init) { return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int Downmix_Reset(downmix_object_t *pDownmixer, bool init) { int Downmix_Reset(downmix_object_t *pDownmixer __unused, bool init __unused) { return 0; }
173,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ixheaacd_real_synth_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer, WORD32 num_columns, FLOAT32 qmf_buf_real[][64], FLOAT32 qmf_buf_imag[][64]) { WORD32 i, j, k, l, idx; FLOAT32 g[640]; FLOAT32 w[640]; FLOAT32 synth_out[128]; FLOAT32 accu_r; WORD32 synth_size = ptr_hbe_txposer->synth_size; FLOAT32 *ptr_cos_tab_trans_qmf = (FLOAT32 *)&ixheaacd_cos_table_trans_qmf[0][0] + ptr_hbe_txposer->k_start * 32; FLOAT32 *buffer = ptr_hbe_txposer->synth_buf; for (idx = 0; idx < num_columns; idx++) { FLOAT32 loc_qmf_buf[64]; FLOAT32 *synth_buf_r = loc_qmf_buf; FLOAT32 *out_buf = ptr_hbe_txposer->ptr_input_buf + (idx + 1) * ptr_hbe_txposer->synth_size; FLOAT32 *synth_cos_tab = ptr_hbe_txposer->synth_cos_tab; const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->synth_wind_coeff; if (ptr_hbe_txposer->k_start < 0) return -1; for (k = 0; k < synth_size; k++) { WORD32 ki = ptr_hbe_txposer->k_start + k; synth_buf_r[k] = (FLOAT32)( ptr_cos_tab_trans_qmf[(k << 1) + 0] * qmf_buf_real[idx][ki] + ptr_cos_tab_trans_qmf[(k << 1) + 1] * qmf_buf_imag[idx][ki]); synth_buf_r[k + ptr_hbe_txposer->synth_size] = 0; } for (l = (20 * synth_size - 1); l >= 2 * synth_size; l--) { buffer[l] = buffer[l - 2 * synth_size]; } if (synth_size == 20) { FLOAT32 *psynth_cos_tab = synth_cos_tab; for (l = 0; l < (synth_size + 1); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[synth_size - l] = accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } for (l = (synth_size + 1); l < (2 * synth_size - synth_size / 2); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[3 * synth_size - l] = -accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[3 * synth_size >> 1] = accu_r; } else { FLOAT32 tmp; FLOAT32 *ptr_u = synth_out; WORD32 kmax = (synth_size >> 1); FLOAT32 *syn_buf = &buffer[kmax]; kmax += synth_size; if (ixheaacd_real_synth_fft != NULL) (*ixheaacd_real_synth_fft)(synth_buf_r, synth_out, synth_size * 2); else return -1; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } syn_buf = &buffer[0]; kmax -= synth_size; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } } for (i = 0; i < 5; i++) { memcpy(&g[(2 * i + 0) * synth_size], &buffer[(4 * i + 0) * synth_size], sizeof(FLOAT32) * synth_size); memcpy(&g[(2 * i + 1) * synth_size], &buffer[(4 * i + 3) * synth_size], sizeof(FLOAT32) * synth_size); } for (k = 0; k < 10 * synth_size; k++) { w[k] = g[k] * interp_window_coeff[k]; } for (i = 0; i < synth_size; i++) { accu_r = 0.0; for (j = 0; j < 10; j++) { accu_r = accu_r + w[synth_size * j + i]; } out_buf[i] = (FLOAT32)accu_r; } } return 0; } Commit Message: Fix for stack corruption in esbr Bug: 110769924 Test: poc from bug before/after Change-Id: I99c6e89902064849ea1310c271064bdeccf7f20e (cherry picked from commit 7e90d745c22695236437297cd8167a9312427a4a) (cherry picked from commit 5464927f0c1fc721fa03d1c5be77b0b43dfffc50) CWE ID: CWE-787
WORD32 ixheaacd_real_synth_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer, WORD32 num_columns, FLOAT32 qmf_buf_real[][64], FLOAT32 qmf_buf_imag[][64]) { WORD32 i, j, k, l, idx; FLOAT32 g[640]; FLOAT32 w[640]; FLOAT32 synth_out[128]; FLOAT32 accu_r; WORD32 synth_size = ptr_hbe_txposer->synth_size; FLOAT32 *ptr_cos_tab_trans_qmf = (FLOAT32 *)&ixheaacd_cos_table_trans_qmf[0][0] + ptr_hbe_txposer->k_start * 32; FLOAT32 *buffer = ptr_hbe_txposer->synth_buf; for (idx = 0; idx < num_columns; idx++) { FLOAT32 loc_qmf_buf[64]; FLOAT32 *synth_buf_r = loc_qmf_buf; FLOAT32 *out_buf = ptr_hbe_txposer->ptr_input_buf + (idx + 1) * ptr_hbe_txposer->synth_size; FLOAT32 *synth_cos_tab = ptr_hbe_txposer->synth_cos_tab; const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->synth_wind_coeff; if (ptr_hbe_txposer->k_start < 0) return -1; for (k = 0; k < synth_size; k++) { WORD32 ki = ptr_hbe_txposer->k_start + k; synth_buf_r[k] = (FLOAT32)( ptr_cos_tab_trans_qmf[(k << 1) + 0] * qmf_buf_real[idx][ki] + ptr_cos_tab_trans_qmf[(k << 1) + 1] * qmf_buf_imag[idx][ki]); synth_buf_r[k + ptr_hbe_txposer->synth_size] = 0; } for (l = (20 * synth_size - 1); l >= 2 * synth_size; l--) { buffer[l] = buffer[l - 2 * synth_size]; } if (synth_size == 20) { FLOAT32 *psynth_cos_tab = synth_cos_tab; for (l = 0; l < (synth_size + 1); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[synth_size - l] = accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } for (l = (synth_size + 1); l < (2 * synth_size - synth_size / 2); l++) { accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[0 + l] = accu_r; buffer[3 * synth_size - l] = -accu_r; psynth_cos_tab = psynth_cos_tab + synth_size; } accu_r = 0.0; for (k = 0; k < synth_size; k++) { accu_r += synth_buf_r[k] * psynth_cos_tab[k]; } buffer[3 * synth_size >> 1] = accu_r; } else { FLOAT32 tmp; FLOAT32 *ptr_u = synth_out; WORD32 kmax = (synth_size >> 1); FLOAT32 *syn_buf = &buffer[kmax]; kmax += synth_size; if (ptr_hbe_txposer->ixheaacd_real_synth_fft != NULL) (*(ptr_hbe_txposer->ixheaacd_real_synth_fft))(synth_buf_r, synth_out, synth_size * 2); else return -1; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } syn_buf = &buffer[0]; kmax -= synth_size; for (k = 0; k < kmax; k++) { tmp = ((*ptr_u++) * (*synth_cos_tab++)); tmp -= ((*ptr_u++) * (*synth_cos_tab++)); *syn_buf++ = tmp; } } for (i = 0; i < 5; i++) { memcpy(&g[(2 * i + 0) * synth_size], &buffer[(4 * i + 0) * synth_size], sizeof(FLOAT32) * synth_size); memcpy(&g[(2 * i + 1) * synth_size], &buffer[(4 * i + 3) * synth_size], sizeof(FLOAT32) * synth_size); } for (k = 0; k < 10 * synth_size; k++) { w[k] = g[k] * interp_window_coeff[k]; } for (i = 0; i < synth_size; i++) { accu_r = 0.0; for (j = 0; j < 10; j++) { accu_r = accu_r + w[synth_size * j + i]; } out_buf[i] = (FLOAT32)accu_r; } } return 0; }
174,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void CopyPixels(PixelPacket *destination, const PixelPacket *source,const MagickSizeType number_pixels) { #if !defined(MAGICKCORE_OPENMP_SUPPORT) || (MAGICKCORE_QUANTUM_DEPTH <= 8) (void) memcpy(destination,source,(size_t) number_pixels*sizeof(*source)); #else { register MagickOffsetType i; if ((number_pixels*sizeof(*source)) < MagickMaxBufferExtent) { (void) memcpy(destination,source,(size_t) number_pixels* sizeof(*source)); return; } #pragma omp parallel for for (i=0; i < (MagickOffsetType) number_pixels; i++) destination[i]=source[i]; } #endif } Commit Message: CWE ID: CWE-189
static inline void CopyPixels(PixelPacket *destination,
168,811
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: UserCloudPolicyManagerChromeOS::UserCloudPolicyManagerChromeOS( scoped_ptr<CloudPolicyStore> store, scoped_ptr<CloudExternalDataManager> external_data_manager, const base::FilePath& component_policy_cache_path, bool wait_for_policy_fetch, base::TimeDelta initial_policy_fetch_timeout, const scoped_refptr<base::SequencedTaskRunner>& task_runner, const scoped_refptr<base::SequencedTaskRunner>& file_task_runner, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) : CloudPolicyManager( PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, std::string()), store.get(), task_runner, file_task_runner, io_task_runner), store_(store.Pass()), external_data_manager_(external_data_manager.Pass()), component_policy_cache_path_(component_policy_cache_path), wait_for_policy_fetch_(wait_for_policy_fetch), policy_fetch_timeout_(false, false) { time_init_started_ = base::Time::Now(); if (wait_for_policy_fetch_) { policy_fetch_timeout_.Start( FROM_HERE, initial_policy_fetch_timeout, base::Bind(&UserCloudPolicyManagerChromeOS::OnBlockingFetchTimeout, base::Unretained(this))); } } Commit Message: Make the policy fetch for first time login blocking The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users. BUG=334584 Review URL: https://codereview.chromium.org/330843002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
UserCloudPolicyManagerChromeOS::UserCloudPolicyManagerChromeOS( scoped_ptr<CloudPolicyStore> store, scoped_ptr<CloudExternalDataManager> external_data_manager, const base::FilePath& component_policy_cache_path, bool wait_for_policy_fetch, base::TimeDelta initial_policy_fetch_timeout, const scoped_refptr<base::SequencedTaskRunner>& task_runner, const scoped_refptr<base::SequencedTaskRunner>& file_task_runner, const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) : CloudPolicyManager( PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, std::string()), store.get(), task_runner, file_task_runner, io_task_runner), store_(store.Pass()), external_data_manager_(external_data_manager.Pass()), component_policy_cache_path_(component_policy_cache_path), wait_for_policy_fetch_(wait_for_policy_fetch), policy_fetch_timeout_(false, false) { time_init_started_ = base::Time::Now(); if (wait_for_policy_fetch_ && !initial_policy_fetch_timeout.is_max()) { policy_fetch_timeout_.Start( FROM_HERE, initial_policy_fetch_timeout, base::Bind(&UserCloudPolicyManagerChromeOS::OnBlockingFetchTimeout, base::Unretained(this))); } }
171,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode) { M_fs_info_t *info = NULL; char *pold = NULL; char *pnew = NULL; M_fs_type_t type; M_bool ret = M_TRUE; if (mode & M_FS_FILE_MODE_OVERWRITE) return M_TRUE; /* If we're not overwriting we need to verify existance. * * For files we need to check if the file name exists in the * directory it's being copied to. * * For directories we need to check if the directory name * exists in the directory it's being copied to. */ if (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS) return M_FALSE; type = M_fs_info_get_type(info); M_fs_info_destroy(info); if (type != M_FS_TYPE_DIR) { /* File exists at path. */ if (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } } /* Is dir */ pold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO); pnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO); if (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } done: M_free(pnew); M_free(pold); return ret; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
static M_bool M_fs_check_overwrite_allowed(const char *p1, const char *p2, M_uint32 mode) { M_fs_info_t *info = NULL; char *pold = NULL; char *pnew = NULL; M_fs_type_t type; M_bool ret = M_TRUE; if (mode & M_FS_FILE_MODE_OVERWRITE) return M_TRUE; /* If we're not overwriting we need to verify existance. * * For files we need to check if the file name exists in the * directory it's being copied to. * * For directories we need to check if the directory name * exists in the directory it's being copied to. */ if (M_fs_info(&info, p1, M_FS_PATH_INFO_FLAGS_BASIC) != M_FS_ERROR_SUCCESS) return M_FALSE; type = M_fs_info_get_type(info); M_fs_info_destroy(info); if (type != M_FS_TYPE_DIR) { /* File exists at path. */ if (M_fs_perms_can_access(p2, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } } /* Is dir */ pold = M_fs_path_basename(p1, M_FS_SYSTEM_AUTO); pnew = M_fs_path_join(p2, pnew, M_FS_SYSTEM_AUTO); if (M_fs_perms_can_access(pnew, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) { ret = M_FALSE; goto done; } done: M_free(pnew); M_free(pold); return ret; }
169,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 FILE *open_log_file(void) { if(log_fp) /* keep it open unless we rotate */ return log_fp; log_fp = fopen(log_file, "a+"); if(log_fp == NULL) { if (daemon_mode == FALSE) { printf("Warning: Cannot open log file '%s' for writing\n", log_file); } return NULL; } (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC); return log_fp; } Commit Message: Merge branch 'maint' CWE ID: CWE-264
static FILE *open_log_file(void) { int fh; struct stat st; if(log_fp) /* keep it open unless we rotate */ return log_fp; if ((fh = open(log_file, O_RDWR|O_APPEND|O_CREAT|O_NOFOLLOW, S_IRUSR|S_IWUSR)) == -1) { if (daemon_mode == FALSE) printf("Warning: Cannot open log file '%s' for writing\n", log_file); return NULL; } log_fp = fdopen(fh, "a+"); if(log_fp == NULL) { if (daemon_mode == FALSE) printf("Warning: Cannot open log file '%s' for writing\n", log_file); return NULL; } if ((fstat(fh, &st)) == -1) { log_fp = NULL; close(fh); if (daemon_mode == FALSE) printf("Warning: Cannot fstat log file '%s'\n", log_file); return NULL; } if (st.st_nlink != 1 || (st.st_mode & S_IFMT) != S_IFREG) { log_fp = NULL; close(fh); if (daemon_mode == FALSE) printf("Warning: log file '%s' has an invalid mode\n", log_file); return NULL; } (void)fcntl(fileno(log_fp), F_SETFD, FD_CLOEXEC); return log_fp; }
166,860
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ Commit Message: Fix bug #72262 - do not overflow int CWE ID: CWE-190
SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */
167,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: bool Extension::HasAPIPermission(const std::string& function_name) const { base::AutoLock auto_lock(runtime_data_lock_); return runtime_data_.GetActivePermissions()-> HasAccessToFunction(function_name); } Commit Message: Tighten restrictions on hosted apps calling extension APIs Only allow component apps to make any API calls, and for them only allow the namespaces they explicitly have permission for (plus chrome.test - I need to see if I can rework some WebStore tests to remove even this). BUG=172369 Review URL: https://chromiumcodereview.appspot.com/12095095 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180426 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
bool Extension::HasAPIPermission(const std::string& function_name) const { base::AutoLock auto_lock(runtime_data_lock_); return runtime_data_.GetActivePermissions()-> HasAccessToFunction(function_name, true); }
171,351
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BlobDataHandle::BlobDataHandle(PassOwnPtr<BlobData> data, long long size) { UNUSED_PARAM(size); m_internalURL = BlobURL::createInternalURL(); ThreadableBlobRegistry::registerBlobURL(m_internalURL, data); } 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:
BlobDataHandle::BlobDataHandle(PassOwnPtr<BlobData> data, long long size) { UNUSED_PARAM(size); m_internalURL = BlobURL::createInternalURL(); BlobRegistry::registerBlobURL(m_internalURL, data); }
170,694
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Atom::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x00) // Display ID { status = ParseDisplay(pReader, pos, size); if (status < 0) // error return status; } else if (id == 0x1654) // StringUID ID { status = UnserializeString(pReader, pos, size, m_string_uid); if (status < 0) // error return status; } else if (id == 0x33C4) // UID ID { long long val; status = UnserializeInt(pReader, pos, size, val); if (status < 0) // error return status; m_uid = val; } else if (id == 0x11) // TimeStart ID { const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_start_timecode = val; } else if (id == 0x12) // TimeEnd ID { const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_stop_timecode = val; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Atom::Parse(
174,402
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ZEND_METHOD(CURLFile, __wakeup) { zend_update_property_string(curl_CURLFile_class, getThis(), "name", sizeof("name")-1, "" TSRMLS_CC); zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC); } Commit Message: CWE ID: CWE-416
ZEND_METHOD(CURLFile, __wakeup) { zval *_this = getThis(); zend_unset_property(curl_CURLFile_class, _this, "name", sizeof("name")-1 TSRMLS_CC); zend_update_property_string(curl_CURLFile_class, _this, "name", sizeof("name")-1, "" TSRMLS_CC); zend_throw_exception(NULL, "Unserialization of CURLFile instances is not allowed", 0 TSRMLS_CC); }
165,259
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: push_decoder_state (DECODER_STATE ds) { if (ds->idx >= ds->stacksize) { fprintf (stderr, "ERROR: decoder stack overflow!\n"); abort (); } ds->stack[ds->idx++] = ds->cur; } Commit Message: CWE ID: CWE-20
push_decoder_state (DECODER_STATE ds) { if (ds->idx >= ds->stacksize) { fprintf (stderr, "ksba: ber-decoder: stack overflow!\n"); return gpg_error (GPG_ERR_LIMIT_REACHED); } ds->stack[ds->idx++] = ds->cur; return 0; }
165,052
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_size_of_type(int color_type, int bit_depth, unsigned int *colors) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_size_of_type(int color_type, int bit_depth, unsigned int *colors) image_size_of_type(int color_type, int bit_depth, unsigned int *colors, int small) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (small) { if (pixel_depth <= 8) /* there will be one row */ return 1 << pixel_depth; else return 256; } else if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } }
173,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_BOOLEAN_context(struct asn1_data *data, bool v, int context) { asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(context)); asn1_write_uint8(data, v ? 0xFF : 0); asn1_pop_tag(data); return !data->has_error; } Commit Message: CWE ID: CWE-399
bool asn1_write_BOOLEAN_context(struct asn1_data *data, bool v, int context) { if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(context))) return false; if (!asn1_write_uint8(data, v ? 0xFF : 0)) return false; return asn1_pop_tag(data); }
164,586
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); } Commit Message: CWE ID: CWE-399
static void SRP_user_pwd_free(SRP_user_pwd *user_pwd) void SRP_user_pwd_free(SRP_user_pwd *user_pwd) { if (user_pwd == NULL) return; BN_free(user_pwd->s); BN_clear_free(user_pwd->v); OPENSSL_free(user_pwd->id); OPENSSL_free(user_pwd->info); OPENSSL_free(user_pwd); }
165,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sctp_association_free(struct sctp_association *asoc) { struct sock *sk = asoc->base.sk; struct sctp_transport *transport; struct list_head *pos, *temp; int i; /* Only real associations count against the endpoint, so * don't bother for if this is a temporary association. */ if (!asoc->temp) { list_del(&asoc->asocs); /* Decrement the backlog value for a TCP-style listening * socket. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) sk->sk_ack_backlog--; } /* Mark as dead, so other users can know this structure is * going away. */ asoc->base.dead = true; /* Dispose of any data lying around in the outqueue. */ sctp_outq_free(&asoc->outqueue); /* Dispose of any pending messages for the upper layer. */ sctp_ulpq_free(&asoc->ulpq); /* Dispose of any pending chunks on the inqueue. */ sctp_inq_free(&asoc->base.inqueue); sctp_tsnmap_free(&asoc->peer.tsn_map); /* Free ssnmap storage. */ sctp_ssnmap_free(asoc->ssnmap); /* Clean up the bound address list. */ sctp_bind_addr_free(&asoc->base.bind_addr); /* Do we need to go through all of our timers and * delete them? To be safe we will try to delete all, but we * should be able to go through and make a guess based * on our state. */ for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) { if (del_timer(&asoc->timers[i])) sctp_association_put(asoc); } /* Free peer's cached cookie. */ kfree(asoc->peer.cookie); kfree(asoc->peer.peer_random); kfree(asoc->peer.peer_chunks); kfree(asoc->peer.peer_hmacs); /* Release the transport structures. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); list_del_rcu(pos); sctp_transport_free(transport); } asoc->peer.transport_count = 0; sctp_asconf_queue_teardown(asoc); /* Free pending address space being deleted */ if (asoc->asconf_addr_del_pending != NULL) kfree(asoc->asconf_addr_del_pending); /* AUTH - Free the endpoint shared keys */ sctp_auth_destroy_keys(&asoc->endpoint_shared_keys); /* AUTH - Free the association shared key */ sctp_auth_key_put(asoc->asoc_shared_key); sctp_association_put(asoc); } Commit Message: sctp: Fix sk_ack_backlog wrap-around problem Consider the scenario: For a TCP-style socket, while processing the COOKIE_ECHO chunk in sctp_sf_do_5_1D_ce(), after it has passed a series of sanity check, a new association would be created in sctp_unpack_cookie(), but afterwards, some processing maybe failed, and sctp_association_free() will be called to free the previously allocated association, in sctp_association_free(), sk_ack_backlog value is decremented for this socket, since the initial value for sk_ack_backlog is 0, after the decrement, it will be 65535, a wrap-around problem happens, and if we want to establish new associations afterward in the same socket, ABORT would be triggered since sctp deem the accept queue as full. Fix this issue by only decrementing sk_ack_backlog for associations in the endpoint's list. Fix-suggested-by: Neil Horman <nhorman@tuxdriver.com> Signed-off-by: Xufeng Zhang <xufeng.zhang@windriver.com> Acked-by: Daniel Borkmann <dborkman@redhat.com> Acked-by: Vlad Yasevich <vyasevich@gmail.com> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID: CWE-20
void sctp_association_free(struct sctp_association *asoc) { struct sock *sk = asoc->base.sk; struct sctp_transport *transport; struct list_head *pos, *temp; int i; /* Only real associations count against the endpoint, so * don't bother for if this is a temporary association. */ if (!list_empty(&asoc->asocs)) { list_del(&asoc->asocs); /* Decrement the backlog value for a TCP-style listening * socket. */ if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) sk->sk_ack_backlog--; } /* Mark as dead, so other users can know this structure is * going away. */ asoc->base.dead = true; /* Dispose of any data lying around in the outqueue. */ sctp_outq_free(&asoc->outqueue); /* Dispose of any pending messages for the upper layer. */ sctp_ulpq_free(&asoc->ulpq); /* Dispose of any pending chunks on the inqueue. */ sctp_inq_free(&asoc->base.inqueue); sctp_tsnmap_free(&asoc->peer.tsn_map); /* Free ssnmap storage. */ sctp_ssnmap_free(asoc->ssnmap); /* Clean up the bound address list. */ sctp_bind_addr_free(&asoc->base.bind_addr); /* Do we need to go through all of our timers and * delete them? To be safe we will try to delete all, but we * should be able to go through and make a guess based * on our state. */ for (i = SCTP_EVENT_TIMEOUT_NONE; i < SCTP_NUM_TIMEOUT_TYPES; ++i) { if (del_timer(&asoc->timers[i])) sctp_association_put(asoc); } /* Free peer's cached cookie. */ kfree(asoc->peer.cookie); kfree(asoc->peer.peer_random); kfree(asoc->peer.peer_chunks); kfree(asoc->peer.peer_hmacs); /* Release the transport structures. */ list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { transport = list_entry(pos, struct sctp_transport, transports); list_del_rcu(pos); sctp_transport_free(transport); } asoc->peer.transport_count = 0; sctp_asconf_queue_teardown(asoc); /* Free pending address space being deleted */ if (asoc->asconf_addr_del_pending != NULL) kfree(asoc->asconf_addr_del_pending); /* AUTH - Free the endpoint shared keys */ sctp_auth_destroy_keys(&asoc->endpoint_shared_keys); /* AUTH - Free the association shared key */ sctp_auth_key_put(asoc->asoc_shared_key); sctp_association_put(asoc); }
166,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 MockRenderThread::RemoveRoute(int32 routing_id) { EXPECT_EQ(routing_id_, routing_id); widget_ = NULL; } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void MockRenderThread::RemoveRoute(int32 routing_id) { // We may hear this for views created from OnMsgCreateWindow as well, // in which case we don't want to track the new widget. if (routing_id_ == routing_id) widget_ = NULL; }
171,024
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SampleTable::~SampleTable() { delete[] mSampleToChunkEntries; mSampleToChunkEntries = NULL; delete[] mSyncSamples; mSyncSamples = NULL; delete mCompositionDeltaLookup; mCompositionDeltaLookup = NULL; delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; delete[] mSampleTimeEntries; mSampleTimeEntries = NULL; delete[] mTimeToSample; mTimeToSample = NULL; delete mSampleIterator; mSampleIterator = NULL; } Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d CWE ID: CWE-20
SampleTable::~SampleTable() { delete[] mSampleToChunkEntries; mSampleToChunkEntries = NULL; delete[] mSyncSamples; mSyncSamples = NULL; delete mCompositionDeltaLookup; mCompositionDeltaLookup = NULL; delete[] mCompositionTimeDeltaEntries; mCompositionTimeDeltaEntries = NULL; delete[] mSampleTimeEntries; mSampleTimeEntries = NULL; delete mSampleIterator; mSampleIterator = NULL; }
174,174
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DownloadResourceHandler::OnRequestRedirected( const net::RedirectInfo& redirect_info, network::ResourceResponse* response, std::unique_ptr<ResourceController> controller) { url::Origin new_origin(url::Origin::Create(redirect_info.new_url)); if (!follow_cross_origin_redirects_ && !first_origin_.IsSameOriginWith(new_origin)) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &NavigateOnUIThread, redirect_info.new_url, request()->url_chain(), Referrer(GURL(redirect_info.new_referrer), Referrer::NetReferrerPolicyToBlinkReferrerPolicy( redirect_info.new_referrer_policy)), GetRequestInfo()->HasUserGesture(), GetRequestInfo()->GetWebContentsGetterForRequest())); controller->Cancel(); return; } if (core_.OnRequestRedirected()) { controller->Resume(); } else { controller->Cancel(); } } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <japhet@chromium.org> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <clamy@chromium.org> Commit-Queue: Jochen Eisinger <jochen@chromium.org> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
void DownloadResourceHandler::OnRequestRedirected( const net::RedirectInfo& redirect_info, network::ResourceResponse* response, std::unique_ptr<ResourceController> controller) { url::Origin new_origin(url::Origin::Create(redirect_info.new_url)); if (!follow_cross_origin_redirects_ && !first_origin_.IsSameOriginWith(new_origin)) { base::PostTaskWithTraits( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &NavigateOnUIThread, redirect_info.new_url, request()->url_chain(), Referrer(GURL(redirect_info.new_referrer), Referrer::NetReferrerPolicyToBlinkReferrerPolicy( redirect_info.new_referrer_policy)), GetRequestInfo()->HasUserGesture(), GetRequestInfo()->GetWebContentsGetterForRequest(), GetRequestInfo()->frame_tree_node_id())); controller->Cancel(); return; } if (core_.OnRequestRedirected()) { controller->Resume(); } else { controller->Cancel(); } }
173,025
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM( uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) { GLuint count = c.count; uint32 pnames_size; if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) { return error::kOutOfBounds; } const GLenum* pnames = GetSharedMemoryAs<const GLenum*>( c.pnames_shm_id, c.pnames_shm_offset, pnames_size); if (pnames == NULL) { return error::kOutOfBounds; } scoped_array<GLenum> enums(new GLenum[count]); memcpy(enums.get(), pnames, pnames_size); uint32 num_results = 0; for (GLuint ii = 0; ii < count; ++ii) { uint32 num = util_.GLGetNumValuesReturned(enums[ii]); if (num == 0) { SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname"); return error::kNoError; } DCHECK_LE(num, 4u); if (!SafeAdd(num_results, num, &num_results)) { return error::kOutOfBounds; } } uint32 result_size = 0; if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) { return error::kOutOfBounds; } if (result_size != static_cast<uint32>(c.size)) { SetGLError(GL_INVALID_VALUE, "glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE"); return error::kNoError; } GLint* results = GetSharedMemoryAs<GLint*>( c.results_shm_id, c.results_shm_offset, result_size); if (results == NULL) { return error::kOutOfBounds; } for (uint32 ii = 0; ii < num_results; ++ii) { if (results[ii]) { return error::kInvalidArguments; } } GLint* start = results; for (GLuint ii = 0; ii < count; ++ii) { GLsizei num_written = 0; if (!GetHelper(enums[ii], results, &num_written)) { glGetIntegerv(enums[ii], results); } results += num_written; } if (static_cast<uint32>(results - start) != num_results) { return error::kOutOfBounds; } return error::kNoError; } Commit Message: Fix SafeAdd and SafeMultiply BUG=145648,145544 Review URL: https://chromiumcodereview.appspot.com/10916165 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@155478 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM( uint32 immediate_data_size, const gles2::GetMultipleIntegervCHROMIUM& c) { GLuint count = c.count; uint32 pnames_size; if (!SafeMultiplyUint32(count, sizeof(GLenum), &pnames_size)) { return error::kOutOfBounds; } const GLenum* pnames = GetSharedMemoryAs<const GLenum*>( c.pnames_shm_id, c.pnames_shm_offset, pnames_size); if (pnames == NULL) { return error::kOutOfBounds; } scoped_array<GLenum> enums(new GLenum[count]); memcpy(enums.get(), pnames, pnames_size); uint32 num_results = 0; for (GLuint ii = 0; ii < count; ++ii) { uint32 num = util_.GLGetNumValuesReturned(enums[ii]); if (num == 0) { SetGLErrorInvalidEnum("glGetMulitpleCHROMIUM", enums[ii], "pname"); return error::kNoError; } DCHECK_LE(num, 4u); if (!SafeAddUint32(num_results, num, &num_results)) { return error::kOutOfBounds; } } uint32 result_size = 0; if (!SafeMultiplyUint32(num_results, sizeof(GLint), &result_size)) { return error::kOutOfBounds; } if (result_size != static_cast<uint32>(c.size)) { SetGLError(GL_INVALID_VALUE, "glGetMulitpleCHROMIUM", "bad size GL_INVALID_VALUE"); return error::kNoError; } GLint* results = GetSharedMemoryAs<GLint*>( c.results_shm_id, c.results_shm_offset, result_size); if (results == NULL) { return error::kOutOfBounds; } for (uint32 ii = 0; ii < num_results; ++ii) { if (results[ii]) { return error::kInvalidArguments; } } GLint* start = results; for (GLuint ii = 0; ii < count; ++ii) { GLsizei num_written = 0; if (!GetHelper(enums[ii], results, &num_written)) { glGetIntegerv(enums[ii], results); } results += num_written; } if (static_cast<uint32>(results - start) != num_results) { return error::kOutOfBounds; } return error::kNoError; }
170,748
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xmp_init() { RESET_ERROR; try { bool result = SXMPFiles::Initialize(kXMPFiles_IgnoreLocalText); SXMPMeta::SetDefaultErrorCallback(&_xmp_error_callback, nullptr, 1); return result; SXMPMeta::SetDefaultErrorCallback(&_xmp_error_callback, nullptr, 1); return result; } catch (const XMP_Error &e) { set_error(e); } return false; } Commit Message: CWE ID: CWE-416
bool xmp_init() { RESET_ERROR; try { // XMP SDK 5.1.2 needs this because it has been stripped off local // text conversion the one that was done in Exempi with libiconv. bool result = SXMPFiles::Initialize(kXMPFiles_IgnoreLocalText); SXMPMeta::SetDefaultErrorCallback(&_xmp_error_callback, nullptr, 1); return result; SXMPMeta::SetDefaultErrorCallback(&_xmp_error_callback, nullptr, 1); return result; } catch (const XMP_Error &e) { set_error(e); } return false; }
165,368
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderWidgetHostViewAura::UpdateExternalTexture() { if (accelerated_compositing_state_changed_) accelerated_compositing_state_changed_ = false; if (current_surface_ != 0 && host_->is_accelerated_compositing_active()) { ui::Texture* container = image_transport_clients_[current_surface_]; window_->SetExternalTexture(container); current_surface_in_use_by_compositor_ = true; if (!container) { resize_locks_.clear(); } else { ResizeLockList::iterator it = resize_locks_.begin(); while (it != resize_locks_.end()) { gfx::Size container_size = ConvertSizeToDIP(this, container->size()); if ((*it)->expected_size() == container_size) break; ++it; } if (it != resize_locks_.end()) { ++it; ui::Compositor* compositor = GetCompositor(); if (compositor) { locks_pending_commit_.insert( locks_pending_commit_.begin(), resize_locks_.begin(), it); for (ResizeLockList::iterator it2 = resize_locks_.begin(); it2 !=it; ++it2) { it2->get()->UnlockCompositor(); } if (!compositor->HasObserver(this)) compositor->AddObserver(this); } resize_locks_.erase(resize_locks_.begin(), it); } } } else { window_->SetExternalTexture(NULL); if (ShouldReleaseFrontSurface() && host_->is_accelerated_compositing_active()) { ui::Compositor* compositor = GetCompositor(); if (compositor) { can_lock_compositor_ = NO_PENDING_COMMIT; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura:: SetSurfaceNotInUseByCompositor, AsWeakPtr())); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } } resize_locks_.clear(); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 TBR=sky@chromium.org Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::UpdateExternalTexture() { if (accelerated_compositing_state_changed_) accelerated_compositing_state_changed_ = false; if (current_surface_ != 0 && host_->is_accelerated_compositing_active()) { ui::Texture* container = image_transport_clients_[current_surface_]; window_->SetExternalTexture(container); if (!container) { resize_locks_.clear(); } else { ResizeLockList::iterator it = resize_locks_.begin(); while (it != resize_locks_.end()) { gfx::Size container_size = ConvertSizeToDIP(this, container->size()); if ((*it)->expected_size() == container_size) break; ++it; } if (it != resize_locks_.end()) { ++it; ui::Compositor* compositor = GetCompositor(); if (compositor) { locks_pending_commit_.insert( locks_pending_commit_.begin(), resize_locks_.begin(), it); for (ResizeLockList::iterator it2 = resize_locks_.begin(); it2 !=it; ++it2) { it2->get()->UnlockCompositor(); } if (!compositor->HasObserver(this)) compositor->AddObserver(this); } resize_locks_.erase(resize_locks_.begin(), it); } } } else { window_->SetExternalTexture(NULL); resize_locks_.clear(); } }
171,387
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) { if (buffer == 0) { return NULL; } Mutex::Autolock autoLock(mBufferIDLock); ssize_t index = mBufferIDToBufferHeader.indexOfKey(buffer); if (index < 0) { CLOGW("findBufferHeader: buffer %u not found", buffer); return NULL; } return mBufferIDToBufferHeader.valueAt(index); } Commit Message: DO NOT MERGE omx: check buffer port before using Bug: 28816827 Change-Id: I3d5bad4a1ef96dec544b05bb31cc6f7109aae0a5 CWE ID: CWE-119
OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader(OMX::buffer_id buffer) { OMX_BUFFERHEADERTYPE *OMXNodeInstance::findBufferHeader( OMX::buffer_id buffer, OMX_U32 portIndex) { if (buffer == 0) { return NULL; } Mutex::Autolock autoLock(mBufferIDLock); ssize_t index = mBufferIDToBufferHeader.indexOfKey(buffer); if (index < 0) { CLOGW("findBufferHeader: buffer %u not found", buffer); return NULL; } OMX_BUFFERHEADERTYPE *header = mBufferIDToBufferHeader.valueAt(index); BufferMeta *buffer_meta = static_cast<BufferMeta *>(header->pAppPrivate); if (buffer_meta->getPortIndex() != portIndex) { CLOGW("findBufferHeader: buffer %u found but with incorrect port index.", buffer); android_errorWriteLog(0x534e4554, "28816827"); return NULL; } return header; }
173,528
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int mem_resize(jas_stream_memobj_t *m, int bufsize) { unsigned char *buf; assert(bufsize >= 0); JAS_DBGLOG(100, ("mem_resize(%p, %d)\n", m, bufsize)); if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { JAS_DBGLOG(100, ("mem_resize realloc failed\n")); return -1; } JAS_DBGLOG(100, ("mem_resize realloc succeeded\n")); m->buf_ = buf; m->bufsize_ = bufsize; return 0; } Commit Message: Made some changes to the I/O stream library for memory streams. There were a number of potential problems due to the possibility of integer overflow. Changed some integral types to the larger types size_t or ssize_t. For example, the function mem_resize now takes the buffer size parameter as a size_t. Added a new function jas_stream_memopen2, which takes a buffer size specified as a size_t instead of an int. This can be used in jas_image_cmpt_create to avoid potential overflow problems. Added a new function jas_deprecated to warn about reliance on deprecated library behavior. CWE ID: CWE-190
static int mem_resize(jas_stream_memobj_t *m, int bufsize) static int mem_resize(jas_stream_memobj_t *m, size_t bufsize) { unsigned char *buf; //assert(bufsize >= 0); JAS_DBGLOG(100, ("mem_resize(%p, %zu)\n", m, bufsize)); if (!bufsize) { jas_eprintf( "mem_resize was not really designed to handle a buffer of size 0\n" "This may not work.\n" ); } if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { JAS_DBGLOG(100, ("mem_resize realloc failed\n")); return -1; } JAS_DBGLOG(100, ("mem_resize realloc succeeded\n")); m->buf_ = buf; m->bufsize_ = bufsize; return 0; }
168,750
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool ATSParser::PSISection::isCRCOkay() const { if (!isComplete()) { return false; } uint8_t* data = mBuffer->data(); if ((data[1] & 0x80) == 0) { return true; } unsigned sectionLength = U16_AT(data + 1) & 0xfff; ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes); sectionLength -= mSkipBytes; uint32_t crc = 0xffffffff; for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) { uint8_t b = data[i]; int index = ((crc >> 24) ^ (b & 0xff)) & 0xff; crc = CRC_TABLE[index] ^ (crc << 8); } ALOGV("crc: %08x\n", crc); return (crc == 0); } Commit Message: Check section size when verifying CRC Bug: 28333006 Change-Id: Ief7a2da848face78f0edde21e2f2009316076679 CWE ID: CWE-119
bool ATSParser::PSISection::isCRCOkay() const { if (!isComplete()) { return false; } uint8_t* data = mBuffer->data(); if ((data[1] & 0x80) == 0) { return true; } unsigned sectionLength = U16_AT(data + 1) & 0xfff; ALOGV("sectionLength %u, skip %u", sectionLength, mSkipBytes); if(sectionLength < mSkipBytes) { ALOGE("b/28333006"); android_errorWriteLog(0x534e4554, "28333006"); return false; } sectionLength -= mSkipBytes; uint32_t crc = 0xffffffff; for(unsigned i = 0; i < sectionLength + 4 /* crc */; i++) { uint8_t b = data[i]; int index = ((crc >> 24) ^ (b & 0xff)) & 0xff; crc = CRC_TABLE[index] ^ (crc << 8); } ALOGV("crc: %08x\n", crc); return (crc == 0); }
173,769
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode, unsigned int flags) { struct ext4_extent_header *neh; struct buffer_head *bh; ext4_fsblk_t newblock, goal = 0; struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es; int err = 0; /* Try to prepend new index to old one */ if (ext_depth(inode)) goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode))); if (goal > le32_to_cpu(es->s_first_data_block)) { flags |= EXT4_MB_HINT_TRY_GOAL; goal--; } else goal = ext4_inode_to_goal_block(inode); newblock = ext4_new_meta_blocks(handle, inode, goal, flags, NULL, &err); if (newblock == 0) return err; bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) return -ENOMEM; lock_buffer(bh); err = ext4_journal_get_create_access(handle, bh); if (err) { unlock_buffer(bh); goto out; } /* move top-level index/leaf into new block */ memmove(bh->b_data, EXT4_I(inode)->i_data, sizeof(EXT4_I(inode)->i_data)); /* set size of new block */ neh = ext_block_hdr(bh); /* old root could have indexes or leaves * so calculate e_max right way */ if (ext_depth(inode)) neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0)); else neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0)); neh->eh_magic = EXT4_EXT_MAGIC; ext4_extent_block_csum_set(inode, neh); set_buffer_uptodate(bh); unlock_buffer(bh); err = ext4_handle_dirty_metadata(handle, inode, bh); if (err) goto out; /* Update top-level index: num,max,pointer */ neh = ext_inode_hdr(inode); neh->eh_entries = cpu_to_le16(1); ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock); if (neh->eh_depth == 0) { /* Root extent block becomes index block */ neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0)); EXT_FIRST_INDEX(neh)->ei_block = EXT_FIRST_EXTENT(neh)->ee_block; } ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n", le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max), le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block), ext4_idx_pblock(EXT_FIRST_INDEX(neh))); le16_add_cpu(&neh->eh_depth, 1); ext4_mark_inode_dirty(handle, inode); out: brelse(bh); return err; } Commit Message: ext4: zero out the unused memory region in the extent tree block This commit zeroes out the unused memory region in the buffer_head corresponding to the extent metablock after writing the extent header and the corresponding extent node entries. This is done to prevent random uninitialized data from getting into the filesystem when the extent block is synced. This fixes CVE-2019-11833. Signed-off-by: Sriram Rajagopalan <sriramr@arista.com> Signed-off-by: Theodore Ts'o <tytso@mit.edu> Cc: stable@kernel.org CWE ID: CWE-200
static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode, unsigned int flags) { struct ext4_extent_header *neh; struct buffer_head *bh; ext4_fsblk_t newblock, goal = 0; struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es; int err = 0; size_t ext_size = 0; /* Try to prepend new index to old one */ if (ext_depth(inode)) goal = ext4_idx_pblock(EXT_FIRST_INDEX(ext_inode_hdr(inode))); if (goal > le32_to_cpu(es->s_first_data_block)) { flags |= EXT4_MB_HINT_TRY_GOAL; goal--; } else goal = ext4_inode_to_goal_block(inode); newblock = ext4_new_meta_blocks(handle, inode, goal, flags, NULL, &err); if (newblock == 0) return err; bh = sb_getblk_gfp(inode->i_sb, newblock, __GFP_MOVABLE | GFP_NOFS); if (unlikely(!bh)) return -ENOMEM; lock_buffer(bh); err = ext4_journal_get_create_access(handle, bh); if (err) { unlock_buffer(bh); goto out; } ext_size = sizeof(EXT4_I(inode)->i_data); /* move top-level index/leaf into new block */ memmove(bh->b_data, EXT4_I(inode)->i_data, ext_size); /* zero out unused area in the extent block */ memset(bh->b_data + ext_size, 0, inode->i_sb->s_blocksize - ext_size); /* set size of new block */ neh = ext_block_hdr(bh); /* old root could have indexes or leaves * so calculate e_max right way */ if (ext_depth(inode)) neh->eh_max = cpu_to_le16(ext4_ext_space_block_idx(inode, 0)); else neh->eh_max = cpu_to_le16(ext4_ext_space_block(inode, 0)); neh->eh_magic = EXT4_EXT_MAGIC; ext4_extent_block_csum_set(inode, neh); set_buffer_uptodate(bh); unlock_buffer(bh); err = ext4_handle_dirty_metadata(handle, inode, bh); if (err) goto out; /* Update top-level index: num,max,pointer */ neh = ext_inode_hdr(inode); neh->eh_entries = cpu_to_le16(1); ext4_idx_store_pblock(EXT_FIRST_INDEX(neh), newblock); if (neh->eh_depth == 0) { /* Root extent block becomes index block */ neh->eh_max = cpu_to_le16(ext4_ext_space_root_idx(inode, 0)); EXT_FIRST_INDEX(neh)->ei_block = EXT_FIRST_EXTENT(neh)->ee_block; } ext_debug("new root: num %d(%d), lblock %d, ptr %llu\n", le16_to_cpu(neh->eh_entries), le16_to_cpu(neh->eh_max), le32_to_cpu(EXT_FIRST_INDEX(neh)->ei_block), ext4_idx_pblock(EXT_FIRST_INDEX(neh))); le16_add_cpu(&neh->eh_depth, 1); ext4_mark_inode_dirty(handle, inode); out: brelse(bh); return err; }
169,677
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool IDNSpoofChecker::Check(base::StringPiece16 label) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII || (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string))) return true; if (non_ascii_latin_letters_.containsSome(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]" "[\\u30ce\\u30f3\\u30bd\\u30be]" "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|" "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|" "\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|" "^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|" "^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|" "[a-z]\\u30fb|\\u30fb[a-z]|" "^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|" "[a-z][\\u0585\\u0581]+[a-z]|" "^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|" "[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); } Commit Message: Block domain labels made of Cyrillic letters that look alike Latin Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф. BUG=683314 TEST=components_unittests --gtest_filter=U*IDN* Review-Url: https://codereview.chromium.org/2683793010 Cr-Commit-Position: refs/heads/master@{#459226} CWE ID: CWE-20
bool IDNSpoofChecker::Check(base::StringPiece16 label) { bool IDNSpoofChecker::Check(base::StringPiece16 label, bool is_tld_ascii) { UErrorCode status = U_ZERO_ERROR; int32_t result = uspoof_check(checker_, label.data(), base::checked_cast<int32_t>(label.size()), NULL, &status); if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) return false; icu::UnicodeString label_string(FALSE, label.data(), base::checked_cast<int32_t>(label.size())); if (deviation_characters_.containsSome(label_string)) return false; // extra check unless it contains Kana letter exceptions or it's made entirely // of Cyrillic letters that look like Latin letters. Note that the following // combinations of scripts are treated as a 'logical' single script. result &= USPOOF_RESTRICTION_LEVEL_MASK; if (result == USPOOF_ASCII) return true; if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && kana_letters_exceptions_.containsNone(label_string)) { // Check Cyrillic confusable only for ASCII TLDs. return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); } if (non_ascii_latin_letters_.containsSome(label_string)) return false; if (!tls_index.initialized()) tls_index.Initialize(&OnThreadTermination); icu::RegexMatcher* dangerous_pattern = reinterpret_cast<icu::RegexMatcher*>(tls_index.Get()); if (!dangerous_pattern) { dangerous_pattern = new icu::RegexMatcher( icu::UnicodeString( "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]" "[\\u30ce\\u30f3\\u30bd\\u30be]" "[^\\p{scx=kana}\\p{scx=hira}\\p{scx=hani}]|" "[^\\p{scx=kana}\\p{scx=hira}]\\u30fc|" "\\u30fc[^\\p{scx=kana}\\p{scx=hira}]|" "^[\\p{scx=kana}]+[\\u3078-\\u307a][\\p{scx=kana}]+$|" "^[\\p{scx=hira}]+[\\u30d8-\\u30da][\\p{scx=hira}]+$|" "[a-z]\\u30fb|\\u30fb[a-z]|" "^[\\u0585\\u0581]+[a-z]|[a-z][\\u0585\\u0581]+$|" "[a-z][\\u0585\\u0581]+[a-z]|" "^[og]+[\\p{scx=armn}]|[\\p{scx=armn}][og]+$|" "[\\p{scx=armn}][og]+[\\p{scx=armn}]", -1, US_INV), 0, status); tls_index.Set(dangerous_pattern); } dangerous_pattern->reset(label_string); return !dangerous_pattern->find(); }
172,388
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); } Commit Message: CWE ID:
static void ncq_err(NCQTransferState *ncq_tfs) { IDEState *ide_state = &ncq_tfs->drive->port.ifs[0]; ide_state->error = ABRT_ERR; ide_state->status = READY_STAT | ERR_STAT; ncq_tfs->drive->port_regs.scr_err |= (1 << ncq_tfs->tag); ncq_tfs->used = 0; }
165,223
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_get_objs (MyObject *obj, GPtrArray **objs, GError **error) { *objs = g_ptr_array_new (); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject")); g_ptr_array_add (*objs, g_strdup ("/org/freedesktop/DBus/GLib/Tests/MyTestObject2")); return TRUE; } Commit Message: CWE ID: CWE-264
my_object_get_objs (MyObject *obj, GPtrArray **objs, GError **error)
165,101
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded, sizeof(buffer)); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } }
169,130
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context, AVFrame* frame) { VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt); if (format == VideoFrame::UNKNOWN) return AVERROR(EINVAL); DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 || format == VideoFrame::YV12J); gfx::Size size(codec_context->width, codec_context->height); int ret; if ((ret = av_image_check_size(size.width(), size.height(), 0, NULL)) < 0) return ret; gfx::Size natural_size; if (codec_context->sample_aspect_ratio.num > 0) { natural_size = GetNaturalSize(size, codec_context->sample_aspect_ratio.num, codec_context->sample_aspect_ratio.den); } else { natural_size = config_.natural_size(); } if (!VideoFrame::IsValidConfig(format, size, gfx::Rect(size), natural_size)) return AVERROR(EINVAL); scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame(format, size, gfx::Rect(size), natural_size, kNoTimestamp()); for (int i = 0; i < 3; i++) { frame->base[i] = video_frame->data(i); frame->data[i] = video_frame->data(i); frame->linesize[i] = video_frame->stride(i); } frame->opaque = NULL; video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque)); frame->type = FF_BUFFER_TYPE_USER; frame->width = codec_context->width; frame->height = codec_context->height; frame->format = codec_context->pix_fmt; return 0; } Commit Message: Replicate FFmpeg's video frame allocation strategy. This should avoid accidental overreads and overwrites due to our VideoFrame's not being as large as FFmpeg expects. BUG=368980 TEST=new regression test Review URL: https://codereview.chromium.org/270193002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@268831 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
int FFmpegVideoDecoder::GetVideoBuffer(AVCodecContext* codec_context, AVFrame* frame) { VideoFrame::Format format = PixelFormatToVideoFormat(codec_context->pix_fmt); if (format == VideoFrame::UNKNOWN) return AVERROR(EINVAL); DCHECK(format == VideoFrame::YV12 || format == VideoFrame::YV16 || format == VideoFrame::YV12J); gfx::Size size(codec_context->width, codec_context->height); const int ret = av_image_check_size(size.width(), size.height(), 0, NULL); if (ret < 0) return ret; gfx::Size natural_size; if (codec_context->sample_aspect_ratio.num > 0) { natural_size = GetNaturalSize(size, codec_context->sample_aspect_ratio.num, codec_context->sample_aspect_ratio.den); } else { natural_size = config_.natural_size(); } // FFmpeg has specific requirements on the allocation size of the frame. The // following logic replicates FFmpeg's allocation strategy to ensure buffers // are not overread / overwritten. See ff_init_buffer_info() for details. // // When lowres is non-zero, dimensions should be divided by 2^(lowres), but // since we don't use this, just DCHECK that it's zero. DCHECK_EQ(codec_context->lowres, 0); gfx::Size coded_size(std::max(size.width(), codec_context->coded_width), std::max(size.height(), codec_context->coded_height)); if (!VideoFrame::IsValidConfig( format, coded_size, gfx::Rect(size), natural_size)) return AVERROR(EINVAL); scoped_refptr<VideoFrame> video_frame = frame_pool_.CreateFrame( format, coded_size, gfx::Rect(size), natural_size, kNoTimestamp()); for (int i = 0; i < 3; i++) { frame->base[i] = video_frame->data(i); frame->data[i] = video_frame->data(i); frame->linesize[i] = video_frame->stride(i); } frame->opaque = NULL; video_frame.swap(reinterpret_cast<VideoFrame**>(&frame->opaque)); frame->type = FF_BUFFER_TYPE_USER; frame->width = coded_size.width(); frame->height = coded_size.height(); frame->format = codec_context->pix_fmt; return 0; }
171,677
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 remove_bond(const bt_bdaddr_t *bd_addr) { /* sanity check */ if (interface_ready() == FALSE) return BT_STATUS_NOT_READY; return btif_dm_remove_bond(bd_addr); } Commit Message: Add guest mode functionality (2/3) Add a flag to enable() to start Bluetooth in restricted mode. In restricted mode, all devices that are paired during restricted mode are deleted upon leaving restricted mode. Right now restricted mode is only entered while a guest user is active. Bug: 27410683 Change-Id: I8f23d28ef0aa3a8df13d469c73005c8e1b894d19 CWE ID: CWE-20
static int remove_bond(const bt_bdaddr_t *bd_addr) { if (is_restricted_mode() && !btif_storage_is_restricted_device(bd_addr)) return BT_STATUS_SUCCESS; /* sanity check */ if (interface_ready() == FALSE) return BT_STATUS_NOT_READY; return btif_dm_remove_bond(bd_addr); }
173,552
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; switch (ioctl) { case KVM_ARM_VCPU_INIT: { struct kvm_vcpu_init init; if (copy_from_user(&init, argp, sizeof(init))) return -EFAULT; return kvm_vcpu_set_target(vcpu, &init); } case KVM_SET_ONE_REG: case KVM_GET_ONE_REG: { struct kvm_one_reg reg; if (copy_from_user(&reg, argp, sizeof(reg))) return -EFAULT; if (ioctl == KVM_SET_ONE_REG) return kvm_arm_set_reg(vcpu, &reg); else return kvm_arm_get_reg(vcpu, &reg); } case KVM_GET_REG_LIST: { struct kvm_reg_list __user *user_list = argp; struct kvm_reg_list reg_list; unsigned n; if (copy_from_user(&reg_list, user_list, sizeof(reg_list))) return -EFAULT; n = reg_list.n; reg_list.n = kvm_arm_num_regs(vcpu); if (copy_to_user(user_list, &reg_list, sizeof(reg_list))) return -EFAULT; if (n < reg_list.n) return -E2BIG; return kvm_arm_copy_reg_indices(vcpu, user_list->reg); } default: return -EINVAL; } } Commit Message: ARM: KVM: prevent NULL pointer dereferences with KVM VCPU ioctl Some ARM KVM VCPU ioctls require the vCPU to be properly initialized with the KVM_ARM_VCPU_INIT ioctl before being used with further requests. KVM_RUN checks whether this initialization has been done, but other ioctls do not. Namely KVM_GET_REG_LIST will dereference an array with index -1 without initialization and thus leads to a kernel oops. Fix this by adding checks before executing the ioctl handlers. [ Removed superflous comment from static function - Christoffer ] Changes from v1: * moved check into a static function with a meaningful name Signed-off-by: Andre Przywara <andre.przywara@linaro.org> Signed-off-by: Christoffer Dall <cdall@cs.columbia.edu> CWE ID: CWE-399
long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; switch (ioctl) { case KVM_ARM_VCPU_INIT: { struct kvm_vcpu_init init; if (copy_from_user(&init, argp, sizeof(init))) return -EFAULT; return kvm_vcpu_set_target(vcpu, &init); } case KVM_SET_ONE_REG: case KVM_GET_ONE_REG: { struct kvm_one_reg reg; if (unlikely(!kvm_vcpu_initialized(vcpu))) return -ENOEXEC; if (copy_from_user(&reg, argp, sizeof(reg))) return -EFAULT; if (ioctl == KVM_SET_ONE_REG) return kvm_arm_set_reg(vcpu, &reg); else return kvm_arm_get_reg(vcpu, &reg); } case KVM_GET_REG_LIST: { struct kvm_reg_list __user *user_list = argp; struct kvm_reg_list reg_list; unsigned n; if (unlikely(!kvm_vcpu_initialized(vcpu))) return -ENOEXEC; if (copy_from_user(&reg_list, user_list, sizeof(reg_list))) return -EFAULT; n = reg_list.n; reg_list.n = kvm_arm_num_regs(vcpu); if (copy_to_user(user_list, &reg_list, sizeof(reg_list))) return -EFAULT; if (n < reg_list.n) return -E2BIG; return kvm_arm_copy_reg_indices(vcpu, user_list->reg); } default: return -EINVAL; } }
165,952
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: __reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode, int type, struct posix_acl *acl) { char *name; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_equiv_mode(acl, &inode->i_mode); if (error < 0) return error; else { if (error == 0) acl = NULL; } } break; case ACL_TYPE_DEFAULT: name = XATTR_NAME_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = reiserfs_posix_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0); /* * Ensure that the inode gets dirtied if we're only using * the mode bits and an old ACL didn't exist. We don't need * to check if the inode is hashed here since we won't get * called by reiserfs_inherit_default_acl(). */ if (error == -ENODATA) { error = 0; if (type == ACL_TYPE_ACCESS) { inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); } } kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; } Commit Message: posix_acl: Clear SGID bit when setting file permissions When file permissions are modified via chmod(2) and the user is not in the owning group or capable of CAP_FSETID, the setgid bit is cleared in inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file permissions as well as the new ACL, but doesn't clear the setgid bit in a similar way; this allows to bypass the check in chmod(2). Fix that. References: CVE-2016-7097 Reviewed-by: Christoph Hellwig <hch@lst.de> Reviewed-by: Jeff Layton <jlayton@redhat.com> Signed-off-by: Jan Kara <jack@suse.cz> Signed-off-by: Andreas Gruenbacher <agruenba@redhat.com> CWE ID: CWE-285
__reiserfs_set_acl(struct reiserfs_transaction_handle *th, struct inode *inode, int type, struct posix_acl *acl) { char *name; void *value = NULL; size_t size = 0; int error; switch (type) { case ACL_TYPE_ACCESS: name = XATTR_NAME_POSIX_ACL_ACCESS; if (acl) { error = posix_acl_update_mode(inode, &inode->i_mode, &acl); if (error) return error; } break; case ACL_TYPE_DEFAULT: name = XATTR_NAME_POSIX_ACL_DEFAULT; if (!S_ISDIR(inode->i_mode)) return acl ? -EACCES : 0; break; default: return -EINVAL; } if (acl) { value = reiserfs_posix_acl_to_disk(acl, &size); if (IS_ERR(value)) return (int)PTR_ERR(value); } error = reiserfs_xattr_set_handle(th, inode, name, value, size, 0); /* * Ensure that the inode gets dirtied if we're only using * the mode bits and an old ACL didn't exist. We don't need * to check if the inode is hashed here since we won't get * called by reiserfs_inherit_default_acl(). */ if (error == -ENODATA) { error = 0; if (type == ACL_TYPE_ACCESS) { inode->i_ctime = CURRENT_TIME_SEC; mark_inode_dirty(inode); } } kfree(value); if (!error) set_cached_acl(inode, type, acl); return error; }
166,978
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Chapters::Atom::GetDisplayCount() const { return m_displays_count; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
int Chapters::Atom::GetDisplayCount() const
174,305
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bpf_prog *bpf_prog_get(u32 ufd) { struct fd f = fdget(ufd); struct bpf_prog *prog; prog = __bpf_prog_get(f); if (IS_ERR(prog)) return prog; atomic_inc(&prog->aux->refcnt); fdput(f); return prog; } Commit Message: bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <jannh@google.com> Signed-off-by: Alexei Starovoitov <ast@kernel.org> Acked-by: Daniel Borkmann <daniel@iogearbox.net> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
struct bpf_prog *bpf_prog_get(u32 ufd) { struct fd f = fdget(ufd); struct bpf_prog *prog; prog = __bpf_prog_get(f); if (IS_ERR(prog)) return prog; prog = bpf_prog_inc(prog); fdput(f); return prog; }
167,254
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DXVAVideoDecodeAccelerator::DXVAVideoDecodeAccelerator( media::VideoDecodeAccelerator::Client* client, base::ProcessHandle renderer_process) : client_(client), egl_config_(NULL), state_(kUninitialized), pictures_requested_(false), renderer_process_(renderer_process), last_input_buffer_id_(-1), inputs_before_decode_(0) { memset(&input_stream_info_, 0, sizeof(input_stream_info_)); memset(&output_stream_info_, 0, sizeof(output_stream_info_)); } 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:
DXVAVideoDecodeAccelerator::DXVAVideoDecodeAccelerator( media::VideoDecodeAccelerator::Client* client) : client_(client), egl_config_(NULL), state_(kUninitialized), pictures_requested_(false), last_input_buffer_id_(-1), inputs_before_decode_(0) { memset(&input_stream_info_, 0, sizeof(input_stream_info_)); memset(&output_stream_info_, 0, sizeof(output_stream_info_)); }
170,940
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long long VideoTrack::GetWidth() const { return m_width; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long long VideoTrack::GetWidth() const
174,382
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_file_splice_write( struct pipe_inode_info *pipe, struct file *outfilp, loff_t *ppos, size_t count, unsigned int flags) { struct inode *inode = outfilp->f_mapping->host; struct xfs_inode *ip = XFS_I(inode); int ioflags = 0; ssize_t ret; XFS_STATS_INC(xs_write_calls); if (outfilp->f_mode & FMODE_NOCMTIME) ioflags |= IO_INVIS; if (XFS_FORCED_SHUTDOWN(ip->i_mount)) return -EIO; xfs_ilock(ip, XFS_IOLOCK_EXCL); trace_xfs_file_splice_write(ip, count, *ppos, ioflags); ret = generic_file_splice_write(pipe, outfilp, ppos, count, flags); if (ret > 0) XFS_STATS_ADD(xs_write_bytes, ret); xfs_iunlock(ip, XFS_IOLOCK_EXCL); return ret; } Commit Message: ->splice_write() via ->write_iter() iter_file_splice_write() - a ->splice_write() instance that gathers the pipe buffers, builds a bio_vec-based iov_iter covering those and feeds it to ->write_iter(). A bunch of simple cases coverted to that... [AV: fixed the braino spotted by Cyrill] Signed-off-by: Al Viro <viro@zeniv.linux.org.uk> CWE ID: CWE-264
xfs_file_splice_write(
166,810
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY); } (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; } Commit Message: ipsec: Fix aborted xfrm policy dump crash An independent security researcher, Mohamed Ghannam, has reported this vulnerability to Beyond Security's SecuriTeam Secure Disclosure program. The xfrm_dump_policy_done function expects xfrm_dump_policy to have been called at least once or it will crash. This can be triggered if a dump fails because the target socket's receive buffer is full. This patch fixes it by using the cb->start mechanism to ensure that the initialisation is always done regardless of the buffer situation. Fixes: 12a169e7d8f4 ("ipsec: Put dumpers on the dump list") Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au> Signed-off-by: Steffen Klassert <steffen.klassert@secunet.com> CWE ID: CWE-416
static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *)cb->args; struct xfrm_dump_info info; info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; }
167,662
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintPreviewDataSource::StartDataRequest(const std::string& path, bool is_incognito, int request_id) { if (!EndsWith(path, "/print.pdf", true)) { ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id); return; } scoped_refptr<base::RefCountedBytes> data; std::vector<std::string> url_substr; base::SplitString(path, '/', &url_substr); int page_index = 0; if (url_substr.size() == 3 && base::StringToInt(url_substr[1], &page_index)) { PrintPreviewDataService::GetInstance()->GetDataEntry( url_substr[0], page_index, &data); } if (data.get()) { SendResponse(request_id, data); return; } scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes); SendResponse(request_id, empty_bytes); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewDataSource::StartDataRequest(const std::string& path, bool is_incognito, int request_id) { if (!EndsWith(path, "/print.pdf", true)) { ChromeWebUIDataSource::StartDataRequest(path, is_incognito, request_id); return; } scoped_refptr<base::RefCountedBytes> data; std::vector<std::string> url_substr; base::SplitString(path, '/', &url_substr); int preview_ui_id = -1; int page_index = 0; if (url_substr.size() == 3 && base::StringToInt(url_substr[0], &preview_ui_id), base::StringToInt(url_substr[1], &page_index) && preview_ui_id >= 0) { PrintPreviewDataService::GetInstance()->GetDataEntry( preview_ui_id, page_index, &data); } if (data.get()) { SendResponse(request_id, data); return; } scoped_refptr<base::RefCountedBytes> empty_bytes(new base::RefCountedBytes); SendResponse(request_id, empty_bytes); }
170,827
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 pdf_creator_t *new_creator(int *n_elements) { pdf_creator_t *daddy; static const pdf_creator_t creator_template[] = { {"Title", ""}, {"Author", ""}, {"Subject", ""}, {"Keywords", ""}, {"Creator", ""}, {"Producer", ""}, {"CreationDate", ""}, {"ModDate", ""}, {"Trapped", ""}, }; daddy = malloc(sizeof(creator_template)); memcpy(daddy, creator_template, sizeof(creator_template)); if (n_elements) *n_elements = sizeof(creator_template) / sizeof(creator_template[0]); return daddy; } Commit Message: Zero and sanity check all dynamic allocs. This addresses the memory issues in Issue #6 expressed in calloc_some.pdf and malloc_some.pdf CWE ID: CWE-787
static pdf_creator_t *new_creator(int *n_elements) { pdf_creator_t *daddy; static const pdf_creator_t creator_template[] = { {"Title", ""}, {"Author", ""}, {"Subject", ""}, {"Keywords", ""}, {"Creator", ""}, {"Producer", ""}, {"CreationDate", ""}, {"ModDate", ""}, {"Trapped", ""}, }; daddy = safe_calloc(sizeof(creator_template)); memcpy(daddy, creator_template, sizeof(creator_template)); if (n_elements) *n_elements = sizeof(creator_template) / sizeof(creator_template[0]); return daddy; }
169,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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, delete) { char *fname; size_t fname_len; char *error; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname); RETURN_FALSE; } phar_flush(phar_obj->archive, NULL, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, delete) { char *fname; size_t fname_len; char *error; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0, "Cannot write out phar archive, phar is read-only"); return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) { RETURN_FALSE; } if (phar_obj->archive->is_persistent && FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } if (zend_hash_str_exists(&phar_obj->archive->manifest, fname, (uint) fname_len)) { if (NULL != (entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len))) { if (entry->is_deleted) { /* entry is deleted, but has not been flushed to disk yet */ RETURN_TRUE; } else { entry->is_deleted = 1; entry->is_modified = 1; phar_obj->archive->is_modified = 1; } } } else { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Entry %s does not exist and cannot be deleted", fname); RETURN_FALSE; } phar_flush(phar_obj->archive, NULL, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; }
165,063
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf) { int ret; /* MBIM backwards compatible function? */ if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM) return -ENODEV; /* The NCM data altsetting is fixed, so we hard-coded it. * Additionally, generic NCM devices are assumed to accept arbitrarily * placed NDP. */ ret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0); /* * We should get an event when network connection is "connected" or * "disconnected". Set network connection in "disconnected" state * (carrier is OFF) during attach, so the IP network stack does not * start IPv6 negotiation and more. */ usbnet_link_change(dev, 0, 0); return ret; } Commit Message: cdc_ncm: do not call usbnet_link_change from cdc_ncm_bind usbnet_link_change will call schedule_work and should be avoided if bind is failing. Otherwise we will end up with scheduled work referring to a netdev which has gone away. Instead of making the call conditional, we can just defer it to usbnet_probe, using the driver_info flag made for this purpose. Fixes: 8a34b0ae8778 ("usbnet: cdc_ncm: apply usbnet_link_change") Reported-by: Andrey Konovalov <andreyknvl@gmail.com> Suggested-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Bjørn Mork <bjorn@mork.no> Signed-off-by: David S. Miller <davem@davemloft.net> CWE ID:
static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf) { /* MBIM backwards compatible function? */ if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM) return -ENODEV; /* The NCM data altsetting is fixed, so we hard-coded it. * Additionally, generic NCM devices are assumed to accept arbitrarily * placed NDP. */ return cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0); }
167,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 Reset() { error_nframes_ = 0; droppable_nframes_ = 0; } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void Reset() { error_nframes_ = 0; droppable_nframes_ = 0; pattern_switch_ = 0; }
174,543
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() { if (!ContextGL()) return; ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test R=kbr@chromium.org,piman@chromium.org Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <piman@chromium.org> Reviewed-by: Kenneth Russell <kbr@chromium.org> Commit-Queue: Zhenyao Mo <zmo@chromium.org> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
void WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() { void WebGLRenderingContextBase:: DrawingBufferClientRestorePixelPackParameters() { if (!ContextGL()) return; ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_); }
172,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: image_transform_png_set_expand_add(image_transform *this, PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit * depth is at least 8 already. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_transform_png_set_expand_add(image_transform *this, const image_transform **that, png_byte colour_type, png_byte bit_depth) { UNUSED(bit_depth) this->next = *that; *that = this; /* 'expand' should do nothing for RGBA or GA input - no tRNS and the bit * depth is at least 8 already. */ return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; }
173,629
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppResult::Open(int event_flags) { RecordHistogram(APP_SEARCH_RESULT); const extensions::Extension* extension = extensions::ExtensionSystem::Get(profile_)->extension_service() ->GetInstalledExtension(app_id_); if (!extension) return; if (!extensions::util::IsAppLaunchable(app_id_, profile_)) return; if (RunExtensionEnableFlow()) return; if (display_type() != DISPLAY_RECOMMENDATION) { extensions::RecordAppListSearchLaunch(extension); content::RecordAction( base::UserMetricsAction("AppList_ClickOnAppFromSearch")); } controller_->ActivateApp( profile_, extension, AppListControllerDelegate::LAUNCH_FROM_APP_LIST_SEARCH, event_flags); } Commit Message: [Extensions] Add GetInstalledExtension() method to ExtensionRegistry This CL adds GetInstalledExtension() method to ExtensionRegistry and uses it instead of deprecated ExtensionService::GetInstalledExtension() in chrome/browser/ui/app_list/. Part of removing the deprecated GetInstalledExtension() call from the ExtensionService. BUG=489687 Review URL: https://codereview.chromium.org/1130353010 Cr-Commit-Position: refs/heads/master@{#333036} CWE ID:
void AppResult::Open(int event_flags) { RecordHistogram(APP_SEARCH_RESULT); const extensions::Extension* extension = extensions::ExtensionRegistry::Get(profile_)->GetInstalledExtension( app_id_); if (!extension) return; if (!extensions::util::IsAppLaunchable(app_id_, profile_)) return; if (RunExtensionEnableFlow()) return; if (display_type() != DISPLAY_RECOMMENDATION) { extensions::RecordAppListSearchLaunch(extension); content::RecordAction( base::UserMetricsAction("AppList_ClickOnAppFromSearch")); } controller_->ActivateApp( profile_, extension, AppListControllerDelegate::LAUNCH_FROM_APP_LIST_SEARCH, event_flags); }
171,726
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long mkvparser::UnserializeInt(IMkvReader* pReader, long long pos, long size, long long& result) { assert(pReader); assert(pos >= 0); assert(size > 0); assert(size <= 8); { signed char b; const long status = pReader->Read(pos, 1, (unsigned char*)&b); if (status < 0) return status; result = b; ++pos; } for (long i = 1; i < size; ++i) { unsigned char b; const long status = pReader->Read(pos, 1, &b); if (status < 0) return status; result <<= 8; result |= b; ++pos; } return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long mkvparser::UnserializeInt(IMkvReader* pReader, long long pos, long size, long UnserializeInt(IMkvReader* pReader, long long pos, long long size, long long& result_ref) { if (!pReader || pos < 0 || size < 1 || size > 8) return E_FILE_FORMAT_INVALID; signed char first_byte = 0; const long status = pReader->Read(pos, 1, (unsigned char*)&first_byte); if (status < 0) return status; unsigned long long result = first_byte; ++pos; for (long i = 1; i < size; ++i) { unsigned char b; const long status = pReader->Read(pos, 1, &b); if (status < 0) return status; result <<= 8; result |= b; ++pos; } result_ref = static_cast<long long>(result); return 0; }
173,866
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Automation::InitWithBrowserPath(const FilePath& browser_exe, const CommandLine& options, Error** error) { if (!file_util::PathExists(browser_exe)) { std::string message = base::StringPrintf( "Could not find Chrome binary at: %" PRFilePath, browser_exe.value().c_str()); *error = new Error(kUnknownError, message); return; } CommandLine command(browser_exe); command.AppendSwitch(switches::kDisableHangMonitor); command.AppendSwitch(switches::kDisablePromptOnRepost); command.AppendSwitch(switches::kDomAutomationController); command.AppendSwitch(switches::kFullMemoryCrashReport); command.AppendSwitchASCII(switches::kHomePage, chrome::kAboutBlankURL); command.AppendSwitch(switches::kNoDefaultBrowserCheck); command.AppendSwitch(switches::kNoFirstRun); command.AppendSwitchASCII(switches::kTestType, "webdriver"); command.AppendArguments(options, false); launcher_.reset(new AnonymousProxyLauncher(false)); ProxyLauncher::LaunchState launch_props = { false, // clear_profile FilePath(), // template_user_data ProxyLauncher::DEFAULT_THEME, command, true, // include_testing_id true // show_window }; std::string chrome_details = base::StringPrintf( "Using Chrome binary at: %" PRFilePath, browser_exe.value().c_str()); VLOG(1) << chrome_details; if (!launcher_->LaunchBrowserAndServer(launch_props, true)) { *error = new Error( kUnknownError, "Unable to either launch or connect to Chrome. Please check that " "ChromeDriver is up-to-date. " + chrome_details); return; } launcher_->automation()->set_action_timeout_ms(base::kNoTimeout); VLOG(1) << "Chrome launched successfully. Version: " << automation()->server_version(); bool has_automation_version = false; *error = CompareVersion(730, 0, &has_automation_version); if (*error) return; chrome_details += ", version (" + automation()->server_version() + ")"; if (has_automation_version) { int version = 0; std::string error_msg; if (!SendGetChromeDriverAutomationVersion( automation(), &version, &error_msg)) { *error = new Error(kUnknownError, error_msg + " " + chrome_details); return; } if (version > automation::kChromeDriverAutomationVersion) { *error = new Error( kUnknownError, "ChromeDriver is not compatible with this version of Chrome. " + chrome_details); return; } } } Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log remotely. Also add a 'chrome.verbose' boolean startup option. Remove usage of VLOG(1) in chromedriver. We do not need as complicated logging as in Chrome. BUG=85241 TEST=none Review URL: http://codereview.chromium.org/7104085 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
void Automation::InitWithBrowserPath(const FilePath& browser_exe, const CommandLine& options, Error** error) { if (!file_util::PathExists(browser_exe)) { std::string message = base::StringPrintf( "Could not find Chrome binary at: %" PRFilePath, browser_exe.value().c_str()); *error = new Error(kUnknownError, message); return; } CommandLine command(browser_exe); command.AppendSwitch(switches::kDisableHangMonitor); command.AppendSwitch(switches::kDisablePromptOnRepost); command.AppendSwitch(switches::kDomAutomationController); command.AppendSwitch(switches::kFullMemoryCrashReport); command.AppendSwitchASCII(switches::kHomePage, chrome::kAboutBlankURL); command.AppendSwitch(switches::kNoDefaultBrowserCheck); command.AppendSwitch(switches::kNoFirstRun); command.AppendSwitchASCII(switches::kTestType, "webdriver"); command.AppendArguments(options, false); launcher_.reset(new AnonymousProxyLauncher(false)); ProxyLauncher::LaunchState launch_props = { false, // clear_profile FilePath(), // template_user_data ProxyLauncher::DEFAULT_THEME, command, true, // include_testing_id true // show_window }; std::string chrome_details = base::StringPrintf( "Using Chrome binary at: %" PRFilePath, browser_exe.value().c_str()); LOG(INFO) << chrome_details; if (!launcher_->LaunchBrowserAndServer(launch_props, true)) { *error = new Error( kUnknownError, "Unable to either launch or connect to Chrome. Please check that " "ChromeDriver is up-to-date. " + chrome_details); return; } launcher_->automation()->set_action_timeout_ms(base::kNoTimeout); LOG(INFO) << "Chrome launched successfully. Version: " << automation()->server_version(); bool has_automation_version = false; *error = CompareVersion(730, 0, &has_automation_version); if (*error) return; chrome_details += ", version (" + automation()->server_version() + ")"; if (has_automation_version) { int version = 0; std::string error_msg; if (!SendGetChromeDriverAutomationVersion( automation(), &version, &error_msg)) { *error = new Error(kUnknownError, error_msg + " " + chrome_details); return; } if (version > automation::kChromeDriverAutomationVersion) { *error = new Error( kUnknownError, "ChromeDriver is not compatible with this version of Chrome. " + chrome_details); return; } } }
170,452
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; } Commit Message: [MJ2] Avoid index out of bounds access to pi->include[] Signed-off-by: Young_X <YangX92@hotmail.com> CWE ID: CWE-20
static opj_bool pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; long index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on) { pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; /* Avoids index out of bounds access with include*/ if (index >= pi->include_size) { opj_pi_emit_error(pi, "Invalid access to pi->include"); return OPJ_FALSE; } if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP: ; } } } } return OPJ_FALSE; }
169,770