instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| 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 DownloadController::StartAndroidDownloadInternal(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download, const DownloadInfo& info, bool allowed) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!allowed)
return;
WebContents* web_contents = wc_getter.Run();
if (!web_contents)
return;
base::string16 filename = net::GetSuggestedFilename(
info.url, info.content_disposition,
std::string(), // referrer_charset
std::string(), // suggested_name
info.original_mime_type,
default_file_name_);
ChromeDownloadDelegate::FromWebContents(web_contents)->RequestHTTPGetDownload(
info.url.spec(), info.user_agent,
info.content_disposition, info.original_mime_type,
info.cookie, info.referer, filename,
info.total_bytes, info.has_user_gesture,
must_download);
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254 | void DownloadController::StartAndroidDownloadInternal(
| 171,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: ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
u_char *p;
size_t slen, rlen;
int r, ssh1cipher;
if (!compat20) {
ssh1cipher = cipher_ctx_get_number(state->receive_context);
slen = cipher_get_keyiv_len(state->send_context);
rlen = cipher_get_keyiv_len(state->receive_context);
if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
(r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
(r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
(r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0 ||
(r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
(r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0 ||
(r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
return r;
} else {
if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
(r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
(r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
return r;
}
slen = cipher_get_keycontext(state->send_context, NULL);
rlen = cipher_get_keycontext(state->receive_context, NULL);
if ((r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->send_context, p) != (int)slen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = ssh_packet_get_compress_state(m, ssh)) != 0 ||
(r = sshbuf_put_stringb(m, state->input)) != 0 ||
(r = sshbuf_put_stringb(m, state->output)) != 0)
return r;
return 0;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | ssh_packet_get_state(struct ssh *ssh, struct sshbuf *m)
{
struct session_state *state = ssh->state;
u_char *p;
size_t slen, rlen;
int r, ssh1cipher;
if (!compat20) {
ssh1cipher = cipher_ctx_get_number(state->receive_context);
slen = cipher_get_keyiv_len(state->send_context);
rlen = cipher_get_keyiv_len(state->receive_context);
if ((r = sshbuf_put_u32(m, state->remote_protocol_flags)) != 0 ||
(r = sshbuf_put_u32(m, ssh1cipher)) != 0 ||
(r = sshbuf_put_string(m, state->ssh1_key, state->ssh1_keylen)) != 0 ||
(r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0 ||
(r = cipher_get_keyiv(state->send_context, p, slen)) != 0 ||
(r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0 ||
(r = cipher_get_keyiv(state->receive_context, p, rlen)) != 0)
return r;
} else {
if ((r = kex_to_blob(m, ssh->kex)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_OUT)) != 0 ||
(r = newkeys_to_blob(m, ssh, MODE_IN)) != 0 ||
(r = sshbuf_put_u64(m, state->rekey_limit)) != 0 ||
(r = sshbuf_put_u32(m, state->rekey_interval)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_send.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_send.bytes)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.seqnr)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.blocks)) != 0 ||
(r = sshbuf_put_u32(m, state->p_read.packets)) != 0 ||
(r = sshbuf_put_u64(m, state->p_read.bytes)) != 0)
return r;
}
slen = cipher_get_keycontext(state->send_context, NULL);
rlen = cipher_get_keycontext(state->receive_context, NULL);
if ((r = sshbuf_put_u32(m, slen)) != 0 ||
(r = sshbuf_reserve(m, slen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->send_context, p) != (int)slen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = sshbuf_put_u32(m, rlen)) != 0 ||
(r = sshbuf_reserve(m, rlen, &p)) != 0)
return r;
if (cipher_get_keycontext(state->receive_context, p) != (int)rlen)
return SSH_ERR_INTERNAL_ERROR;
if ((r = sshbuf_put_stringb(m, state->input)) != 0 ||
(r = sshbuf_put_stringb(m, state->output)) != 0)
return r;
return 0;
}
| 168,653 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string TestFlashMessageLoop::TestRunWithoutQuit() {
message_loop_ = new pp::flash::MessageLoop(instance_);
pp::CompletionCallback callback = callback_factory_.NewCallback(
&TestFlashMessageLoop::DestroyMessageLoopResourceTask);
pp::Module::Get()->core()->CallOnMainThread(0, callback);
int32_t result = message_loop_->Run();
if (message_loop_) {
delete message_loop_;
message_loop_ = NULL;
ASSERT_TRUE(false);
}
ASSERT_EQ(PP_ERROR_ABORTED, result);
PASS();
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264 | std::string TestFlashMessageLoop::TestRunWithoutQuit() {
message_loop_ = new pp::flash::MessageLoop(instance_);
pp::CompletionCallback callback = callback_factory_.NewCallback(
&TestFlashMessageLoop::DestroyMessageLoopResourceTask);
pp::Module::Get()->core()->CallOnMainThread(0, callback);
int32_t result = message_loop_->Run();
if (message_loop_) {
delete message_loop_;
message_loop_ = nullptr;
ASSERT_TRUE(false);
}
ASSERT_EQ(PP_ERROR_ABORTED, result);
PASS();
}
| 172,128 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: vsock_stream_recvmsg(struct kiocb *kiocb,
struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk;
struct vsock_sock *vsk;
int err;
size_t target;
ssize_t copied;
long timeout;
struct vsock_transport_recv_notify_data recv_data;
DEFINE_WAIT(wait);
sk = sock->sk;
vsk = vsock_sk(sk);
err = 0;
lock_sock(sk);
if (sk->sk_state != SS_CONNECTED) {
/* Recvmsg is supposed to return 0 if a peer performs an
* orderly shutdown. Differentiate between that case and when a
* peer has not connected or a local shutdown occured with the
* SOCK_DONE flag.
*/
if (sock_flag(sk, SOCK_DONE))
err = 0;
else
err = -ENOTCONN;
goto out;
}
if (flags & MSG_OOB) {
err = -EOPNOTSUPP;
goto out;
}
/* We don't check peer_shutdown flag here since peer may actually shut
* down, but there can be data in the queue that a local socket can
* receive.
*/
if (sk->sk_shutdown & RCV_SHUTDOWN) {
err = 0;
goto out;
}
/* It is valid on Linux to pass in a zero-length receive buffer. This
* is not an error. We may as well bail out now.
*/
if (!len) {
err = 0;
goto out;
}
/* We must not copy less than target bytes into the user's buffer
* before returning successfully, so we wait for the consume queue to
* have that much data to consume before dequeueing. Note that this
* makes it impossible to handle cases where target is greater than the
* queue size.
*/
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
if (target >= transport->stream_rcvhiwat(vsk)) {
err = -ENOMEM;
goto out;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
copied = 0;
err = transport->notify_recv_init(vsk, target, &recv_data);
if (err < 0)
goto out;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
while (1) {
s64 ready = vsock_stream_has_data(vsk);
if (ready < 0) {
/* Invalid queue pair content. XXX This should be
* changed to a connection reset in a later change.
*/
err = -ENOMEM;
goto out_wait;
} else if (ready > 0) {
ssize_t read;
err = transport->notify_recv_pre_dequeue(
vsk, target, &recv_data);
if (err < 0)
break;
read = transport->stream_dequeue(
vsk, msg->msg_iov,
len - copied, flags);
if (read < 0) {
err = -ENOMEM;
break;
}
copied += read;
err = transport->notify_recv_post_dequeue(
vsk, target, read,
!(flags & MSG_PEEK), &recv_data);
if (err < 0)
goto out_wait;
if (read >= target || flags & MSG_PEEK)
break;
target -= read;
} else {
if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN)
|| (vsk->peer_shutdown & SEND_SHUTDOWN)) {
break;
}
/* Don't wait for non-blocking sockets. */
if (timeout == 0) {
err = -EAGAIN;
break;
}
err = transport->notify_recv_pre_block(
vsk, target, &recv_data);
if (err < 0)
break;
release_sock(sk);
timeout = schedule_timeout(timeout);
lock_sock(sk);
if (signal_pending(current)) {
err = sock_intr_errno(timeout);
break;
} else if (timeout == 0) {
err = -EAGAIN;
break;
}
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
}
}
if (sk->sk_err)
err = -sk->sk_err;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
err = 0;
if (copied > 0) {
/* We only do these additional bookkeeping/notification steps
* if we actually copied something out of the queue pair
* instead of just peeking ahead.
*/
if (!(flags & MSG_PEEK)) {
/* If the other side has shutdown for sending and there
* is nothing more to read, then modify the socket
* state.
*/
if (vsk->peer_shutdown & SEND_SHUTDOWN) {
if (vsock_stream_has_data(vsk) <= 0) {
sk->sk_state = SS_UNCONNECTED;
sock_set_flag(sk, SOCK_DONE);
sk->sk_state_change(sk);
}
}
}
err = copied;
}
out_wait:
finish_wait(sk_sleep(sk), &wait);
out:
release_sock(sk);
return err;
}
Commit Message: VSOCK: Fix missing msg_namelen update in vsock_stream_recvmsg()
The code misses to update the msg_namelen member to 0 and therefore
makes net/socket.c leak the local, uninitialized sockaddr_storage
variable to userland -- 128 bytes of kernel stack memory.
Cc: Andy King <[email protected]>
Cc: Dmitry Torokhov <[email protected]>
Cc: George Zhang <[email protected]>
Signed-off-by: Mathias Krause <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | vsock_stream_recvmsg(struct kiocb *kiocb,
struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk;
struct vsock_sock *vsk;
int err;
size_t target;
ssize_t copied;
long timeout;
struct vsock_transport_recv_notify_data recv_data;
DEFINE_WAIT(wait);
sk = sock->sk;
vsk = vsock_sk(sk);
err = 0;
msg->msg_namelen = 0;
lock_sock(sk);
if (sk->sk_state != SS_CONNECTED) {
/* Recvmsg is supposed to return 0 if a peer performs an
* orderly shutdown. Differentiate between that case and when a
* peer has not connected or a local shutdown occured with the
* SOCK_DONE flag.
*/
if (sock_flag(sk, SOCK_DONE))
err = 0;
else
err = -ENOTCONN;
goto out;
}
if (flags & MSG_OOB) {
err = -EOPNOTSUPP;
goto out;
}
/* We don't check peer_shutdown flag here since peer may actually shut
* down, but there can be data in the queue that a local socket can
* receive.
*/
if (sk->sk_shutdown & RCV_SHUTDOWN) {
err = 0;
goto out;
}
/* It is valid on Linux to pass in a zero-length receive buffer. This
* is not an error. We may as well bail out now.
*/
if (!len) {
err = 0;
goto out;
}
/* We must not copy less than target bytes into the user's buffer
* before returning successfully, so we wait for the consume queue to
* have that much data to consume before dequeueing. Note that this
* makes it impossible to handle cases where target is greater than the
* queue size.
*/
target = sock_rcvlowat(sk, flags & MSG_WAITALL, len);
if (target >= transport->stream_rcvhiwat(vsk)) {
err = -ENOMEM;
goto out;
}
timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
copied = 0;
err = transport->notify_recv_init(vsk, target, &recv_data);
if (err < 0)
goto out;
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
while (1) {
s64 ready = vsock_stream_has_data(vsk);
if (ready < 0) {
/* Invalid queue pair content. XXX This should be
* changed to a connection reset in a later change.
*/
err = -ENOMEM;
goto out_wait;
} else if (ready > 0) {
ssize_t read;
err = transport->notify_recv_pre_dequeue(
vsk, target, &recv_data);
if (err < 0)
break;
read = transport->stream_dequeue(
vsk, msg->msg_iov,
len - copied, flags);
if (read < 0) {
err = -ENOMEM;
break;
}
copied += read;
err = transport->notify_recv_post_dequeue(
vsk, target, read,
!(flags & MSG_PEEK), &recv_data);
if (err < 0)
goto out_wait;
if (read >= target || flags & MSG_PEEK)
break;
target -= read;
} else {
if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN)
|| (vsk->peer_shutdown & SEND_SHUTDOWN)) {
break;
}
/* Don't wait for non-blocking sockets. */
if (timeout == 0) {
err = -EAGAIN;
break;
}
err = transport->notify_recv_pre_block(
vsk, target, &recv_data);
if (err < 0)
break;
release_sock(sk);
timeout = schedule_timeout(timeout);
lock_sock(sk);
if (signal_pending(current)) {
err = sock_intr_errno(timeout);
break;
} else if (timeout == 0) {
err = -EAGAIN;
break;
}
prepare_to_wait(sk_sleep(sk), &wait,
TASK_INTERRUPTIBLE);
}
}
if (sk->sk_err)
err = -sk->sk_err;
else if (sk->sk_shutdown & RCV_SHUTDOWN)
err = 0;
if (copied > 0) {
/* We only do these additional bookkeeping/notification steps
* if we actually copied something out of the queue pair
* instead of just peeking ahead.
*/
if (!(flags & MSG_PEEK)) {
/* If the other side has shutdown for sending and there
* is nothing more to read, then modify the socket
* state.
*/
if (vsk->peer_shutdown & SEND_SHUTDOWN) {
if (vsock_stream_has_data(vsk) <= 0) {
sk->sk_state = SS_UNCONNECTED;
sock_set_flag(sk, SOCK_DONE);
sk->sk_state_change(sk);
}
}
}
err = copied;
}
out_wait:
finish_wait(sk_sleep(sk), &wait);
out:
release_sock(sk);
return err;
}
| 166,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert,
BIO *dcont, BIO *out, unsigned int flags)
{
int r;
BIO *cont;
if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) {
CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA);
return 0;
}
if (!dcont && !check_content(cms))
return 0;
if (flags & CMS_DEBUG_DECRYPT)
cms->d.envelopedData->encryptedContentInfo->debug = 1;
else
cms->d.envelopedData->encryptedContentInfo->debug = 0;
if (!pk && !cert && !dcont && !out)
return 1;
if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert))
r = cms_copy_content(out, cont, flags);
do_free_upto(cont, dcont);
return r;
}
Commit Message:
CWE ID: CWE-311 | int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert,
BIO *dcont, BIO *out, unsigned int flags)
{
int r;
BIO *cont;
if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_enveloped) {
CMSerr(CMS_F_CMS_DECRYPT, CMS_R_TYPE_NOT_ENVELOPED_DATA);
return 0;
}
if (!dcont && !check_content(cms))
return 0;
if (flags & CMS_DEBUG_DECRYPT)
cms->d.envelopedData->encryptedContentInfo->debug = 1;
else
cms->d.envelopedData->encryptedContentInfo->debug = 0;
if (!cert)
cms->d.envelopedData->encryptedContentInfo->havenocert = 1;
else
cms->d.envelopedData->encryptedContentInfo->havenocert = 0;
if (!pk && !cert && !dcont && !out)
return 1;
if (pk && !CMS_decrypt_set1_pkey(cms, pk, cert))
r = cms_copy_content(out, cont, flags);
do_free_upto(cont, dcont);
return r;
}
| 165,138 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCacheUpdateJob::HandleMasterEntryFetchCompleted(URLFetcher* fetcher,
int net_error) {
DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING);
UpdateURLLoaderRequest* request = fetcher->request();
const GURL& url = request->GetURL();
master_entry_fetches_.erase(url);
++master_entries_completed_;
int response_code = net_error == net::OK ? request->GetResponseCode() : -1;
auto found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
if (response_code / 100 == 2) {
AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get()
: group_->newest_complete_cache();
DCHECK(fetcher->response_writer());
AppCacheEntry master_entry(AppCacheEntry::MASTER,
fetcher->response_writer()->response_id(),
fetcher->response_writer()->amount_written());
if (cache->AddOrModifyEntry(url, master_entry))
added_master_entries_.push_back(url);
else
duplicate_response_ids_.push_back(master_entry.response_id());
if (!inprogress_cache_.get()) {
DCHECK(cache == group_->newest_complete_cache());
for (AppCacheHost* host : hosts)
host->AssociateCompleteCache(cache);
}
} else {
HostNotifier host_notifier;
for (AppCacheHost* host : hosts) {
host_notifier.AddHost(host);
if (inprogress_cache_.get())
host->AssociateNoCache(GURL());
host->RemoveObserver(this);
}
hosts.clear();
failed_master_entries_.insert(url);
const char kFormatString[] = "Manifest fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, request->GetURL(), fetcher->result(), response_code);
host_notifier.SendErrorNotifications(blink::mojom::AppCacheErrorDetails(
message, blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/));
if (inprogress_cache_.get()) {
pending_master_entries_.erase(found);
--master_entries_completed_;
if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) {
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
message,
blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/),
fetcher->result(), GURL());
return;
}
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchMasterEntries();
MaybeCompleteUpdate();
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCacheUpdateJob::HandleMasterEntryFetchCompleted(URLFetcher* fetcher,
int net_error) {
DCHECK(internal_state_ == NO_UPDATE || internal_state_ == DOWNLOADING);
UpdateURLLoaderRequest* request = fetcher->request();
const GURL& url = request->GetURL();
master_entry_fetches_.erase(url);
++master_entries_completed_;
int response_code = net_error == net::OK ? request->GetResponseCode() : -1;
auto found = pending_master_entries_.find(url);
DCHECK(found != pending_master_entries_.end());
PendingHosts& hosts = found->second;
if (response_code / 100 == 2) {
AppCache* cache = inprogress_cache_.get() ? inprogress_cache_.get()
: group_->newest_complete_cache();
DCHECK(fetcher->response_writer());
// Master entries cannot be cross-origin by definition, so they do not
// require padding.
AppCacheEntry master_entry(
AppCacheEntry::MASTER, fetcher->response_writer()->response_id(),
fetcher->response_writer()->amount_written(), /*padding_size=*/0);
if (cache->AddOrModifyEntry(url, master_entry))
added_master_entries_.push_back(url);
else
duplicate_response_ids_.push_back(master_entry.response_id());
if (!inprogress_cache_.get()) {
DCHECK(cache == group_->newest_complete_cache());
for (AppCacheHost* host : hosts)
host->AssociateCompleteCache(cache);
}
} else {
HostNotifier host_notifier;
for (AppCacheHost* host : hosts) {
host_notifier.AddHost(host);
if (inprogress_cache_.get())
host->AssociateNoCache(GURL());
host->RemoveObserver(this);
}
hosts.clear();
failed_master_entries_.insert(url);
const char kFormatString[] = "Manifest fetch failed (%d) %s";
std::string message = FormatUrlErrorMessage(
kFormatString, request->GetURL(), fetcher->result(), response_code);
host_notifier.SendErrorNotifications(blink::mojom::AppCacheErrorDetails(
message, blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/));
if (inprogress_cache_.get()) {
pending_master_entries_.erase(found);
--master_entries_completed_;
if (update_type_ == CACHE_ATTEMPT && pending_master_entries_.empty()) {
HandleCacheFailure(
blink::mojom::AppCacheErrorDetails(
message,
blink::mojom::AppCacheErrorReason::APPCACHE_MANIFEST_ERROR,
request->GetURL(), response_code, false /*is_cross_origin*/),
fetcher->result(), GURL());
return;
}
}
}
DCHECK(internal_state_ != CACHE_FAILURE);
FetchMasterEntries();
MaybeCompleteUpdate();
}
| 172,995 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 netlbl_cipsov4_add_common(struct genl_info *info,
struct cipso_v4_doi *doi_def)
{
struct nlattr *nla;
int nla_rem;
u32 iter = 0;
doi_def->doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);
if (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_TAGLST],
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
return -EINVAL;
nla_for_each_nested(nla, info->attrs[NLBL_CIPSOV4_A_TAGLST], nla_rem)
if (nla->nla_type == NLBL_CIPSOV4_A_TAG) {
if (iter > CIPSO_V4_TAG_MAXCNT)
return -EINVAL;
doi_def->tags[iter++] = nla_get_u8(nla);
}
if (iter < CIPSO_V4_TAG_MAXCNT)
doi_def->tags[iter] = CIPSO_V4_TAG_INVALID;
return 0;
}
Commit Message: NetLabel: correct CIPSO tag handling when adding new DOI definitions
The current netlbl_cipsov4_add_common() function has two problems which are
fixed with this patch. The first is an off-by-one bug where it is possibile to
overflow the doi_def->tags[] array. The second is a bug where the same
doi_def->tags[] array was not always fully initialized, which caused sporadic
failures.
Signed-off-by: Paul Moore <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: CWE-119 | static int netlbl_cipsov4_add_common(struct genl_info *info,
struct cipso_v4_doi *doi_def)
{
struct nlattr *nla;
int nla_rem;
u32 iter = 0;
doi_def->doi = nla_get_u32(info->attrs[NLBL_CIPSOV4_A_DOI]);
if (nla_validate_nested(info->attrs[NLBL_CIPSOV4_A_TAGLST],
NLBL_CIPSOV4_A_MAX,
netlbl_cipsov4_genl_policy) != 0)
return -EINVAL;
nla_for_each_nested(nla, info->attrs[NLBL_CIPSOV4_A_TAGLST], nla_rem)
if (nla->nla_type == NLBL_CIPSOV4_A_TAG) {
if (iter >= CIPSO_V4_TAG_MAXCNT)
return -EINVAL;
doi_def->tags[iter++] = nla_get_u8(nla);
}
while (iter < CIPSO_V4_TAG_MAXCNT)
doi_def->tags[iter++] = CIPSO_V4_TAG_INVALID;
return 0;
}
| 169,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
newsk->sk_state = TCP_SYN_RECV;
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
newsk->sk_write_space = sk_stream_write_space;
/* listeners have SOCK_RCU_FREE, not the children */
sock_reset_flag(newsk, SOCK_RCU_FREE);
newsk->sk_mark = inet_rsk(req)->ir_mark;
atomic64_set(&newsk->sk_cookie,
atomic64_read(&inet_rsk(req)->ir_cookie));
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
security_inet_csk_clone(newsk, req);
}
return newsk;
}
Commit Message: dccp/tcp: do not inherit mc_list from parent
syzkaller found a way to trigger double frees from ip_mc_drop_socket()
It turns out that leave a copy of parent mc_list at accept() time,
which is very bad.
Very similar to commit 8b485ce69876 ("tcp: do not inherit
fastopen_req from parent")
Initial report from Pray3r, completed by Andrey one.
Thanks a lot to them !
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Pray3r <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-415 | struct sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
newsk->sk_state = TCP_SYN_RECV;
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
newsk->sk_write_space = sk_stream_write_space;
/* listeners have SOCK_RCU_FREE, not the children */
sock_reset_flag(newsk, SOCK_RCU_FREE);
inet_sk(newsk)->mc_list = NULL;
newsk->sk_mark = inet_rsk(req)->ir_mark;
atomic64_set(&newsk->sk_cookie,
atomic64_read(&inet_rsk(req)->ir_cookie));
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
security_inet_csk_clone(newsk, req);
}
return newsk;
}
| 168,190 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mm_answer_pam_free_ctx(int sock, Buffer *m)
{
debug3("%s", __func__);
(sshpam_device.free_ctx)(sshpam_ctxt);
buffer_clear(m);
mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
auth_method = "keyboard-interactive";
auth_submethod = "pam";
return (sshpam_authok == sshpam_ctxt);
}
Commit Message: set sshpam_ctxt to NULL after free
Avoids use-after-free in monitor when privsep child is compromised.
Reported by Moritz Jodeit; ok dtucker@
CWE ID: CWE-264 | mm_answer_pam_free_ctx(int sock, Buffer *m)
{
int r = sshpam_authok != NULL && sshpam_authok == sshpam_ctxt;
debug3("%s", __func__);
(sshpam_device.free_ctx)(sshpam_ctxt);
sshpam_ctxt = sshpam_authok = NULL;
buffer_clear(m);
mm_request_send(sock, MONITOR_ANS_PAM_FREE_CTX, m);
auth_method = "keyboard-interactive";
auth_submethod = "pam";
return r;
}
| 166,584 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
int retsize;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL ||
cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL ||
*replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL ||
*replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
if (pCmdData == NULL ||
cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)) ||
pReplyData == NULL ||
*replySize < (sizeof(effect_param_t) + sizeof(int32_t))){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *)pCmdData;
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t)))
|| pReplyData == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
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 Reverb_command(effect_handle_t self,
uint32_t cmdCode,
uint32_t cmdSize,
void *pCmdData,
uint32_t *replySize,
void *pReplyData){
android::ReverbContext * pContext = (android::ReverbContext *) self;
int retsize;
LVREV_ControlParams_st ActiveParams; /* Current control Parameters */
LVREV_ReturnStatus_en LvmStatus=LVREV_SUCCESS; /* Function call status */
if (pContext == NULL){
ALOGV("\tLVM_ERROR : Reverb_command ERROR pContext == NULL");
return -EINVAL;
}
switch (cmdCode){
case EFFECT_CMD_INIT:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_INIT: ERROR");
return -EINVAL;
}
*(int *) pReplyData = 0;
break;
case EFFECT_CMD_SET_CONFIG:
if (pCmdData == NULL || cmdSize != sizeof(effect_config_t) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_CONFIG: ERROR");
return -EINVAL;
}
*(int *) pReplyData = android::Reverb_setConfig(pContext,
(effect_config_t *) pCmdData);
break;
case EFFECT_CMD_GET_CONFIG:
if (pReplyData == NULL || replySize == NULL || *replySize != sizeof(effect_config_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_CONFIG: ERROR");
return -EINVAL;
}
android::Reverb_getConfig(pContext, (effect_config_t *)pReplyData);
break;
case EFFECT_CMD_RESET:
Reverb_setConfig(pContext, &pContext->config);
break;
case EFFECT_CMD_GET_PARAM:{
effect_param_t *p = (effect_param_t *)pCmdData;
if (pCmdData == NULL || cmdSize < sizeof(effect_param_t) ||
cmdSize < (sizeof(effect_param_t) + p->psize) ||
pReplyData == NULL || replySize == NULL ||
*replySize < (sizeof(effect_param_t) + p->psize)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_GET_PARAM: ERROR");
return -EINVAL;
}
memcpy(pReplyData, pCmdData, sizeof(effect_param_t) + p->psize);
p = (effect_param_t *)pReplyData;
int voffset = ((p->psize - 1) / sizeof(int32_t) + 1) * sizeof(int32_t);
p->status = android::Reverb_getParameter(pContext,
(void *)p->data,
&p->vsize,
p->data + voffset);
*replySize = sizeof(effect_param_t) + voffset + p->vsize;
} break;
case EFFECT_CMD_SET_PARAM:{
if (pCmdData == NULL || (cmdSize < (sizeof(effect_param_t) + sizeof(int32_t))) ||
pReplyData == NULL || replySize == NULL || *replySize != sizeof(int32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR");
return -EINVAL;
}
effect_param_t *p = (effect_param_t *) pCmdData;
if (p->psize != sizeof(int32_t)){
ALOGV("\t4LVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_PARAM: ERROR, psize is not sizeof(int32_t)");
return -EINVAL;
}
*(int *)pReplyData = android::Reverb_setParameter(pContext,
(void *)p->data,
p->data + p->psize);
} break;
case EFFECT_CMD_ENABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_TRUE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_ENABLE: ERROR-Effect is already enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_TRUE;
/* Get the current settings */
LvmStatus = LVREV_GetControlParameters(pContext->hInstance, &ActiveParams);
LVM_ERROR_CHECK(LvmStatus, "LVREV_GetControlParameters", "EFFECT_CMD_ENABLE")
pContext->SamplesToExitCount =
(ActiveParams.T60 * pContext->config.inputCfg.samplingRate)/1000;
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
break;
case EFFECT_CMD_DISABLE:
if (pReplyData == NULL || *replySize != sizeof(int)){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR");
return -EINVAL;
}
if(pContext->bEnabled == LVM_FALSE){
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_DISABLE: ERROR-Effect is not yet enabled");
return -EINVAL;
}
*(int *)pReplyData = 0;
pContext->bEnabled = LVM_FALSE;
break;
case EFFECT_CMD_SET_VOLUME:
if (pCmdData == NULL ||
cmdSize != 2 * sizeof(uint32_t)) {
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"EFFECT_CMD_SET_VOLUME: ERROR");
return -EINVAL;
}
if (pReplyData != NULL) { // we have volume control
pContext->leftVolume = (LVM_INT16)((*(uint32_t *)pCmdData + (1 << 11)) >> 12);
pContext->rightVolume = (LVM_INT16)((*((uint32_t *)pCmdData + 1) + (1 << 11)) >> 12);
*(uint32_t *)pReplyData = (1 << 24);
*((uint32_t *)pReplyData + 1) = (1 << 24);
if (pContext->volumeMode == android::REVERB_VOLUME_OFF) {
pContext->volumeMode = android::REVERB_VOLUME_FLAT;
}
} else { // we don't have volume control
pContext->leftVolume = REVERB_UNIT_VOLUME;
pContext->rightVolume = REVERB_UNIT_VOLUME;
pContext->volumeMode = android::REVERB_VOLUME_OFF;
}
ALOGV("EFFECT_CMD_SET_VOLUME left %d, right %d mode %d",
pContext->leftVolume, pContext->rightVolume, pContext->volumeMode);
break;
case EFFECT_CMD_SET_DEVICE:
case EFFECT_CMD_SET_AUDIO_MODE:
break;
default:
ALOGV("\tLVM_ERROR : Reverb_command cmdCode Case: "
"DEFAULT start %d ERROR",cmdCode);
return -EINVAL;
}
return 0;
} /* end Reverb_command */
| 173,350 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vt_reset_keyboard(int fd) {
int kb;
/* If we can't read the default, then default to unicode. It's 2017 after all. */
kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
if (ioctl(fd, KDSKBMODE, kb) < 0)
return -errno;
return 0;
}
Commit Message: Merge pull request #12378 from rbalint/vt-kbd-reset-check
VT kbd reset check
CWE ID: CWE-255 | int vt_reset_keyboard(int fd) {
int kb, r;
/* If we can't read the default, then default to unicode. It's 2017 after all. */
kb = vt_default_utf8() != 0 ? K_UNICODE : K_XLATE;
r = vt_verify_kbmode(fd);
if (r == -EBUSY) {
log_debug_errno(r, "Keyboard is not in XLATE or UNICODE mode, not resetting: %m");
return 0;
} else if (r < 0)
return r;
if (ioctl(fd, KDSKBMODE, kb) < 0)
return -errno;
return 0;
}
| 169,776 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AudioOutputDevice::OnStreamCreated(
base::SharedMemoryHandle handle,
base::SyncSocket::Handle socket_handle,
int length) {
DCHECK(message_loop()->BelongsToCurrentThread());
#if defined(OS_WIN)
DCHECK(handle);
DCHECK(socket_handle);
#else
DCHECK_GE(handle.fd, 0);
DCHECK_GE(socket_handle, 0);
#endif
DCHECK(stream_id_);
if (!audio_thread_.get())
return;
DCHECK(audio_thread_->IsStopped());
audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback(
audio_parameters_, input_channels_, handle, length, callback_));
audio_thread_->Start(
audio_callback_.get(), socket_handle, "AudioOutputDevice");
is_started_ = true;
if (play_on_start_)
PlayOnIOThread();
}
Commit Message: Revert r157378 as it caused WebRTC to dereference null pointers when restarting a call.
I've kept my unit test changes intact but disabled until I get a proper fix.
BUG=147499,150805
TBR=henrika
Review URL: https://codereview.chromium.org/10946040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@157626 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void AudioOutputDevice::OnStreamCreated(
base::SharedMemoryHandle handle,
base::SyncSocket::Handle socket_handle,
int length) {
DCHECK(message_loop()->BelongsToCurrentThread());
#if defined(OS_WIN)
DCHECK(handle);
DCHECK(socket_handle);
#else
DCHECK_GE(handle.fd, 0);
DCHECK_GE(socket_handle, 0);
#endif
DCHECK(stream_id_);
DCHECK(audio_thread_.IsStopped());
audio_callback_.reset(new AudioOutputDevice::AudioThreadCallback(
audio_parameters_, input_channels_, handle, length, callback_));
audio_thread_.Start(audio_callback_.get(), socket_handle,
"AudioOutputDevice");
is_started_ = true;
if (play_on_start_)
PlayOnIOThread();
}
| 170,705 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t OMXNodeInstance::allocateSecureBuffer(
OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer,
void **buffer_data, sp<NativeHandle> *native_handle) {
if (buffer == NULL || buffer_data == NULL || native_handle == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
BufferMeta *buffer_meta = new BufferMeta(size, portIndex);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, size);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
if (mSecureBufferType[portIndex] == kSecureBufferTypeNativeHandle) {
*buffer_data = NULL;
*native_handle = NativeHandle::create(
(native_handle_t *)header->pBuffer, false /* ownsHandle */);
} else {
*buffer_data = header->pBuffer;
*native_handle = NULL;
}
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateSecureBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%zu@%p:%p", size, *buffer_data,
*native_handle == NULL ? NULL : (*native_handle)->handle()));
return OK;
}
Commit Message: OMXNodeInstance: sanity check portIndex.
Bug: 31385713
Change-Id: Ib91d00eb5cc8c51c84d37f5d36d6b7ca594d201f
(cherry picked from commit f80a1f5075a7c6e1982d37c68bfed7c9a611bb20)
CWE ID: CWE-264 | status_t OMXNodeInstance::allocateSecureBuffer(
OMX_U32 portIndex, size_t size, OMX::buffer_id *buffer,
void **buffer_data, sp<NativeHandle> *native_handle) {
if (buffer == NULL || buffer_data == NULL || native_handle == NULL) {
ALOGE("b/25884056");
return BAD_VALUE;
}
if (portIndex >= NELEM(mSecureBufferType)) {
ALOGE("b/31385713, portIndex(%u)", portIndex);
android_errorWriteLog(0x534e4554, "31385713");
return BAD_VALUE;
}
Mutex::Autolock autoLock(mLock);
BufferMeta *buffer_meta = new BufferMeta(size, portIndex);
OMX_BUFFERHEADERTYPE *header;
OMX_ERRORTYPE err = OMX_AllocateBuffer(
mHandle, &header, portIndex, buffer_meta, size);
if (err != OMX_ErrorNone) {
CLOG_ERROR(allocateBuffer, err, BUFFER_FMT(portIndex, "%zu@", size));
delete buffer_meta;
buffer_meta = NULL;
*buffer = 0;
return StatusFromOMXError(err);
}
CHECK_EQ(header->pAppPrivate, buffer_meta);
*buffer = makeBufferID(header);
if (mSecureBufferType[portIndex] == kSecureBufferTypeNativeHandle) {
*buffer_data = NULL;
*native_handle = NativeHandle::create(
(native_handle_t *)header->pBuffer, false /* ownsHandle */);
} else {
*buffer_data = header->pBuffer;
*native_handle = NULL;
}
addActiveBuffer(portIndex, *buffer);
sp<GraphicBufferSource> bufferSource(getGraphicBufferSource());
if (bufferSource != NULL && portIndex == kPortIndexInput) {
bufferSource->addCodecBuffer(header);
}
CLOG_BUFFER(allocateSecureBuffer, NEW_BUFFER_FMT(
*buffer, portIndex, "%zu@%p:%p", size, *buffer_data,
*native_handle == NULL ? NULL : (*native_handle)->handle()));
return OK;
}
| 173,384 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 OnReadAllMetadata(
const SessionStore::SessionInfo& session_info,
SessionStore::FactoryCompletionCallback callback,
std::unique_ptr<ModelTypeStore> store,
std::unique_ptr<ModelTypeStore::RecordList> record_list,
const base::Optional<syncer::ModelError>& error,
std::unique_ptr<syncer::MetadataBatch> metadata_batch) {
if (error) {
std::move(callback).Run(error, /*store=*/nullptr,
/*metadata_batch=*/nullptr);
return;
}
std::map<std::string, sync_pb::SessionSpecifics> initial_data;
for (ModelTypeStore::Record& record : *record_list) {
const std::string& storage_key = record.id;
SessionSpecifics specifics;
if (storage_key.empty() ||
!specifics.ParseFromString(std::move(record.value))) {
DVLOG(1) << "Ignoring corrupt database entry with key: " << storage_key;
continue;
}
initial_data[storage_key].Swap(&specifics);
}
auto session_store = std::make_unique<SessionStore>(
sessions_client_, session_info, std::move(store),
std::move(initial_data), metadata_batch->GetAllMetadata(),
restored_foreign_tab_callback_);
std::move(callback).Run(/*error=*/base::nullopt, std::move(session_store),
std::move(metadata_batch));
}
Commit Message: Add trace event to sync_sessions::OnReadAllMetadata()
It is likely a cause of janks on UI thread on Android.
Add a trace event to get metrics about the duration.
BUG=902203
Change-Id: I4c4e9c2a20790264b982007ea7ee88ddfa7b972c
Reviewed-on: https://chromium-review.googlesource.com/c/1319369
Reviewed-by: Mikel Astiz <[email protected]>
Commit-Queue: ssid <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606104}
CWE ID: CWE-20 | void OnReadAllMetadata(
const SessionStore::SessionInfo& session_info,
SessionStore::FactoryCompletionCallback callback,
std::unique_ptr<ModelTypeStore> store,
std::unique_ptr<ModelTypeStore::RecordList> record_list,
const base::Optional<syncer::ModelError>& error,
std::unique_ptr<syncer::MetadataBatch> metadata_batch) {
// Remove after fixing https://crbug.com/902203.
TRACE_EVENT0("browser", "FactoryImpl::OnReadAllMetadata");
if (error) {
std::move(callback).Run(error, /*store=*/nullptr,
/*metadata_batch=*/nullptr);
return;
}
std::map<std::string, sync_pb::SessionSpecifics> initial_data;
for (ModelTypeStore::Record& record : *record_list) {
const std::string& storage_key = record.id;
SessionSpecifics specifics;
if (storage_key.empty() ||
!specifics.ParseFromString(std::move(record.value))) {
DVLOG(1) << "Ignoring corrupt database entry with key: " << storage_key;
continue;
}
initial_data[storage_key].Swap(&specifics);
}
auto session_store = std::make_unique<SessionStore>(
sessions_client_, session_info, std::move(store),
std::move(initial_data), metadata_batch->GetAllMetadata(),
restored_foreign_tab_callback_);
std::move(callback).Run(/*error=*/base::nullopt, std::move(session_store),
std::move(metadata_batch));
}
| 172,612 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ConfigureQuicParams(base::StringPiece quic_trial_group,
const VariationParameters& quic_trial_params,
bool is_quic_force_disabled,
bool is_quic_force_enabled,
const std::string& quic_user_agent_id,
net::HttpNetworkSession::Params* params) {
params->enable_quic =
ShouldEnableQuic(quic_trial_group, quic_trial_params,
is_quic_force_disabled, is_quic_force_enabled);
params->mark_quic_broken_when_network_blackholes =
ShouldMarkQuicBrokenWhenNetworkBlackholes(quic_trial_params);
params->enable_server_push_cancellation =
ShouldEnableServerPushCancelation(quic_trial_params);
params->retry_without_alt_svc_on_quic_errors =
ShouldRetryWithoutAltSvcOnQuicErrors(quic_trial_params);
params->support_ietf_format_quic_altsvc =
ShouldSupportIetfFormatQuicAltSvc(quic_trial_params);
if (params->enable_quic) {
params->enable_quic_proxies_for_https_urls =
ShouldEnableQuicProxiesForHttpsUrls(quic_trial_params);
params->enable_quic_proxies_for_https_urls = false;
params->quic_connection_options =
GetQuicConnectionOptions(quic_trial_params);
params->quic_client_connection_options =
GetQuicClientConnectionOptions(quic_trial_params);
params->quic_close_sessions_on_ip_change =
ShouldQuicCloseSessionsOnIpChange(quic_trial_params);
params->quic_goaway_sessions_on_ip_change =
ShouldQuicGoAwaySessionsOnIpChange(quic_trial_params);
int idle_connection_timeout_seconds =
GetQuicIdleConnectionTimeoutSeconds(quic_trial_params);
if (idle_connection_timeout_seconds != 0) {
params->quic_idle_connection_timeout_seconds =
idle_connection_timeout_seconds;
}
int reduced_ping_timeout_seconds =
GetQuicReducedPingTimeoutSeconds(quic_trial_params);
if (reduced_ping_timeout_seconds > 0 &&
reduced_ping_timeout_seconds < quic::kPingTimeoutSecs) {
params->quic_reduced_ping_timeout_seconds = reduced_ping_timeout_seconds;
}
int max_time_before_crypto_handshake_seconds =
GetQuicMaxTimeBeforeCryptoHandshakeSeconds(quic_trial_params);
if (max_time_before_crypto_handshake_seconds > 0) {
params->quic_max_time_before_crypto_handshake_seconds =
max_time_before_crypto_handshake_seconds;
}
int max_idle_time_before_crypto_handshake_seconds =
GetQuicMaxIdleTimeBeforeCryptoHandshakeSeconds(quic_trial_params);
if (max_idle_time_before_crypto_handshake_seconds > 0) {
params->quic_max_idle_time_before_crypto_handshake_seconds =
max_idle_time_before_crypto_handshake_seconds;
}
params->quic_race_cert_verification =
ShouldQuicRaceCertVerification(quic_trial_params);
params->quic_estimate_initial_rtt =
ShouldQuicEstimateInitialRtt(quic_trial_params);
params->quic_headers_include_h2_stream_dependency =
ShouldQuicHeadersIncludeH2StreamDependencies(quic_trial_params);
params->quic_migrate_sessions_on_network_change_v2 =
ShouldQuicMigrateSessionsOnNetworkChangeV2(quic_trial_params);
params->quic_migrate_sessions_early_v2 =
ShouldQuicMigrateSessionsEarlyV2(quic_trial_params);
params->quic_retry_on_alternate_network_before_handshake =
ShouldQuicRetryOnAlternateNetworkBeforeHandshake(quic_trial_params);
params->quic_go_away_on_path_degrading =
ShouldQuicGoawayOnPathDegrading(quic_trial_params);
params->quic_race_stale_dns_on_connection =
ShouldQuicRaceStaleDNSOnConnection(quic_trial_params);
int max_time_on_non_default_network_seconds =
GetQuicMaxTimeOnNonDefaultNetworkSeconds(quic_trial_params);
if (max_time_on_non_default_network_seconds > 0) {
params->quic_max_time_on_non_default_network =
base::TimeDelta::FromSeconds(max_time_on_non_default_network_seconds);
}
int max_migrations_to_non_default_network_on_write_error =
GetQuicMaxNumMigrationsToNonDefaultNetworkOnWriteError(
quic_trial_params);
if (max_migrations_to_non_default_network_on_write_error > 0) {
params->quic_max_migrations_to_non_default_network_on_write_error =
max_migrations_to_non_default_network_on_write_error;
}
int max_migrations_to_non_default_network_on_path_degrading =
GetQuicMaxNumMigrationsToNonDefaultNetworkOnPathDegrading(
quic_trial_params);
if (max_migrations_to_non_default_network_on_path_degrading > 0) {
params->quic_max_migrations_to_non_default_network_on_path_degrading =
max_migrations_to_non_default_network_on_path_degrading;
}
params->quic_allow_server_migration =
ShouldQuicAllowServerMigration(quic_trial_params);
params->quic_host_whitelist = GetQuicHostWhitelist(quic_trial_params);
}
size_t max_packet_length = GetQuicMaxPacketLength(quic_trial_params);
if (max_packet_length != 0) {
params->quic_max_packet_length = max_packet_length;
}
params->quic_user_agent_id = quic_user_agent_id;
quic::QuicTransportVersionVector supported_versions =
GetQuicVersions(quic_trial_params);
if (!supported_versions.empty())
params->quic_supported_versions = supported_versions;
}
Commit Message: Fix a bug in network_session_configurator.cc in which support for HTTPS URLS in QUIC proxies was always set to false.
BUG=914497
Change-Id: I56ad16088168302598bb448553ba32795eee3756
Reviewed-on: https://chromium-review.googlesource.com/c/1417356
Auto-Submit: Ryan Hamilton <[email protected]>
Commit-Queue: Zhongyi Shi <[email protected]>
Reviewed-by: Zhongyi Shi <[email protected]>
Cr-Commit-Position: refs/heads/master@{#623763}
CWE ID: CWE-310 | void ConfigureQuicParams(base::StringPiece quic_trial_group,
const VariationParameters& quic_trial_params,
bool is_quic_force_disabled,
bool is_quic_force_enabled,
const std::string& quic_user_agent_id,
net::HttpNetworkSession::Params* params) {
params->enable_quic =
ShouldEnableQuic(quic_trial_group, quic_trial_params,
is_quic_force_disabled, is_quic_force_enabled);
params->mark_quic_broken_when_network_blackholes =
ShouldMarkQuicBrokenWhenNetworkBlackholes(quic_trial_params);
params->enable_server_push_cancellation =
ShouldEnableServerPushCancelation(quic_trial_params);
params->retry_without_alt_svc_on_quic_errors =
ShouldRetryWithoutAltSvcOnQuicErrors(quic_trial_params);
params->support_ietf_format_quic_altsvc =
ShouldSupportIetfFormatQuicAltSvc(quic_trial_params);
if (params->enable_quic) {
params->enable_quic_proxies_for_https_urls =
ShouldEnableQuicProxiesForHttpsUrls(quic_trial_params);
params->quic_connection_options =
GetQuicConnectionOptions(quic_trial_params);
params->quic_client_connection_options =
GetQuicClientConnectionOptions(quic_trial_params);
params->quic_close_sessions_on_ip_change =
ShouldQuicCloseSessionsOnIpChange(quic_trial_params);
params->quic_goaway_sessions_on_ip_change =
ShouldQuicGoAwaySessionsOnIpChange(quic_trial_params);
int idle_connection_timeout_seconds =
GetQuicIdleConnectionTimeoutSeconds(quic_trial_params);
if (idle_connection_timeout_seconds != 0) {
params->quic_idle_connection_timeout_seconds =
idle_connection_timeout_seconds;
}
int reduced_ping_timeout_seconds =
GetQuicReducedPingTimeoutSeconds(quic_trial_params);
if (reduced_ping_timeout_seconds > 0 &&
reduced_ping_timeout_seconds < quic::kPingTimeoutSecs) {
params->quic_reduced_ping_timeout_seconds = reduced_ping_timeout_seconds;
}
int max_time_before_crypto_handshake_seconds =
GetQuicMaxTimeBeforeCryptoHandshakeSeconds(quic_trial_params);
if (max_time_before_crypto_handshake_seconds > 0) {
params->quic_max_time_before_crypto_handshake_seconds =
max_time_before_crypto_handshake_seconds;
}
int max_idle_time_before_crypto_handshake_seconds =
GetQuicMaxIdleTimeBeforeCryptoHandshakeSeconds(quic_trial_params);
if (max_idle_time_before_crypto_handshake_seconds > 0) {
params->quic_max_idle_time_before_crypto_handshake_seconds =
max_idle_time_before_crypto_handshake_seconds;
}
params->quic_race_cert_verification =
ShouldQuicRaceCertVerification(quic_trial_params);
params->quic_estimate_initial_rtt =
ShouldQuicEstimateInitialRtt(quic_trial_params);
params->quic_headers_include_h2_stream_dependency =
ShouldQuicHeadersIncludeH2StreamDependencies(quic_trial_params);
params->quic_migrate_sessions_on_network_change_v2 =
ShouldQuicMigrateSessionsOnNetworkChangeV2(quic_trial_params);
params->quic_migrate_sessions_early_v2 =
ShouldQuicMigrateSessionsEarlyV2(quic_trial_params);
params->quic_retry_on_alternate_network_before_handshake =
ShouldQuicRetryOnAlternateNetworkBeforeHandshake(quic_trial_params);
params->quic_go_away_on_path_degrading =
ShouldQuicGoawayOnPathDegrading(quic_trial_params);
params->quic_race_stale_dns_on_connection =
ShouldQuicRaceStaleDNSOnConnection(quic_trial_params);
int max_time_on_non_default_network_seconds =
GetQuicMaxTimeOnNonDefaultNetworkSeconds(quic_trial_params);
if (max_time_on_non_default_network_seconds > 0) {
params->quic_max_time_on_non_default_network =
base::TimeDelta::FromSeconds(max_time_on_non_default_network_seconds);
}
int max_migrations_to_non_default_network_on_write_error =
GetQuicMaxNumMigrationsToNonDefaultNetworkOnWriteError(
quic_trial_params);
if (max_migrations_to_non_default_network_on_write_error > 0) {
params->quic_max_migrations_to_non_default_network_on_write_error =
max_migrations_to_non_default_network_on_write_error;
}
int max_migrations_to_non_default_network_on_path_degrading =
GetQuicMaxNumMigrationsToNonDefaultNetworkOnPathDegrading(
quic_trial_params);
if (max_migrations_to_non_default_network_on_path_degrading > 0) {
params->quic_max_migrations_to_non_default_network_on_path_degrading =
max_migrations_to_non_default_network_on_path_degrading;
}
params->quic_allow_server_migration =
ShouldQuicAllowServerMigration(quic_trial_params);
params->quic_host_whitelist = GetQuicHostWhitelist(quic_trial_params);
}
size_t max_packet_length = GetQuicMaxPacketLength(quic_trial_params);
if (max_packet_length != 0) {
params->quic_max_packet_length = max_packet_length;
}
params->quic_user_agent_id = quic_user_agent_id;
quic::QuicTransportVersionVector supported_versions =
GetQuicVersions(quic_trial_params);
if (!supported_versions.empty())
params->quic_supported_versions = supported_versions;
}
| 173,064 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 atusb_read_reg(struct atusb *atusb, uint8_t reg)
{
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
uint8_t value;
dev_dbg(&usb_dev->dev, "atusb: reg = 0x%x\n", reg);
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_REG_READ, ATUSB_REQ_FROM_DEV,
0, reg, &value, 1, 1000);
return ret >= 0 ? value : ret;
}
Commit Message: ieee802154: atusb: do not use the stack for buffers to make them DMA able
From 4.9 we should really avoid using the stack here as this will not be DMA
able on various platforms. This changes the buffers already being present in
time of 4.9 being released. This should go into stable as well.
Reported-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Stefan Schmidt <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-119 | static int atusb_read_reg(struct atusb *atusb, uint8_t reg)
{
struct usb_device *usb_dev = atusb->usb_dev;
int ret;
uint8_t *buffer;
uint8_t value;
buffer = kmalloc(1, GFP_KERNEL);
if (!buffer)
return -ENOMEM;
dev_dbg(&usb_dev->dev, "atusb: reg = 0x%x\n", reg);
ret = atusb_control_msg(atusb, usb_rcvctrlpipe(usb_dev, 0),
ATUSB_REG_READ, ATUSB_REQ_FROM_DEV,
0, reg, buffer, 1, 1000);
if (ret >= 0) {
value = buffer[0];
kfree(buffer);
return value;
} else {
kfree(buffer);
return ret;
}
}
| 168,392 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended)
{
zval *IM, *EXT = NULL;
gdImagePtr im=NULL;
long col = -1, x = -1, y = -1;
int str_len, fontname_len, i, brect[8];
double ptsize, angle;
char *str = NULL, *fontname = NULL;
char *error = NULL;
int argc = ZEND_NUM_ARGS();
gdFTStringExtra strex = {0};
if (mode == TTFTEXT_BBOX) {
if (argc < 4 || argc > ((extended) ? 5 : 4)) {
ZEND_WRONG_PARAM_COUNT();
} else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
RETURN_FALSE;
}
} else {
if (argc < 8 || argc > ((extended) ? 9 : 8)) {
ZEND_WRONG_PARAM_COUNT();
} else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
}
/* convert angle to radians */
angle = angle * (M_PI/180);
if (extended && EXT) { /* parse extended info */
HashPosition pos;
/* walk the assoc array */
zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos);
do {
zval ** item;
char * key;
ulong num_key;
if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) {
continue;
}
if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) {
continue;
}
if (strcmp("linespacing", key) == 0) {
convert_to_double_ex(item);
strex.flags |= gdFTEX_LINESPACE;
strex.linespacing = Z_DVAL_PP(item);
}
} while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS);
}
#ifdef VIRTUAL_DIR
{
char tmp_font_path[MAXPATHLEN];
if (!VCWD_REALPATH(fontname, tmp_font_path)) {
fontname = NULL;
}
}
#endif /* VIRTUAL_DIR */
PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename");
#ifdef HAVE_GD_FREETYPE
if (extended) {
error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex);
}
else
error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str);
#endif /* HAVE_GD_FREETYPE */
if (error) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error);
RETURN_FALSE;
}
array_init(return_value);
/* return array with the text's bounding box */
for (i = 0; i < 8; i++) {
add_next_index_long(return_value, brect[i]);
}
}
Commit Message: Fix bug#72697 - select_colors write out-of-bounds
CWE ID: CWE-787 | static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int extended)
{
zval *IM, *EXT = NULL;
gdImagePtr im=NULL;
long col = -1, x = -1, y = -1;
int str_len, fontname_len, i, brect[8];
double ptsize, angle;
char *str = NULL, *fontname = NULL;
char *error = NULL;
int argc = ZEND_NUM_ARGS();
gdFTStringExtra strex = {0};
if (mode == TTFTEXT_BBOX) {
if (argc < 4 || argc > ((extended) ? 5 : 4)) {
ZEND_WRONG_PARAM_COUNT();
} else if (zend_parse_parameters(argc TSRMLS_CC, "ddss|a", &ptsize, &angle, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
RETURN_FALSE;
}
} else {
if (argc < 8 || argc > ((extended) ? 9 : 8)) {
ZEND_WRONG_PARAM_COUNT();
} else if (zend_parse_parameters(argc TSRMLS_CC, "rddlllss|a", &IM, &ptsize, &angle, &x, &y, &col, &fontname, &fontname_len, &str, &str_len, &EXT) == FAILURE) {
RETURN_FALSE;
}
ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, "Image", le_gd);
}
/* convert angle to radians */
angle = angle * (M_PI/180);
if (extended && EXT) { /* parse extended info */
HashPosition pos;
/* walk the assoc array */
zend_hash_internal_pointer_reset_ex(HASH_OF(EXT), &pos);
do {
zval ** item;
char * key;
ulong num_key;
if (zend_hash_get_current_key_ex(HASH_OF(EXT), &key, NULL, &num_key, 0, &pos) != HASH_KEY_IS_STRING) {
continue;
}
if (zend_hash_get_current_data_ex(HASH_OF(EXT), (void **) &item, &pos) == FAILURE) {
continue;
}
if (strcmp("linespacing", key) == 0) {
convert_to_double_ex(item);
strex.flags |= gdFTEX_LINESPACE;
strex.linespacing = Z_DVAL_PP(item);
}
} while (zend_hash_move_forward_ex(HASH_OF(EXT), &pos) == SUCCESS);
}
#ifdef VIRTUAL_DIR
{
char tmp_font_path[MAXPATHLEN];
if (!VCWD_REALPATH(fontname, tmp_font_path)) {
fontname = NULL;
}
}
#endif /* VIRTUAL_DIR */
PHP_GD_CHECK_OPEN_BASEDIR(fontname, "Invalid font filename");
#ifdef HAVE_GD_FREETYPE
if (extended) {
error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex);
}
else
error = gdImageStringFT(im, brect, col, fontname, ptsize, angle, x, y, str);
#endif /* HAVE_GD_FREETYPE */
if (error) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", error);
RETURN_FALSE;
}
array_init(return_value);
/* return array with the text's bounding box */
for (i = 0; i < 8; i++) {
add_next_index_long(return_value, brect[i]);
}
}
| 166,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long CuePoint::GetTime(const Segment* pSegment) const
{
assert(pSegment);
assert(m_timecode >= 0);
const SegmentInfo* const pInfo = pSegment->GetInfo();
assert(pInfo);
const long long scale = pInfo->GetTimeCodeScale();
assert(scale >= 1);
const long long time = scale * m_timecode;
return time;
}
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 CuePoint::GetTime(const Segment* pSegment) const
| 174,364 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip)
{
CPUState *cs = CPU(cpu);
CPUX86State *env = &cpu->env;
VAPICHandlers *handlers;
uint8_t opcode[2];
uint32_t imm32;
target_ulong current_pc = 0;
target_ulong current_cs_base = 0;
uint32_t current_flags = 0;
if (smp_cpus == 1) {
handlers = &s->rom_state.up;
} else {
handlers = &s->rom_state.mp;
}
if (!kvm_enabled()) {
cpu_get_tb_cpu_state(env, ¤t_pc, ¤t_cs_base,
¤t_flags);
}
pause_all_vcpus();
cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0);
switch (opcode[0]) {
case 0x89: /* mov r32 to r/m32 */
patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */
patch_call(s, cpu, ip + 1, handlers->set_tpr);
break;
case 0x8b: /* mov r/m32 to r32 */
patch_byte(cpu, ip, 0x90);
patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]);
break;
case 0xa1: /* mov abs to eax */
patch_call(s, cpu, ip, handlers->get_tpr[0]);
break;
case 0xa3: /* mov eax to abs */
patch_call(s, cpu, ip, handlers->set_tpr_eax);
break;
case 0xc7: /* mov imm32, r/m32 (c7/0) */
patch_byte(cpu, ip, 0x68); /* push imm32 */
cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0);
cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1);
patch_call(s, cpu, ip + 5, handlers->set_tpr);
break;
case 0xff: /* push r/m32 */
patch_byte(cpu, ip, 0x50); /* push eax */
patch_call(s, cpu, ip + 1, handlers->get_tpr_stack);
break;
default:
abort();
}
resume_all_vcpus();
if (!kvm_enabled()) {
tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1);
cpu_resume_from_signal(cs, NULL);
}
}
Commit Message:
CWE ID: CWE-200 | static void patch_instruction(VAPICROMState *s, X86CPU *cpu, target_ulong ip)
{
CPUState *cs = CPU(cpu);
CPUX86State *env = &cpu->env;
VAPICHandlers *handlers;
uint8_t opcode[2];
uint32_t imm32 = 0;
target_ulong current_pc = 0;
target_ulong current_cs_base = 0;
uint32_t current_flags = 0;
if (smp_cpus == 1) {
handlers = &s->rom_state.up;
} else {
handlers = &s->rom_state.mp;
}
if (!kvm_enabled()) {
cpu_get_tb_cpu_state(env, ¤t_pc, ¤t_cs_base,
¤t_flags);
}
pause_all_vcpus();
cpu_memory_rw_debug(cs, ip, opcode, sizeof(opcode), 0);
switch (opcode[0]) {
case 0x89: /* mov r32 to r/m32 */
patch_byte(cpu, ip, 0x50 + modrm_reg(opcode[1])); /* push reg */
patch_call(s, cpu, ip + 1, handlers->set_tpr);
break;
case 0x8b: /* mov r/m32 to r32 */
patch_byte(cpu, ip, 0x90);
patch_call(s, cpu, ip + 1, handlers->get_tpr[modrm_reg(opcode[1])]);
break;
case 0xa1: /* mov abs to eax */
patch_call(s, cpu, ip, handlers->get_tpr[0]);
break;
case 0xa3: /* mov eax to abs */
patch_call(s, cpu, ip, handlers->set_tpr_eax);
break;
case 0xc7: /* mov imm32, r/m32 (c7/0) */
patch_byte(cpu, ip, 0x68); /* push imm32 */
cpu_memory_rw_debug(cs, ip + 6, (void *)&imm32, sizeof(imm32), 0);
cpu_memory_rw_debug(cs, ip + 1, (void *)&imm32, sizeof(imm32), 1);
patch_call(s, cpu, ip + 5, handlers->set_tpr);
break;
case 0xff: /* push r/m32 */
patch_byte(cpu, ip, 0x50); /* push eax */
patch_call(s, cpu, ip + 1, handlers->get_tpr_stack);
break;
default:
abort();
}
resume_all_vcpus();
if (!kvm_enabled()) {
tb_gen_code(cs, current_pc, current_cs_base, current_flags, 1);
cpu_resume_from_signal(cs, NULL);
}
}
| 165,076 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ImageDecodedHandlerWithTimeout(
const base::Callback<void(const SkBitmap&)>& image_decoded_callback)
: image_decoded_callback_(image_decoded_callback),
weak_ptr_factory_(this) {}
Commit Message: Local NTP: add smoke tests for doodles
Split LogoService into LogoService interface and LogoServiceImpl to make
it easier to provide fake data to the test.
Bug: 768419
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I84639189d2db1b24a2e139936c99369352bab587
Reviewed-on: https://chromium-review.googlesource.com/690198
Reviewed-by: Sylvain Defresne <[email protected]>
Reviewed-by: Marc Treib <[email protected]>
Commit-Queue: Chris Pickel <[email protected]>
Cr-Commit-Position: refs/heads/master@{#505374}
CWE ID: CWE-119 | explicit ImageDecodedHandlerWithTimeout(
| 171,953 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: magic_setparam(struct magic_set *ms, int param, const void *val)
{
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
ms->indir_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_NAME_MAX:
ms->name_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
ms->elf_phnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
ms->elf_shnum_max = *(const size_t *)val;
return 0;
default:
errno = EINVAL;
return -1;
}
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399 | magic_setparam(struct magic_set *ms, int param, const void *val)
{
switch (param) {
case MAGIC_PARAM_INDIR_MAX:
ms->indir_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_NAME_MAX:
ms->name_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_PHNUM_MAX:
ms->elf_phnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_SHNUM_MAX:
ms->elf_shnum_max = *(const size_t *)val;
return 0;
case MAGIC_PARAM_ELF_NOTES_MAX:
ms->elf_notes_max = *(const size_t *)val;
return 0;
default:
errno = EINVAL;
return -1;
}
}
| 166,775 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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: static void hid_input_field(struct hid_device *hid, struct hid_field *field,
__u8 *data, int interrupt)
{
unsigned n;
unsigned count = field->report_count;
unsigned offset = field->report_offset;
unsigned size = field->report_size;
__s32 min = field->logical_minimum;
__s32 max = field->logical_maximum;
__s32 *value;
value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);
if (!value)
return;
for (n = 0; n < count; n++) {
value[n] = min < 0 ?
snto32(hid_field_extract(hid, data, offset + n * size,
size), size) :
hid_field_extract(hid, data, offset + n * size, size);
/* Ignore report if ErrorRollOver */
if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
value[n] >= min && value[n] <= max &&
field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)
goto exit;
}
for (n = 0; n < count; n++) {
if (HID_MAIN_ITEM_VARIABLE & field->flags) {
hid_process_event(hid, field, &field->usage[n], value[n], interrupt);
continue;
}
if (field->value[n] >= min && field->value[n] <= max
&& field->usage[field->value[n] - min].hid
&& search(value, field->value[n], count))
hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);
if (value[n] >= min && value[n] <= max
&& field->usage[value[n] - min].hid
&& search(field->value, value[n], count))
hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);
}
memcpy(field->value, value, count * sizeof(__s32));
exit:
kfree(value);
}
Commit Message: HID: core: prevent out-of-bound readings
Plugging a Logitech DJ receiver with KASAN activated raises a bunch of
out-of-bound readings.
The fields are allocated up to MAX_USAGE, meaning that potentially, we do
not have enough fields to fit the incoming values.
Add checks and silence KASAN.
Signed-off-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-125 | static void hid_input_field(struct hid_device *hid, struct hid_field *field,
__u8 *data, int interrupt)
{
unsigned n;
unsigned count = field->report_count;
unsigned offset = field->report_offset;
unsigned size = field->report_size;
__s32 min = field->logical_minimum;
__s32 max = field->logical_maximum;
__s32 *value;
value = kmalloc(sizeof(__s32) * count, GFP_ATOMIC);
if (!value)
return;
for (n = 0; n < count; n++) {
value[n] = min < 0 ?
snto32(hid_field_extract(hid, data, offset + n * size,
size), size) :
hid_field_extract(hid, data, offset + n * size, size);
/* Ignore report if ErrorRollOver */
if (!(field->flags & HID_MAIN_ITEM_VARIABLE) &&
value[n] >= min && value[n] <= max &&
value[n] - min < field->maxusage &&
field->usage[value[n] - min].hid == HID_UP_KEYBOARD + 1)
goto exit;
}
for (n = 0; n < count; n++) {
if (HID_MAIN_ITEM_VARIABLE & field->flags) {
hid_process_event(hid, field, &field->usage[n], value[n], interrupt);
continue;
}
if (field->value[n] >= min && field->value[n] <= max
&& field->value[n] - min < field->maxusage
&& field->usage[field->value[n] - min].hid
&& search(value, field->value[n], count))
hid_process_event(hid, field, &field->usage[field->value[n] - min], 0, interrupt);
if (value[n] >= min && value[n] <= max
&& value[n] - min < field->maxusage
&& field->usage[value[n] - min].hid
&& search(field->value, value[n], count))
hid_process_event(hid, field, &field->usage[value[n] - min], 1, interrupt);
}
memcpy(field->value, value, count * sizeof(__s32));
exit:
kfree(value);
}
| 166,921 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
switch (cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m);
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s))
len = sizeof(p->s) - 1;
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
Commit Message: * Enforce limit of 8K on regex searches that have no limits
* Allow the l modifier for regex to mean line count. Default
to byte count. If line count is specified, assume a max
of 80 characters per line to limit the byte count.
* Don't allow conversions to be used for dates, allowing
the mask field to be used as an offset.
* Bump the version of the magic format so that regex changes
are visible.
CWE ID: CWE-399 | mconvert(struct magic_set *ms, struct magic *m, int flip)
{
union VALUETYPE *p = &ms->ms_value;
uint8_t type;
switch (type = cvt_flip(m->type, flip)) {
case FILE_BYTE:
cvt_8(p, m);
return 1;
case FILE_SHORT:
cvt_16(p, m);
return 1;
case FILE_LONG:
case FILE_DATE:
case FILE_LDATE:
cvt_32(p, m);
return 1;
case FILE_QUAD:
case FILE_QDATE:
case FILE_QLDATE:
case FILE_QWDATE:
cvt_64(p, m);
return 1;
case FILE_STRING:
case FILE_BESTRING16:
case FILE_LESTRING16: {
/* Null terminate and eat *trailing* return */
p->s[sizeof(p->s) - 1] = '\0';
return 1;
}
case FILE_PSTRING: {
char *ptr1 = p->s, *ptr2 = ptr1 + file_pstring_length_size(m);
size_t len = file_pstring_get_length(m, ptr1);
if (len >= sizeof(p->s))
len = sizeof(p->s) - 1;
while (len--)
*ptr1++ = *ptr2++;
*ptr1 = '\0';
return 1;
}
case FILE_BESHORT:
p->h = (short)((p->hs[0]<<8)|(p->hs[1]));
cvt_16(p, m);
return 1;
case FILE_BELONG:
case FILE_BEDATE:
case FILE_BELDATE:
p->l = (int32_t)
((p->hl[0]<<24)|(p->hl[1]<<16)|(p->hl[2]<<8)|(p->hl[3]));
if (type == FILE_BELONG)
cvt_32(p, m);
return 1;
case FILE_BEQUAD:
case FILE_BEQDATE:
case FILE_BEQLDATE:
case FILE_BEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8)|((uint64_t)p->hq[7]));
if (type == FILE_BEQUAD)
cvt_64(p, m);
return 1;
case FILE_LESHORT:
p->h = (short)((p->hs[1]<<8)|(p->hs[0]));
cvt_16(p, m);
return 1;
case FILE_LELONG:
case FILE_LEDATE:
case FILE_LELDATE:
p->l = (int32_t)
((p->hl[3]<<24)|(p->hl[2]<<16)|(p->hl[1]<<8)|(p->hl[0]));
if (type == FILE_LELONG)
cvt_32(p, m);
return 1;
case FILE_LEQUAD:
case FILE_LEQDATE:
case FILE_LEQLDATE:
case FILE_LEQWDATE:
p->q = (uint64_t)
(((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8)|((uint64_t)p->hq[0]));
if (type == FILE_LEQUAD)
cvt_64(p, m);
return 1;
case FILE_MELONG:
case FILE_MEDATE:
case FILE_MELDATE:
p->l = (int32_t)
((p->hl[1]<<24)|(p->hl[0]<<16)|(p->hl[3]<<8)|(p->hl[2]));
if (type == FILE_MELONG)
cvt_32(p, m);
return 1;
case FILE_FLOAT:
cvt_float(p, m);
return 1;
case FILE_BEFLOAT:
p->l = ((uint32_t)p->hl[0]<<24)|((uint32_t)p->hl[1]<<16)|
((uint32_t)p->hl[2]<<8) |((uint32_t)p->hl[3]);
cvt_float(p, m);
return 1;
case FILE_LEFLOAT:
p->l = ((uint32_t)p->hl[3]<<24)|((uint32_t)p->hl[2]<<16)|
((uint32_t)p->hl[1]<<8) |((uint32_t)p->hl[0]);
cvt_float(p, m);
return 1;
case FILE_DOUBLE:
cvt_double(p, m);
return 1;
case FILE_BEDOUBLE:
p->q = ((uint64_t)p->hq[0]<<56)|((uint64_t)p->hq[1]<<48)|
((uint64_t)p->hq[2]<<40)|((uint64_t)p->hq[3]<<32)|
((uint64_t)p->hq[4]<<24)|((uint64_t)p->hq[5]<<16)|
((uint64_t)p->hq[6]<<8) |((uint64_t)p->hq[7]);
cvt_double(p, m);
return 1;
case FILE_LEDOUBLE:
p->q = ((uint64_t)p->hq[7]<<56)|((uint64_t)p->hq[6]<<48)|
((uint64_t)p->hq[5]<<40)|((uint64_t)p->hq[4]<<32)|
((uint64_t)p->hq[3]<<24)|((uint64_t)p->hq[2]<<16)|
((uint64_t)p->hq[1]<<8) |((uint64_t)p->hq[0]);
cvt_double(p, m);
return 1;
case FILE_REGEX:
case FILE_SEARCH:
case FILE_DEFAULT:
case FILE_CLEAR:
case FILE_NAME:
case FILE_USE:
return 1;
default:
file_magerror(ms, "invalid type %d in mconvert()", m->type);
return 0;
}
}
| 166,358 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
memset(outHeader->pBuffer,
0,
mConfig->outputFrameSize * sizeof(int16_t));
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
Commit Message: Check mp3 output buffer size
Bug: 27793371
Change-Id: I0fe40a4cfd0a5b488f93d3f3ba6f9495235926ac
CWE ID: CWE-20 | void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError || mOutputPortSettingsChange != NONE) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) {
BufferInfo *inInfo = NULL;
OMX_BUFFERHEADERTYPE *inHeader = NULL;
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
}
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
if (inHeader) {
if (inHeader->nOffset == 0 && inHeader->nFilledLen) {
mAnchorTimeUs = inHeader->nTimeStamp;
mNumFramesOutput = 0;
}
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mSawInputEos = true;
}
mConfig->pInputBuffer =
inHeader->pBuffer + inHeader->nOffset;
mConfig->inputBufferCurrentLength = inHeader->nFilledLen;
} else {
mConfig->pInputBuffer = NULL;
mConfig->inputBufferCurrentLength = 0;
}
mConfig->inputBufferMaxLength = 0;
mConfig->inputBufferUsedLength = 0;
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) {
ALOGE("input buffer too small: got %lu, expected %u",
outHeader->nAllocLen, mConfig->outputFrameSize);
android_errorWriteLog(0x534e4554, "27793371");
notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL);
mSignalledError = true;
return;
}
mConfig->pOutputBuffer =
reinterpret_cast<int16_t *>(outHeader->pBuffer);
ERROR_CODE decoderErr;
if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf))
!= NO_DECODING_ERROR) {
ALOGV("mp3 decoder returned error %d", decoderErr);
if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR
&& decoderErr != SIDE_INFO_ERROR) {
ALOGE("mp3 decoder returned error %d", decoderErr);
notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL);
mSignalledError = true;
return;
}
if (mConfig->outputFrameSize == 0) {
mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t);
}
if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) {
if (!mIsFirst) {
outHeader->nOffset = 0;
outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
memset(outHeader->pBuffer, 0, outHeader->nFilledLen);
}
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
mSignalledOutputEos = true;
} else {
ALOGV_IF(mIsFirst, "insufficient data for first frame, sending silence");
memset(outHeader->pBuffer,
0,
mConfig->outputFrameSize * sizeof(int16_t));
if (inHeader) {
mConfig->inputBufferUsedLength = inHeader->nFilledLen;
}
}
} else if (mConfig->samplingRate != mSamplingRate
|| mConfig->num_channels != mNumChannels) {
mSamplingRate = mConfig->samplingRate;
mNumChannels = mConfig->num_channels;
notify(OMX_EventPortSettingsChanged, 1, 0, NULL);
mOutputPortSettingsChange = AWAITING_DISABLED;
return;
}
if (mIsFirst) {
mIsFirst = false;
outHeader->nOffset =
kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t);
outHeader->nFilledLen =
mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset;
} else if (!mSignalledOutputEos) {
outHeader->nOffset = 0;
outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t);
}
outHeader->nTimeStamp =
mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate;
if (inHeader) {
CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength);
inHeader->nOffset += mConfig->inputBufferUsedLength;
inHeader->nFilledLen -= mConfig->inputBufferUsedLength;
if (inHeader->nFilledLen == 0) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
mNumFramesOutput += mConfig->outputFrameSize / mNumChannels;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
| 173,777 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: zsetstrokecolor(i_ctx_t * i_ctx_p)
{
int code;
code = zswapcolors(i_ctx_p);
if (code < 0)
/* Set up for the continuation procedure which will finish by restoring the fill colour space */
/* Make sure the exec stack has enough space */
check_estack(1);
/* Now, the actual continuation routine */
push_op_estack(setstrokecolor_cont);
code = zsetcolor(i_ctx_p);
if (code >= 0)
if (code >= 0)
return o_push_estack;
return code;
}
Commit Message:
CWE ID: CWE-119 | zsetstrokecolor(i_ctx_t * i_ctx_p)
{
int code;
es_ptr iesp = esp; /* preserve exec stack in case of error */
code = zswapcolors(i_ctx_p);
if (code < 0)
/* Set up for the continuation procedure which will finish by restoring the fill colour space */
/* Make sure the exec stack has enough space */
check_estack(1);
/* Now, the actual continuation routine */
push_op_estack(setstrokecolor_cont);
code = zsetcolor(i_ctx_p);
if (code >= 0)
if (code >= 0)
return o_push_estack;
/* Something went wrong, swap back to the non-stroking colour and restore the exec stack */
esp = iesp;
(void)zswapcolors(i_ctx_p);
return code;
}
| 164,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 em_jcxz(struct x86_emulate_ctxt *ctxt)
{
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
jmp_rel(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int em_jcxz(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0)
rc = jmp_rel(ctxt, ctxt->src.val);
return rc;
}
| 169,911 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return 0;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
return htonl(id);
}
Commit Message: inet: switch IP ID generator to siphash
According to Amit Klein and Benny Pinkas, IP ID generation is too weak
and might be used by attackers.
Even with recent net_hash_mix() fix (netns: provide pure entropy for net_hash_mix())
having 64bit key and Jenkins hash is risky.
It is time to switch to siphash and its 128bit keys.
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Amit Klein <[email protected]>
Reported-by: Benny Pinkas <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return 0;
id = __ipv6_select_ident(net, &addrs[1], &addrs[0]);
return htonl(id);
}
| 169,718 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
Commit Message: Avoid integer overflows in parsing fonts
A malformed TTF can cause size calculations to overflow. This patch
checks the maximum reasonable value so that the total size fits in 32
bits. It also adds some explicit casting to avoid possible technical
undefined behavior when parsing sized unsigned values.
Bug: 25645298
Change-Id: Id4716132041a6f4f1fbb73ec4e445391cf7d9616
(cherry picked from commit 183c9ec2800baa2ce099ee260c6cbc6121cf1274)
CWE ID: CWE-19 | static bool getCoverageFormat12(vector<uint32_t>& coverage, const uint8_t* data, size_t size) {
const size_t kNGroupsOffset = 12;
const size_t kFirstGroupOffset = 16;
const size_t kGroupSize = 12;
const size_t kStartCharCodeOffset = 0;
const size_t kEndCharCodeOffset = 4;
const size_t kMaxNGroups = 0xfffffff0 / kGroupSize; // protection against overflow
// For all values < kMaxNGroups, kFirstGroupOffset + nGroups * kGroupSize fits in 32 bits.
if (kFirstGroupOffset > size) {
return false;
}
uint32_t nGroups = readU32(data, kNGroupsOffset);
if (nGroups >= kMaxNGroups || kFirstGroupOffset + nGroups * kGroupSize > size) {
return false;
}
for (uint32_t i = 0; i < nGroups; i++) {
uint32_t groupOffset = kFirstGroupOffset + i * kGroupSize;
uint32_t start = readU32(data, groupOffset + kStartCharCodeOffset);
uint32_t end = readU32(data, groupOffset + kEndCharCodeOffset);
addRange(coverage, start, end + 1); // file is inclusive, vector is exclusive
}
return true;
}
| 173,965 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: gfx::Rect ShellWindowFrameView::GetBoundsForClientView() const {
if (frame_->IsFullscreen())
return bounds();
return gfx::Rect(0, kCaptionHeight, width(),
std::max(0, height() - kCaptionHeight));
}
Commit Message: [views] Remove header bar on shell windows created with {frame: none}.
BUG=130182
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10597003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143439 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-79 | gfx::Rect ShellWindowFrameView::GetBoundsForClientView() const {
if (is_frameless_ || frame_->IsFullscreen())
return bounds();
return gfx::Rect(0, kCaptionHeight, width(),
std::max(0, height() - kCaptionHeight));
}
| 170,711 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltCopyTreeInternal(xsltTransformContextPtr ctxt,
xmlNodePtr invocNode,
xmlNodePtr node,
xmlNodePtr insert, int isLRE, int topElemVisited)
{
xmlNodePtr copy;
if (node == NULL)
return(NULL);
switch (node->type) {
case XML_ELEMENT_NODE:
case XML_ENTITY_REF_NODE:
case XML_ENTITY_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
#ifdef LIBXML_DOCB_ENABLED
case XML_DOCB_DOCUMENT_NODE:
#endif
break;
case XML_TEXT_NODE: {
int noenc = (node->name == xmlStringTextNoenc);
return(xsltCopyTextString(ctxt, insert, node->content, noenc));
}
case XML_CDATA_SECTION_NODE:
return(xsltCopyTextString(ctxt, insert, node->content, 0));
case XML_ATTRIBUTE_NODE:
return((xmlNodePtr)
xsltShallowCopyAttr(ctxt, invocNode, insert, (xmlAttrPtr) node));
case XML_NAMESPACE_DECL:
return((xmlNodePtr) xsltShallowCopyNsNode(ctxt, invocNode,
insert, (xmlNsPtr) node));
case XML_DOCUMENT_TYPE_NODE:
case XML_DOCUMENT_FRAG_NODE:
case XML_NOTATION_NODE:
case XML_DTD_NODE:
case XML_ELEMENT_DECL:
case XML_ATTRIBUTE_DECL:
case XML_ENTITY_DECL:
case XML_XINCLUDE_START:
case XML_XINCLUDE_END:
return(NULL);
}
if (XSLT_IS_RES_TREE_FRAG(node)) {
if (node->children != NULL)
copy = xsltCopyTreeList(ctxt, invocNode,
node->children, insert, 0, 0);
else
copy = NULL;
return(copy);
}
copy = xmlDocCopyNode(node, insert->doc, 0);
if (copy != NULL) {
copy->doc = ctxt->output;
copy = xsltAddChild(insert, copy);
/*
* The node may have been coalesced into another text node.
*/
if (insert->last != copy)
return(insert->last);
copy->next = NULL;
if (node->type == XML_ELEMENT_NODE) {
/*
* Copy in-scope namespace nodes.
*
* REVISIT: Since we try to reuse existing in-scope ns-decls by
* using xmlSearchNsByHref(), this will eventually change
* the prefix of an original ns-binding; thus it might
* break QNames in element/attribute content.
* OPTIMIZE TODO: If we had a xmlNsPtr * on the transformation
* context, plus a ns-lookup function, which writes directly
* to a given list, then we wouldn't need to create/free the
* nsList every time.
*/
if ((topElemVisited == 0) &&
(node->parent != NULL) &&
(node->parent->type != XML_DOCUMENT_NODE) &&
(node->parent->type != XML_HTML_DOCUMENT_NODE))
{
xmlNsPtr *nsList, *curns, ns;
/*
* If this is a top-most element in a tree to be
* copied, then we need to ensure that all in-scope
* namespaces are copied over. For nodes deeper in the
* tree, it is sufficient to reconcile only the ns-decls
* (node->nsDef entries).
*/
nsList = xmlGetNsList(node->doc, node);
if (nsList != NULL) {
curns = nsList;
do {
/*
* Search by prefix first in order to break as less
* QNames in element/attribute content as possible.
*/
ns = xmlSearchNs(insert->doc, insert,
(*curns)->prefix);
if ((ns == NULL) ||
(! xmlStrEqual(ns->href, (*curns)->href)))
{
ns = NULL;
/*
* Search by namespace name.
* REVISIT TODO: Currently disabled.
*/
#if 0
ns = xmlSearchNsByHref(insert->doc,
insert, (*curns)->href);
#endif
}
if (ns == NULL) {
/*
* Declare a new namespace on the copied element.
*/
ns = xmlNewNs(copy, (*curns)->href,
(*curns)->prefix);
/* TODO: Handle errors */
}
if (node->ns == *curns) {
/*
* If this was the original's namespace then set
* the generated counterpart on the copy.
*/
copy->ns = ns;
}
curns++;
} while (*curns != NULL);
xmlFree(nsList);
}
} else if (node->nsDef != NULL) {
/*
* Copy over all namespace declaration attributes.
*/
if (node->nsDef != NULL) {
if (isLRE)
xsltCopyNamespaceList(ctxt, copy, node->nsDef);
else
xsltCopyNamespaceListInternal(copy, node->nsDef);
}
}
/*
* Set the namespace.
*/
if (node->ns != NULL) {
if (copy->ns == NULL) {
/*
* This will map copy->ns to one of the newly created
* in-scope ns-decls, OR create a new ns-decl on @copy.
*/
copy->ns = xsltGetSpecialNamespace(ctxt, invocNode,
node->ns->href, node->ns->prefix, copy);
}
} else if ((insert->type == XML_ELEMENT_NODE) &&
(insert->ns != NULL))
{
/*
* "Undeclare" the default namespace on @copy with xmlns="".
*/
xsltGetSpecialNamespace(ctxt, invocNode, NULL, NULL, copy);
}
/*
* Copy attribute nodes.
*/
if (node->properties != NULL) {
xsltCopyAttrListNoOverwrite(ctxt, invocNode,
copy, node->properties);
}
if (topElemVisited == 0)
topElemVisited = 1;
}
/*
* Copy the subtree.
*/
if (node->children != NULL) {
xsltCopyTreeList(ctxt, invocNode,
node->children, copy, isLRE, topElemVisited);
}
} else {
xsltTransformError(ctxt, NULL, invocNode,
"xsltCopyTreeInternal: Copying of '%s' failed.\n", node->name);
}
return(copy);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltCopyTreeInternal(xsltTransformContextPtr ctxt,
xmlNodePtr invocNode,
xmlNodePtr node,
xmlNodePtr insert, int isLRE, int topElemVisited)
{
xmlNodePtr copy;
if (node == NULL)
return(NULL);
switch (node->type) {
case XML_ELEMENT_NODE:
case XML_ENTITY_REF_NODE:
case XML_ENTITY_NODE:
case XML_PI_NODE:
case XML_COMMENT_NODE:
case XML_DOCUMENT_NODE:
case XML_HTML_DOCUMENT_NODE:
#ifdef LIBXML_DOCB_ENABLED
case XML_DOCB_DOCUMENT_NODE:
#endif
break;
case XML_TEXT_NODE: {
int noenc = (node->name == xmlStringTextNoenc);
return(xsltCopyTextString(ctxt, insert, node->content, noenc));
}
case XML_CDATA_SECTION_NODE:
return(xsltCopyTextString(ctxt, insert, node->content, 0));
case XML_ATTRIBUTE_NODE:
return((xmlNodePtr)
xsltShallowCopyAttr(ctxt, invocNode, insert, (xmlAttrPtr) node));
case XML_NAMESPACE_DECL:
return((xmlNodePtr) xsltShallowCopyNsNode(ctxt, invocNode,
insert, (xmlNsPtr) node));
case XML_DOCUMENT_TYPE_NODE:
case XML_DOCUMENT_FRAG_NODE:
case XML_NOTATION_NODE:
case XML_DTD_NODE:
case XML_ELEMENT_DECL:
case XML_ATTRIBUTE_DECL:
case XML_ENTITY_DECL:
case XML_XINCLUDE_START:
case XML_XINCLUDE_END:
return(NULL);
}
if (XSLT_IS_RES_TREE_FRAG(node)) {
if (node->children != NULL)
copy = xsltCopyTreeList(ctxt, invocNode,
node->children, insert, 0, 0);
else
copy = NULL;
return(copy);
}
copy = xmlDocCopyNode(node, insert->doc, 0);
if (copy != NULL) {
copy->doc = ctxt->output;
copy = xsltAddChild(insert, copy);
if (copy == NULL) {
xsltTransformError(ctxt, NULL, invocNode,
"xsltCopyTreeInternal: Copying of '%s' failed.\n", node->name);
return (copy);
}
/*
* The node may have been coalesced into another text node.
*/
if (insert->last != copy)
return(insert->last);
copy->next = NULL;
if (node->type == XML_ELEMENT_NODE) {
/*
* Copy in-scope namespace nodes.
*
* REVISIT: Since we try to reuse existing in-scope ns-decls by
* using xmlSearchNsByHref(), this will eventually change
* the prefix of an original ns-binding; thus it might
* break QNames in element/attribute content.
* OPTIMIZE TODO: If we had a xmlNsPtr * on the transformation
* context, plus a ns-lookup function, which writes directly
* to a given list, then we wouldn't need to create/free the
* nsList every time.
*/
if ((topElemVisited == 0) &&
(node->parent != NULL) &&
(node->parent->type != XML_DOCUMENT_NODE) &&
(node->parent->type != XML_HTML_DOCUMENT_NODE))
{
xmlNsPtr *nsList, *curns, ns;
/*
* If this is a top-most element in a tree to be
* copied, then we need to ensure that all in-scope
* namespaces are copied over. For nodes deeper in the
* tree, it is sufficient to reconcile only the ns-decls
* (node->nsDef entries).
*/
nsList = xmlGetNsList(node->doc, node);
if (nsList != NULL) {
curns = nsList;
do {
/*
* Search by prefix first in order to break as less
* QNames in element/attribute content as possible.
*/
ns = xmlSearchNs(insert->doc, insert,
(*curns)->prefix);
if ((ns == NULL) ||
(! xmlStrEqual(ns->href, (*curns)->href)))
{
ns = NULL;
/*
* Search by namespace name.
* REVISIT TODO: Currently disabled.
*/
#if 0
ns = xmlSearchNsByHref(insert->doc,
insert, (*curns)->href);
#endif
}
if (ns == NULL) {
/*
* Declare a new namespace on the copied element.
*/
ns = xmlNewNs(copy, (*curns)->href,
(*curns)->prefix);
/* TODO: Handle errors */
}
if (node->ns == *curns) {
/*
* If this was the original's namespace then set
* the generated counterpart on the copy.
*/
copy->ns = ns;
}
curns++;
} while (*curns != NULL);
xmlFree(nsList);
}
} else if (node->nsDef != NULL) {
/*
* Copy over all namespace declaration attributes.
*/
if (node->nsDef != NULL) {
if (isLRE)
xsltCopyNamespaceList(ctxt, copy, node->nsDef);
else
xsltCopyNamespaceListInternal(copy, node->nsDef);
}
}
/*
* Set the namespace.
*/
if (node->ns != NULL) {
if (copy->ns == NULL) {
/*
* This will map copy->ns to one of the newly created
* in-scope ns-decls, OR create a new ns-decl on @copy.
*/
copy->ns = xsltGetSpecialNamespace(ctxt, invocNode,
node->ns->href, node->ns->prefix, copy);
}
} else if ((insert->type == XML_ELEMENT_NODE) &&
(insert->ns != NULL))
{
/*
* "Undeclare" the default namespace on @copy with xmlns="".
*/
xsltGetSpecialNamespace(ctxt, invocNode, NULL, NULL, copy);
}
/*
* Copy attribute nodes.
*/
if (node->properties != NULL) {
xsltCopyAttrListNoOverwrite(ctxt, invocNode,
copy, node->properties);
}
if (topElemVisited == 0)
topElemVisited = 1;
}
/*
* Copy the subtree.
*/
if (node->children != NULL) {
xsltCopyTreeList(ctxt, invocNode,
node->children, copy, isLRE, topElemVisited);
}
} else {
xsltTransformError(ctxt, NULL, invocNode,
"xsltCopyTreeInternal: Copying of '%s' failed.\n", node->name);
}
return(copy);
}
| 173,324 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ThreadHeap::TakeSnapshot(SnapshotType type) {
DCHECK(thread_state_->InAtomicMarkingPause());
ThreadState::GCSnapshotInfo info(GCInfoTable::GcInfoIndex() + 1);
String thread_dump_name =
String::Format("blink_gc/thread_%lu",
static_cast<unsigned long>(thread_state_->ThreadId()));
const String heaps_dump_name = thread_dump_name + "/heaps";
const String classes_dump_name = thread_dump_name + "/classes";
int number_of_heaps_reported = 0;
#define SNAPSHOT_HEAP(ArenaType) \
{ \
number_of_heaps_reported++; \
switch (type) { \
case SnapshotType::kHeapSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeSnapshot( \
heaps_dump_name + "/" #ArenaType, info); \
break; \
case SnapshotType::kFreelistSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeFreelistSnapshot( \
heaps_dump_name + "/" #ArenaType); \
break; \
default: \
NOTREACHED(); \
} \
}
SNAPSHOT_HEAP(NormalPage1);
SNAPSHOT_HEAP(NormalPage2);
SNAPSHOT_HEAP(NormalPage3);
SNAPSHOT_HEAP(NormalPage4);
SNAPSHOT_HEAP(EagerSweep);
SNAPSHOT_HEAP(Vector1);
SNAPSHOT_HEAP(Vector2);
SNAPSHOT_HEAP(Vector3);
SNAPSHOT_HEAP(Vector4);
SNAPSHOT_HEAP(InlineVector);
SNAPSHOT_HEAP(HashTable);
SNAPSHOT_HEAP(LargeObject);
FOR_EACH_TYPED_ARENA(SNAPSHOT_HEAP);
DCHECK_EQ(number_of_heaps_reported, BlinkGC::kNumberOfArenas);
#undef SNAPSHOT_HEAP
if (type == SnapshotType::kFreelistSnapshot)
return;
size_t total_live_count = 0;
size_t total_dead_count = 0;
size_t total_live_size = 0;
size_t total_dead_size = 0;
for (size_t gc_info_index = 1; gc_info_index <= GCInfoTable::GcInfoIndex();
++gc_info_index) {
total_live_count += info.live_count[gc_info_index];
total_dead_count += info.dead_count[gc_info_index];
total_live_size += info.live_size[gc_info_index];
total_dead_size += info.dead_size[gc_info_index];
}
base::trace_event::MemoryAllocatorDump* thread_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(thread_dump_name);
thread_dump->AddScalar("live_count", "objects", total_live_count);
thread_dump->AddScalar("dead_count", "objects", total_dead_count);
thread_dump->AddScalar("live_size", "bytes", total_live_size);
thread_dump->AddScalar("dead_size", "bytes", total_dead_size);
base::trace_event::MemoryAllocatorDump* heaps_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(heaps_dump_name);
base::trace_event::MemoryAllocatorDump* classes_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(classes_dump_name);
BlinkGCMemoryDumpProvider::Instance()
->CurrentProcessMemoryDump()
->AddOwnershipEdge(classes_dump->guid(), heaps_dump->guid());
}
Commit Message: [oilpan] Fix GCInfoTable for multiple threads
Previously, grow and access from different threads could lead to a race
on the table backing; see bug.
- Rework the table to work on an existing reservation.
- Commit upon growing, avoiding any copies.
Drive-by: Fix over-allocation of table.
Bug: chromium:841280
Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43
Reviewed-on: https://chromium-review.googlesource.com/1061525
Commit-Queue: Michael Lippautz <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560434}
CWE ID: CWE-362 | void ThreadHeap::TakeSnapshot(SnapshotType type) {
DCHECK(thread_state_->InAtomicMarkingPause());
ThreadState::GCSnapshotInfo info(GCInfoTable::Get().GcInfoIndex() + 1);
String thread_dump_name =
String::Format("blink_gc/thread_%lu",
static_cast<unsigned long>(thread_state_->ThreadId()));
const String heaps_dump_name = thread_dump_name + "/heaps";
const String classes_dump_name = thread_dump_name + "/classes";
int number_of_heaps_reported = 0;
#define SNAPSHOT_HEAP(ArenaType) \
{ \
number_of_heaps_reported++; \
switch (type) { \
case SnapshotType::kHeapSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeSnapshot( \
heaps_dump_name + "/" #ArenaType, info); \
break; \
case SnapshotType::kFreelistSnapshot: \
arenas_[BlinkGC::k##ArenaType##ArenaIndex]->TakeFreelistSnapshot( \
heaps_dump_name + "/" #ArenaType); \
break; \
default: \
NOTREACHED(); \
} \
}
SNAPSHOT_HEAP(NormalPage1);
SNAPSHOT_HEAP(NormalPage2);
SNAPSHOT_HEAP(NormalPage3);
SNAPSHOT_HEAP(NormalPage4);
SNAPSHOT_HEAP(EagerSweep);
SNAPSHOT_HEAP(Vector1);
SNAPSHOT_HEAP(Vector2);
SNAPSHOT_HEAP(Vector3);
SNAPSHOT_HEAP(Vector4);
SNAPSHOT_HEAP(InlineVector);
SNAPSHOT_HEAP(HashTable);
SNAPSHOT_HEAP(LargeObject);
FOR_EACH_TYPED_ARENA(SNAPSHOT_HEAP);
DCHECK_EQ(number_of_heaps_reported, BlinkGC::kNumberOfArenas);
#undef SNAPSHOT_HEAP
if (type == SnapshotType::kFreelistSnapshot)
return;
size_t total_live_count = 0;
size_t total_dead_count = 0;
size_t total_live_size = 0;
size_t total_dead_size = 0;
for (size_t gc_info_index = 1;
gc_info_index <= GCInfoTable::Get().GcInfoIndex(); ++gc_info_index) {
total_live_count += info.live_count[gc_info_index];
total_dead_count += info.dead_count[gc_info_index];
total_live_size += info.live_size[gc_info_index];
total_dead_size += info.dead_size[gc_info_index];
}
base::trace_event::MemoryAllocatorDump* thread_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(thread_dump_name);
thread_dump->AddScalar("live_count", "objects", total_live_count);
thread_dump->AddScalar("dead_count", "objects", total_dead_count);
thread_dump->AddScalar("live_size", "bytes", total_live_size);
thread_dump->AddScalar("dead_size", "bytes", total_dead_size);
base::trace_event::MemoryAllocatorDump* heaps_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(heaps_dump_name);
base::trace_event::MemoryAllocatorDump* classes_dump =
BlinkGCMemoryDumpProvider::Instance()
->CreateMemoryAllocatorDumpForCurrentGC(classes_dump_name);
BlinkGCMemoryDumpProvider::Instance()
->CurrentProcessMemoryDump()
->AddOwnershipEdge(classes_dump->guid(), heaps_dump->guid());
}
| 173,137 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
Commit Message: Fix vulnerability in dbus proxy
During the authentication all client data is directly forwarded
to the dbus daemon as is, until we detect the BEGIN command after
which we start filtering the binary dbus protocol.
Unfortunately the detection of the BEGIN command in the proxy
did not exactly match the detection in the dbus daemon. A BEGIN
followed by a space or tab was considered ok in the daemon but
not by the proxy. This could be exploited to send arbitrary
dbus messages to the host, which can be used to break out of
the sandbox.
This was noticed by Gabriel Campana of The Google Security Team.
This fix makes the detection of the authentication phase end
match the dbus code. In addition we duplicate the authentication
line validation from dbus, which includes ensuring all data is
ASCII, and limiting the size of a line to 16k. In fact, we add
some extra stringent checks, disallowing ASCII control chars and
requiring that auth lines start with a capital letter.
CWE ID: CWE-436 | flatpak_proxy_client_finalize (GObject *object)
{
FlatpakProxyClient *client = FLATPAK_PROXY_CLIENT (object);
client->proxy->clients = g_list_remove (client->proxy->clients, client);
g_clear_object (&client->proxy);
g_byte_array_free (client->auth_buffer, TRUE);
g_hash_table_destroy (client->rewrite_reply);
g_hash_table_destroy (client->get_owner_reply);
g_hash_table_destroy (client->unique_id_policy);
free_side (&client->client_side);
free_side (&client->bus_side);
G_OBJECT_CLASS (flatpak_proxy_client_parent_class)->finalize (object);
}
| 169,341 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long ContentEncoding::ParseEncryptionEntry(
long long start,
long long size,
IMkvReader* pReader,
ContentEncryption* encryption) {
assert(pReader);
assert(encryption);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x7E1) {
encryption->algo = UnserializeUInt(pReader, pos, size);
if (encryption->algo != 5)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x7E2) {
delete[] encryption->key_id;
encryption->key_id = NULL;
encryption->key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status = pReader->Read(pos, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
encryption->key_id = buf;
encryption->key_id_len = buflen;
} else if (id == 0x7E3) {
delete[] encryption->signature;
encryption->signature = NULL;
encryption->signature_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status = pReader->Read(pos, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
encryption->signature = buf;
encryption->signature_len = buflen;
} else if (id == 0x7E4) {
delete[] encryption->sig_key_id;
encryption->sig_key_id = NULL;
encryption->sig_key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status = pReader->Read(pos, buflen, buf);
if (read_status) {
delete [] buf;
return status;
}
encryption->sig_key_id = buf;
encryption->sig_key_id_len = buflen;
} else if (id == 0x7E5) {
encryption->sig_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E6) {
encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E7) {
const long status = ParseContentEncAESSettingsEntry(
pos,
size,
pReader,
&encryption->aes_settings);
if (status)
return status;
}
pos += size; //consume payload
assert(pos <= stop);
}
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long ContentEncoding::ParseEncryptionEntry(
long ContentEncoding::ParseEncryptionEntry(long long start, long long size,
IMkvReader* pReader,
ContentEncryption* encryption) {
assert(pReader);
assert(encryption);
long long pos = start;
const long long stop = start + size;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x7E1) {
encryption->algo = UnserializeUInt(pReader, pos, size);
if (encryption->algo != 5)
return E_FILE_FORMAT_INVALID;
} else if (id == 0x7E2) {
delete[] encryption -> key_id;
encryption->key_id = NULL;
encryption->key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->key_id = buf;
encryption->key_id_len = buflen;
} else if (id == 0x7E3) {
delete[] encryption -> signature;
encryption->signature = NULL;
encryption->signature_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->signature = buf;
encryption->signature_len = buflen;
} else if (id == 0x7E4) {
delete[] encryption -> sig_key_id;
encryption->sig_key_id = NULL;
encryption->sig_key_id_len = 0;
if (size <= 0)
return E_FILE_FORMAT_INVALID;
const size_t buflen = static_cast<size_t>(size);
typedef unsigned char* buf_t;
const buf_t buf = new (std::nothrow) unsigned char[buflen];
if (buf == NULL)
return -1;
const int read_status =
pReader->Read(pos, static_cast<long>(buflen), buf);
if (read_status) {
delete[] buf;
return status;
}
encryption->sig_key_id = buf;
encryption->sig_key_id_len = buflen;
} else if (id == 0x7E5) {
encryption->sig_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E6) {
encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size);
} else if (id == 0x7E7) {
const long status = ParseContentEncAESSettingsEntry(
pos, size, pReader, &encryption->aes_settings);
if (status)
return status;
}
pos += size; // consume payload
assert(pos <= stop);
}
return 0;
}
| 174,425 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void prefetch_table(const volatile byte *tab, size_t len)
{
size_t i;
for (i = 0; i < len; i += 8 * 32)
{
(void)tab[i + 0 * 32];
(void)tab[i + 1 * 32];
(void)tab[i + 2 * 32];
(void)tab[i + 3 * 32];
(void)tab[i + 4 * 32];
(void)tab[i + 5 * 32];
(void)tab[i + 6 * 32];
(void)tab[i + 7 * 32];
}
(void)tab[len - 1];
}
Commit Message: AES: move look-up tables to .data section and unshare between processes
* cipher/rijndael-internal.h (ATTR_ALIGNED_64): New.
* cipher/rijndael-tables.h (encT): Move to 'enc_tables' structure.
(enc_tables): New structure for encryption table with counters before
and after.
(encT): New macro.
(dec_tables): Add counters before and after encryption table; Move
from .rodata to .data section.
(do_encrypt): Change 'encT' to 'enc_tables.T'.
(do_decrypt): Change '&dec_tables' to 'dec_tables.T'.
* cipher/cipher-gcm.c (prefetch_table): Make inline; Handle input
with length not multiple of 256.
(prefetch_enc, prefetch_dec): Modify pre- and post-table counters
to unshare look-up table pages between processes.
--
GnuPG-bug-id: 4541
Signed-off-by: Jussi Kivilinna <[email protected]>
CWE ID: CWE-310 | static void prefetch_table(const volatile byte *tab, size_t len)
static inline void prefetch_table(const volatile byte *tab, size_t len)
{
size_t i;
for (i = 0; len - i >= 8 * 32; i += 8 * 32)
{
(void)tab[i + 0 * 32];
(void)tab[i + 1 * 32];
(void)tab[i + 2 * 32];
(void)tab[i + 3 * 32];
(void)tab[i + 4 * 32];
(void)tab[i + 5 * 32];
(void)tab[i + 6 * 32];
(void)tab[i + 7 * 32];
}
for (; i < len; i += 32)
{
(void)tab[i];
}
(void)tab[len - 1];
}
| 170,215 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const {
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
case GL_COMMANDS_ISSUED_CHROMIUM:
case GL_LATENCY_QUERY_CHROMIUM:
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
case GL_GET_ERROR_QUERY_CHROMIUM:
return true;
default:
return false;
}
}
Commit Message: Add GL_PROGRAM_COMPLETION_QUERY_CHROMIUM
This makes the query of GL_COMPLETION_STATUS_KHR to programs much
cheaper by minimizing the round-trip to the GPU thread.
Bug: 881152, 957001
Change-Id: Iadfa798af29225e752c710ca5c25f50b3dd3101a
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1586630
Commit-Queue: Kenneth Russell <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Reviewed-by: Geoff Lang <[email protected]>
Reviewed-by: Kenneth Russell <[email protected]>
Cr-Commit-Position: refs/heads/master@{#657568}
CWE ID: CWE-416 | bool GLES2DecoderPassthroughImpl::IsEmulatedQueryTarget(GLenum target) const {
switch (target) {
case GL_COMMANDS_COMPLETED_CHROMIUM:
case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM:
case GL_COMMANDS_ISSUED_CHROMIUM:
case GL_LATENCY_QUERY_CHROMIUM:
case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM:
case GL_GET_ERROR_QUERY_CHROMIUM:
case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM:
return true;
default:
return false;
}
}
| 172,530 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CancelPendingTask() {
filter_->ResumeAttachOrDestroy(element_instance_id_,
MSG_ROUTING_NONE /* no plugin frame */);
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | CancelPendingTask() {
| 173,037 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 handle_emulation_failure(struct kvm_vcpu *vcpu)
{
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
kvm_queue_exception(vcpu, UD_VECTOR);
return EMULATE_FAIL;
}
Commit Message: KVM: X86: Don't report L2 emulation failures to user-space
This patch prevents that emulation failures which result
from emulating an instruction for an L2-Guest results in
being reported to userspace.
Without this patch a malicious L2-Guest would be able to
kill the L1 by triggering a race-condition between an vmexit
and the instruction emulator.
With this patch the L2 will most likely only kill itself in
this situation.
Signed-off-by: Joerg Roedel <[email protected]>
Signed-off-by: Marcelo Tosatti <[email protected]>
CWE ID: CWE-362 | static int handle_emulation_failure(struct kvm_vcpu *vcpu)
{
int r = EMULATE_DONE;
++vcpu->stat.insn_emulation_fail;
trace_kvm_emulate_insn_failed(vcpu);
if (!is_guest_mode(vcpu)) {
vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
vcpu->run->internal.ndata = 0;
r = EMULATE_FAIL;
}
kvm_queue_exception(vcpu, UD_VECTOR);
return r;
}
| 166,558 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
inode_init_once(&ei->vfs_inode);
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362 | static void init_once(void *foo)
{
struct ext4_inode_info *ei = (struct ext4_inode_info *) foo;
INIT_LIST_HEAD(&ei->i_orphan);
init_rwsem(&ei->xattr_sem);
init_rwsem(&ei->i_data_sem);
init_rwsem(&ei->i_mmap_sem);
inode_init_once(&ei->vfs_inode);
}
| 167,492 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret, key_tries, sign_tries, blind_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
sign_tries = 0;
do
{
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
key_tries = 0;
do
{
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_keypair( grp, &k, &R, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) );
if( key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( r, 0 ) == 0 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
blind_tries = 0;
do
{
size_t n_size = ( grp->nbits + 7 ) / 8;
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) );
/* See mbedtls_ecp_gen_keypair() */
if( ++blind_tries > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
if( sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200 | int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
static int ecdsa_sign_internal( mbedtls_ecp_group *grp, mbedtls_mpi *r,
mbedtls_mpi *s, const mbedtls_mpi *d,
const unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
int (*f_rng_blind)(void *, unsigned char *,
size_t),
void *p_rng_blind )
{
int ret, key_tries, sign_tries, blind_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
if( grp->N.p == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* Make sure d is in range 1..n-1 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_ecp_point_init( &R );
mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
sign_tries = 0;
do
{
/*
* Steps 1-3: generate a suitable ephemeral keypair
* and set r = xR mod n
*/
key_tries = 0;
do
{
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &k, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, &R, &k, &grp->G,
f_rng_blind, p_rng_blind ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) );
if( key_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( r, 0 ) == 0 );
/*
* Step 5: derive MPI from hashed message
*/
MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*
* This loop does the same job as mbedtls_ecp_gen_privkey() and it is
* replaced by a call to it in the mainline. This change is not
* necessary to backport the fix separating the blinding and ephemeral
* key generating RNGs, therefore the original code is kept.
*/
blind_tries = 0;
do
{
size_t n_size = ( grp->nbits + 7 ) / 8;
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng_blind,
p_rng_blind ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) );
if( ++blind_tries > 30 )
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
}
while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 );
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
if( sign_tries++ > 10 )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
}
while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
cleanup:
mbedtls_ecp_point_free( &R );
mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
return( ret );
}
| 170,180 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
int step=n/book->dim;
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j,o;
if (!v) return -1;
for (j=0;j<step;j++){
if(decode_map(book,b,v,point))return -1;
for(i=0,o=j;i<book->dim;i++,o+=step)
a[o]+=v[i];
}
}
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 | long vorbis_book_decodevs_add(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
int step=n/book->dim;
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j,o;
if (!v) return -1;
for (j=0;j<step;j++){
if(decode_map(book,b,v,point))return -1;
for(i=0,o=j;i<book->dim;i++,o+=step)
a[o]+=v[i];
}
}
return 0;
}
| 173,988 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TestAppInstancesHelper(const std::string& app_name) {
LOG(INFO) << "Start of test.";
extensions::ProcessMap* process_map =
extensions::ProcessMap::Get(browser()->profile());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII(app_name)));
const Extension* extension = GetSingleLoadedExtension();
GURL base_url = GetTestBaseURL(app_name);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("path1/empty.html"),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
LOG(INFO) << "Nav 1.";
EXPECT_TRUE(process_map->Contains(
browser()->tab_strip_model()->GetWebContentsAt(1)->
GetRenderProcessHost()->GetID()));
EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(1)->GetWebUI());
content::WindowedNotificationObserver tab_added_observer(
chrome::NOTIFICATION_TAB_ADDED,
content::NotificationService::AllSources());
chrome::NewTab(browser());
tab_added_observer.Wait();
LOG(INFO) << "New tab.";
ui_test_utils::NavigateToURL(browser(),
base_url.Resolve("path2/empty.html"));
LOG(INFO) << "Nav 2.";
EXPECT_TRUE(process_map->Contains(
browser()->tab_strip_model()->GetWebContentsAt(2)->
GetRenderProcessHost()->GetID()));
EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(2)->GetWebUI());
ASSERT_EQ(3, browser()->tab_strip_model()->count());
WebContents* tab1 = browser()->tab_strip_model()->GetWebContentsAt(1);
WebContents* tab2 = browser()->tab_strip_model()->GetWebContentsAt(2);
EXPECT_NE(tab1->GetRenderProcessHost(), tab2->GetRenderProcessHost());
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
OpenWindow(tab1, base_url.Resolve("path1/empty.html"), true, NULL);
LOG(INFO) << "WindowOpenHelper 1.";
OpenWindow(tab2, base_url.Resolve("path2/empty.html"), true, NULL);
LOG(INFO) << "End of test.";
UnloadExtension(extension->id());
}
Commit Message: [Extensions] Update navigations across hypothetical extension extents
Update code to treat navigations across hypothetical extension extents
(e.g. for nonexistent extensions) the same as we do for navigations
crossing installed extension extents.
Bug: 598265
Change-Id: Ibdf2f563ce1fd108ead279077901020a24de732b
Reviewed-on: https://chromium-review.googlesource.com/617180
Commit-Queue: Devlin <[email protected]>
Reviewed-by: Alex Moshchuk <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#495779}
CWE ID: | void TestAppInstancesHelper(const std::string& app_name) {
LOG(INFO) << "Start of test.";
extensions::ProcessMap* process_map =
extensions::ProcessMap::Get(browser()->profile());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII(app_name)));
const Extension* extension = GetSingleLoadedExtension();
GURL base_url = GetTestBaseURL(app_name);
ui_test_utils::NavigateToURLWithDisposition(
browser(), base_url.Resolve("path1/empty.html"),
WindowOpenDisposition::NEW_FOREGROUND_TAB,
ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
LOG(INFO) << "Nav 1.";
EXPECT_TRUE(process_map->Contains(
browser()->tab_strip_model()->GetWebContentsAt(1)->
GetRenderProcessHost()->GetID()));
EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(1)->GetWebUI());
content::WindowedNotificationObserver tab_added_observer(
chrome::NOTIFICATION_TAB_ADDED,
content::NotificationService::AllSources());
chrome::NewTab(browser());
tab_added_observer.Wait();
LOG(INFO) << "New tab.";
ui_test_utils::NavigateToURL(browser(),
base_url.Resolve("path2/empty.html"));
LOG(INFO) << "Nav 2.";
EXPECT_TRUE(process_map->Contains(
browser()->tab_strip_model()->GetWebContentsAt(2)->
GetRenderProcessHost()->GetID()));
EXPECT_FALSE(browser()->tab_strip_model()->GetWebContentsAt(2)->GetWebUI());
ASSERT_EQ(3, browser()->tab_strip_model()->count());
WebContents* tab1 = browser()->tab_strip_model()->GetWebContentsAt(1);
WebContents* tab2 = browser()->tab_strip_model()->GetWebContentsAt(2);
EXPECT_NE(tab1->GetRenderProcessHost(), tab2->GetRenderProcessHost());
ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile()));
OpenWindow(tab1, base_url.Resolve("path1/empty.html"), true, true, NULL);
LOG(INFO) << "WindowOpenHelper 1.";
OpenWindow(tab2, base_url.Resolve("path2/empty.html"), true, true, NULL);
LOG(INFO) << "End of test.";
UnloadExtension(extension->id());
}
| 172,956 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserCommandController::RemoveInterstitialObservers(
TabContents* contents) {
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
content::Source<WebContents>(contents->web_contents()));
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
content::Source<WebContents>(contents->web_contents()));
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void BrowserCommandController::RemoveInterstitialObservers(
WebContents* contents) {
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED,
content::Source<WebContents>(contents));
registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED,
content::Source<WebContents>(contents));
}
| 171,510 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch(
const ScoredHistoryMatch& history_match,
int score) {
const history::URLRow& info = history_match.url_info;
AutocompleteMatch match(this, score, !!info.visit_count(),
history_match.url_matches.empty() ?
AutocompleteMatch::HISTORY_URL : AutocompleteMatch::HISTORY_TITLE);
match.destination_url = info.url();
DCHECK(match.destination_url.is_valid());
std::vector<size_t> offsets =
OffsetsFromTermMatches(history_match.url_matches);
const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP);
match.fill_into_edit =
AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
net::FormatUrlWithOffsets(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, &offsets));
history::TermMatches new_matches =
ReplaceOffsetsInTermMatches(history_match.url_matches, offsets);
match.contents = net::FormatUrl(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, NULL);
match.contents_class =
SpansFromTermMatch(new_matches, match.contents.length(), true);
if (!history_match.can_inline) {
match.inline_autocomplete_offset = string16::npos;
} else {
DCHECK(!new_matches.empty());
match.inline_autocomplete_offset = new_matches[0].offset +
new_matches[0].length;
if (match.inline_autocomplete_offset > match.fill_into_edit.length())
match.inline_autocomplete_offset = match.fill_into_edit.length();
}
match.description = info.title();
match.description_class = SpansFromTermMatch(
history_match.title_matches, match.description.length(), false);
return match;
}
Commit Message: Fix icon returned for HQP matches; the two icons were reversed.
BUG=none
TEST=none
Review URL: https://chromiumcodereview.appspot.com/9695022
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126296 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch(
const ScoredHistoryMatch& history_match,
int score) {
const history::URLRow& info = history_match.url_info;
AutocompleteMatch match(this, score, !!info.visit_count(),
history_match.url_matches.empty() ?
AutocompleteMatch::HISTORY_TITLE : AutocompleteMatch::HISTORY_URL);
match.destination_url = info.url();
DCHECK(match.destination_url.is_valid());
std::vector<size_t> offsets =
OffsetsFromTermMatches(history_match.url_matches);
const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP);
match.fill_into_edit =
AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
net::FormatUrlWithOffsets(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, &offsets));
history::TermMatches new_matches =
ReplaceOffsetsInTermMatches(history_match.url_matches, offsets);
match.contents = net::FormatUrl(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, NULL);
match.contents_class =
SpansFromTermMatch(new_matches, match.contents.length(), true);
if (!history_match.can_inline) {
match.inline_autocomplete_offset = string16::npos;
} else {
DCHECK(!new_matches.empty());
match.inline_autocomplete_offset = new_matches[0].offset +
new_matches[0].length;
if (match.inline_autocomplete_offset > match.fill_into_edit.length())
match.inline_autocomplete_offset = match.fill_into_edit.length();
}
match.description = info.title();
match.description_class = SpansFromTermMatch(
history_match.title_matches, match.description.length(), false);
return match;
}
| 170,999 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
int name_end = -1;
int j = *idx;
int ptr_count = 0;
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
char *cp = name_out;
const char *const end = name_out + name_out_len;
/* Normally, names are a series of length prefixed strings terminated */
/* with a length of 0 (the lengths are u8's < 63). */
/* However, the length can start with a pair of 1 bits and that */
/* means that the next 14 bits are a pointer within the current */
/* packet. */
for (;;) {
u8 label_len;
if (j >= length) return -1;
GET8(label_len);
if (!label_len) break;
if (label_len & 0xc0) {
u8 ptr_low;
GET8(ptr_low);
if (name_end < 0) name_end = j;
j = (((int)label_len & 0x3f) << 8) + ptr_low;
/* Make sure that the target offset is in-bounds. */
if (j < 0 || j >= length) return -1;
/* If we've jumped more times than there are characters in the
* message, we must have a loop. */
if (++ptr_count > length) return -1;
continue;
}
if (label_len > 63) return -1;
if (cp != name_out) {
if (cp + 1 >= end) return -1;
*cp++ = '.';
}
if (cp + label_len >= end) return -1;
memcpy(cp, packet + j, label_len);
cp += label_len;
j += label_len;
}
if (cp >= end) return -1;
*cp = '\0';
if (name_end < 0)
*idx = j;
else
*idx = name_end;
return 0;
err:
return -1;
}
Commit Message: evdns: name_parse(): fix remote stack overread
@asn-the-goblin-slayer:
"the name_parse() function in libevent's DNS code is vulnerable to a buffer overread.
971 if (cp != name_out) {
972 if (cp + 1 >= end) return -1;
973 *cp++ = '.';
974 }
975 if (cp + label_len >= end) return -1;
976 memcpy(cp, packet + j, label_len);
977 cp += label_len;
978 j += label_len;
No check is made against length before the memcpy occurs.
This was found through the Tor bug bounty program and the discovery should be credited to 'Guido Vranken'."
Reproducer for gdb (https://gist.github.com/azat/e4fcf540e9b89ab86d02):
set $PROT_NONE=0x0
set $PROT_READ=0x1
set $PROT_WRITE=0x2
set $MAP_ANONYMOUS=0x20
set $MAP_SHARED=0x01
set $MAP_FIXED=0x10
set $MAP_32BIT=0x40
start
set $length=202
# overread
set $length=2
# allocate with mmap to have a seg fault on page boundary
set $l=(1<<20)*2
p mmap(0, $l, $PROT_READ|$PROT_WRITE, $MAP_ANONYMOUS|$MAP_SHARED|$MAP_32BIT, -1, 0)
set $packet=(char *)$1+$l-$length
# hack the packet
set $packet[0]=63
set $packet[1]='/'
p malloc(sizeof(int))
set $idx=(int *)$2
set $idx[0]=0
set $name_out_len=202
p malloc($name_out_len)
set $name_out=$3
# have WRITE only mapping to fail on read
set $end=$1+$l
p (void *)mmap($end, 1<<12, $PROT_NONE, $MAP_ANONYMOUS|$MAP_SHARED|$MAP_FIXED|$MAP_32BIT, -1, 0)
set $m=$4
p name_parse($packet, $length, $idx, $name_out, $name_out_len)
x/2s (char *)$name_out
Before this patch:
$ gdb -ex 'source gdb' dns-example
$1 = 1073741824
$2 = (void *) 0x633010
$3 = (void *) 0x633030
$4 = (void *) 0x40200000
Program received signal SIGSEGV, Segmentation fault.
__memcpy_sse2_unaligned () at memcpy-sse2-unaligned.S:33
After this patch:
$ gdb -ex 'source gdb' dns-example
$1 = 1073741824
$2 = (void *) 0x633010
$3 = (void *) 0x633030
$4 = (void *) 0x40200000
$5 = -1
0x633030: "/"
0x633032: ""
(gdb) p $m
$6 = (void *) 0x40200000
(gdb) p $1
$7 = 1073741824
(gdb) p/x $1
$8 = 0x40000000
(gdb) quit
P.S. plus drop one condition duplicate.
Fixes: #317
CWE ID: CWE-125 | name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
int name_end = -1;
int j = *idx;
int ptr_count = 0;
#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
char *cp = name_out;
const char *const end = name_out + name_out_len;
/* Normally, names are a series of length prefixed strings terminated */
/* with a length of 0 (the lengths are u8's < 63). */
/* However, the length can start with a pair of 1 bits and that */
/* means that the next 14 bits are a pointer within the current */
/* packet. */
for (;;) {
u8 label_len;
GET8(label_len);
if (!label_len) break;
if (label_len & 0xc0) {
u8 ptr_low;
GET8(ptr_low);
if (name_end < 0) name_end = j;
j = (((int)label_len & 0x3f) << 8) + ptr_low;
/* Make sure that the target offset is in-bounds. */
if (j < 0 || j >= length) return -1;
/* If we've jumped more times than there are characters in the
* message, we must have a loop. */
if (++ptr_count > length) return -1;
continue;
}
if (label_len > 63) return -1;
if (cp != name_out) {
if (cp + 1 >= end) return -1;
*cp++ = '.';
}
if (cp + label_len >= end) return -1;
if (j + label_len > length) return -1;
memcpy(cp, packet + j, label_len);
cp += label_len;
j += label_len;
}
if (cp >= end) return -1;
*cp = '\0';
if (name_end < 0)
*idx = j;
else
*idx = name_end;
return 0;
err:
return -1;
}
| 168,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)
{
struct keydata *keyptr = get_keyptr();
u32 hash[4];
/*
* Pick a unique starting offset for each ephemeral port search
* (saddr, daddr, dport) and 48bits of random data.
*/
hash[0] = (__force u32)saddr;
hash[1] = (__force u32)daddr;
hash[2] = (__force u32)dport ^ keyptr->secret[10];
hash[3] = keyptr->secret[11];
return half_md4_transform(hash, keyptr->secret);
}
Commit Message: net: Compute protocol sequence numbers and fragment IDs using MD5.
Computers have become a lot faster since we compromised on the
partial MD4 hash which we use currently for performance reasons.
MD5 is a much safer choice, and is inline with both RFC1948 and
other ISS generators (OpenBSD, Solaris, etc.)
Furthermore, only having 24-bits of the sequence number be truly
unpredictable is a very serious limitation. So the periodic
regeneration and 8-bit counter have been removed. We compute and
use a full 32-bit sequence number.
For ipv6, DCCP was found to use a 32-bit truncated initial sequence
number (it needs 43-bits) and that is fixed here as well.
Reported-by: Dan Kaminsky <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport)
| 165,765 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: normalize_color_encoding(color_encoding *encoding)
{
PNG_CONST double whiteY = encoding->red.Y + encoding->green.Y +
encoding->blue.Y;
if (whiteY != 1)
{
encoding->red.X /= whiteY;
encoding->red.Y /= whiteY;
encoding->red.Z /= whiteY;
encoding->green.X /= whiteY;
encoding->green.Y /= whiteY;
encoding->green.Z /= whiteY;
encoding->blue.X /= whiteY;
encoding->blue.Y /= whiteY;
encoding->blue.Z /= whiteY;
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | normalize_color_encoding(color_encoding *encoding)
{
const double whiteY = encoding->red.Y + encoding->green.Y +
encoding->blue.Y;
if (whiteY != 1)
{
encoding->red.X /= whiteY;
encoding->red.Y /= whiteY;
encoding->red.Z /= whiteY;
encoding->green.X /= whiteY;
encoding->green.Y /= whiteY;
encoding->green.Z /= whiteY;
encoding->blue.X /= whiteY;
encoding->blue.Y /= whiteY;
encoding->blue.Z /= whiteY;
}
}
| 173,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_have_neon(png_structp png_ptr)
{
FILE *f = fopen("/proc/cpuinfo", "rb");
if (f != NULL)
{
/* This is a simple state machine which reads the input byte-by-byte until
* it gets a match on the 'neon' feature or reaches the end of the stream.
*/
static const char ch_feature[] = { 70, 69, 65, 84, 85, 82, 69, 83 };
static const char ch_neon[] = { 78, 69, 79, 78 };
enum
{
StartLine, Feature, Colon, StartTag, Neon, HaveNeon, SkipTag, SkipLine
} state;
int counter;
for (state=StartLine, counter=0;;)
{
int ch = fgetc(f);
if (ch == EOF)
{
/* EOF means error or end-of-file, return false; neon at EOF is
* assumed to be a mistake.
*/
fclose(f);
return 0;
}
switch (state)
{
case StartLine:
/* Match spaces at the start of line */
if (ch <= 32) /* skip control characters and space */
break;
counter=0;
state = Feature;
/* FALL THROUGH */
case Feature:
/* Match 'FEATURE', ASCII case insensitive. */
if ((ch & ~0x20) == ch_feature[counter])
{
if (++counter == (sizeof ch_feature))
state = Colon;
break;
}
/* did not match 'feature' */
state = SkipLine;
/* FALL THROUGH */
case SkipLine:
skipLine:
/* Skip everything until we see linefeed or carriage return */
if (ch != 10 && ch != 13)
break;
state = StartLine;
break;
case Colon:
/* Match any number of space or tab followed by ':' */
if (ch == 32 || ch == 9)
break;
if (ch == 58) /* i.e. ':' */
{
state = StartTag;
break;
}
/* Either a bad line format or a 'feature' prefix followed by
* other characters.
*/
state = SkipLine;
goto skipLine;
case StartTag:
/* Skip space characters before a tag */
if (ch == 32 || ch == 9)
break;
state = Neon;
counter = 0;
/* FALL THROUGH */
case Neon:
/* Look for 'neon' tag */
if ((ch & ~0x20) == ch_neon[counter])
{
if (++counter == (sizeof ch_neon))
state = HaveNeon;
break;
}
state = SkipTag;
/* FALL THROUGH */
case SkipTag:
/* Skip non-space characters */
if (ch == 10 || ch == 13)
state = StartLine;
else if (ch == 32 || ch == 9)
state = StartTag;
break;
case HaveNeon:
/* Have seen a 'neon' prefix, but there must be a space or new
* line character to terminate it.
*/
if (ch == 10 || ch == 13 || ch == 32 || ch == 9)
{
fclose(f);
return 1;
}
state = SkipTag;
break;
default:
png_error(png_ptr, "png_have_neon: internal error (bug)");
}
}
}
else
png_warning(png_ptr, "/proc/cpuinfo open failed");
return 0;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | png_have_neon(png_structp png_ptr)
{
FILE *f = fopen("/proc/cpuinfo", "rb");
if (f != NULL)
{
/* This is a simple state machine which reads the input byte-by-byte until
* it gets a match on the 'neon' feature or reaches the end of the stream.
*/
static const char ch_feature[] = { 70, 69, 65, 84, 85, 82, 69, 83 };
static const char ch_neon[] = { 78, 69, 79, 78 };
enum
{
StartLine, Feature, Colon, StartTag, Neon, HaveNeon, SkipTag, SkipLine
} state;
int counter;
for (state=StartLine, counter=0;;)
{
int ch = fgetc(f);
if (ch == EOF)
{
/* EOF means error or end-of-file, return false; neon at EOF is
* assumed to be a mistake.
*/
fclose(f);
return 0;
}
switch (state)
{
case StartLine:
/* Match spaces at the start of line */
if (ch <= 32) /* skip control characters and space */
break;
counter=0;
state = Feature;
/* FALL THROUGH */
case Feature:
/* Match 'FEATURE', ASCII case insensitive. */
if ((ch & ~0x20) == ch_feature[counter])
{
if (++counter == (sizeof ch_feature))
state = Colon;
break;
}
/* did not match 'feature' */
state = SkipLine;
/* FALL THROUGH */
case SkipLine:
skipLine:
/* Skip everything until we see linefeed or carriage return */
if (ch != 10 && ch != 13)
break;
state = StartLine;
break;
case Colon:
/* Match any number of space or tab followed by ':' */
if (ch == 32 || ch == 9)
break;
if (ch == 58) /* i.e. ':' */
{
state = StartTag;
break;
}
/* Either a bad line format or a 'feature' prefix followed by
* other characters.
*/
state = SkipLine;
goto skipLine;
case StartTag:
/* Skip space characters before a tag */
if (ch == 32 || ch == 9)
break;
state = Neon;
counter = 0;
/* FALL THROUGH */
case Neon:
/* Look for 'neon' tag */
if ((ch & ~0x20) == ch_neon[counter])
{
if (++counter == (sizeof ch_neon))
state = HaveNeon;
break;
}
state = SkipTag;
/* FALL THROUGH */
case SkipTag:
/* Skip non-space characters */
if (ch == 10 || ch == 13)
state = StartLine;
else if (ch == 32 || ch == 9)
state = StartTag;
break;
case HaveNeon:
/* Have seen a 'neon' prefix, but there must be a space or new
* line character to terminate it.
*/
if (ch == 10 || ch == 13 || ch == 32 || ch == 9)
{
fclose(f);
return 1;
}
state = SkipTag;
break;
default:
png_error(png_ptr, "png_have_neon: internal error (bug)");
}
}
}
#ifdef PNG_WARNINGS_SUPPORTED
else
png_warning(png_ptr, "/proc/cpuinfo open failed");
#endif
return 0;
}
| 173,565 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadVICARImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
c=ReadBlobByte(image);
count=1;
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
length=0;
image->columns=0;
image->rows=0;
while (isgraph(c) && ((image->columns == 0) || (image->rows == 0)))
{
if (isalnum(c) == MagickFalse)
{
c=ReadBlobByte(image);
count++;
}
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
count++;
}
if (value_expected == MagickFalse)
continue;
p=value;
while (isalnum(c))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"Label_RECORDS") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"LBLSIZE") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"RECORD_BYTES") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NS") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"LINES") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NL") == 0)
image->rows=StringToUnsignedLong(value);
}
while (isspace((int) ((unsigned char) c)) != 0)
{
c=ReadBlobByte(image);
count++;
}
}
while (count < (ssize_t) length)
{
c=ReadBlobByte(image);
count++;
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
Read VICAR pixels.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadVICARImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
keyword[MaxTextExtent],
value[MaxTextExtent];
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
QuantumInfo
*quantum_info;
QuantumType
quantum_type;
register PixelPacket
*q;
size_t
length;
ssize_t
count,
y;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Decode image header.
*/
c=ReadBlobByte(image);
count=1;
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
length=0;
image->columns=0;
image->rows=0;
while (isgraph(c) && ((image->columns == 0) || (image->rows == 0)))
{
if (isalnum(c) == MagickFalse)
{
c=ReadBlobByte(image);
count++;
}
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
count++;
}
if (value_expected == MagickFalse)
continue;
p=value;
while (isalnum(c))
{
if ((size_t) (p-value) < (MaxTextExtent-1))
*p++=c;
c=ReadBlobByte(image);
count++;
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
if (LocaleCompare(keyword,"Label_RECORDS") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"LBLSIZE") == 0)
length=(ssize_t) StringToLong(value);
if (LocaleCompare(keyword,"RECORD_BYTES") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NS") == 0)
image->columns=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"LINES") == 0)
image->rows=StringToUnsignedLong(value);
if (LocaleCompare(keyword,"NL") == 0)
image->rows=StringToUnsignedLong(value);
}
while (isspace((int) ((unsigned char) c)) != 0)
{
c=ReadBlobByte(image);
count++;
}
}
while (count < (ssize_t) length)
{
c=ReadBlobByte(image);
count++;
}
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
image->depth=8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
/*
Read VICAR pixels.
*/
(void) SetImageColorspace(image,GRAYColorspace);
quantum_type=GrayQuantum;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
pixels=GetQuantumPixels(quantum_info);
length=GetQuantumExtent(image,quantum_info,quantum_type);
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
count=ReadBlob(image,length,pixels);
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
SetQuantumImageType(image,quantum_type);
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
| 168,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PluginServiceImpl::GetPluginInfo(int render_process_id,
int render_view_id,
ResourceContext* context,
const GURL& url,
const GURL& page_url,
const std::string& mime_type,
bool allow_wildcard,
bool* is_stale,
webkit::WebPluginInfo* info,
std::string* actual_mime_type) {
std::vector<webkit::WebPluginInfo> plugins;
std::vector<std::string> mime_types;
bool stale = GetPluginInfoArray(
url, mime_type, allow_wildcard, &plugins, &mime_types);
if (is_stale)
*is_stale = stale;
for (size_t i = 0; i < plugins.size(); ++i) {
if (!filter_ || filter_->IsPluginEnabled(render_process_id,
render_view_id,
context,
url,
page_url,
&plugins[i])) {
*info = plugins[i];
if (actual_mime_type)
*actual_mime_type = mime_types[i];
return true;
}
}
return false;
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | bool PluginServiceImpl::GetPluginInfo(int render_process_id,
int render_view_id,
ResourceContext* context,
const GURL& url,
const GURL& page_url,
const std::string& mime_type,
bool allow_wildcard,
bool* is_stale,
webkit::WebPluginInfo* info,
std::string* actual_mime_type) {
std::vector<webkit::WebPluginInfo> plugins;
std::vector<std::string> mime_types;
bool stale = GetPluginInfoArray(
url, mime_type, allow_wildcard, &plugins, &mime_types);
if (is_stale)
*is_stale = stale;
for (size_t i = 0; i < plugins.size(); ++i) {
if (!filter_ || filter_->IsPluginAvailable(render_process_id,
render_view_id,
context,
url,
page_url,
&plugins[i])) {
*info = plugins[i];
if (actual_mime_type)
*actual_mime_type = mime_types[i];
return true;
}
}
return false;
}
| 171,475 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GDataDirectoryService::InitializeRootEntry(const std::string& root_id) {
root_.reset(new GDataDirectory(NULL, this));
root_->set_title(kGDataRootDirectory);
root_->SetBaseNameFromTitle();
root_->set_resource_id(root_id);
AddEntryToResourceMap(root_.get());
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void GDataDirectoryService::InitializeRootEntry(const std::string& root_id) {
root_.reset(CreateGDataDirectory());
root_->set_title(kGDataRootDirectory);
root_->SetBaseNameFromTitle();
root_->set_resource_id(root_id);
AddEntryToResourceMap(root_.get());
}
| 171,493 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::PlatformFileError ModifyCacheState(
const FilePath& source_path,
const FilePath& dest_path,
GDataCache::FileOperationType file_operation_type,
const FilePath& symlink_path,
bool create_symlink) {
if (source_path != dest_path) {
bool success = false;
if (file_operation_type == GDataCache::FILE_OPERATION_MOVE)
success = file_util::Move(source_path, dest_path);
else if (file_operation_type == GDataCache::FILE_OPERATION_COPY)
success = file_util::CopyFile(source_path, dest_path);
if (!success) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error "
<< (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"moving " : "copying ")
<< source_path.value()
<< " to " << dest_path.value();
return error;
} else {
DVLOG(1) << (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"Moved " : "Copied ")
<< source_path.value()
<< " to " << dest_path.value();
}
} else {
DVLOG(1) << "No need to move file: source = destination";
}
if (symlink_path.empty())
return base::PLATFORM_FILE_OK;
bool deleted = util::DeleteSymlink(symlink_path);
if (deleted) {
DVLOG(1) << "Deleted symlink " << symlink_path.value();
} else {
if (errno != ENOENT)
PLOG(WARNING) << "Error deleting symlink " << symlink_path.value();
}
if (!create_symlink)
return base::PLATFORM_FILE_OK;
if (!file_util::CreateSymbolicLink(dest_path, symlink_path)) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error creating symlink " << symlink_path.value()
<< " for " << dest_path.value();
return error;
} else {
DVLOG(1) << "Created symlink " << symlink_path.value()
<< " to " << dest_path.value();
}
return base::PLATFORM_FILE_OK;
}
Commit Message: Revert 144993 - gdata: Remove invalid files in the cache directories
Broke linux_chromeos_valgrind:
http://build.chromium.org/p/chromium.memory.fyi/builders/Chromium%20OS%20%28valgrind%29%285%29/builds/8628/steps/memory%20test%3A%20unit/logs/stdio
In theory, we shouldn't have any invalid files left in the
cache directories, but things can go wrong and invalid files
may be left if the device shuts down unexpectedly, for instance.
Besides, it's good to be defensive.
BUG=134862
TEST=added unit tests
Review URL: https://chromiumcodereview.appspot.com/10693020
[email protected]
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145029 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | base::PlatformFileError ModifyCacheState(
const FilePath& source_path,
const FilePath& dest_path,
GDataCache::FileOperationType file_operation_type,
const FilePath& symlink_path,
bool create_symlink) {
if (source_path != dest_path) {
bool success = false;
if (file_operation_type == GDataCache::FILE_OPERATION_MOVE)
success = file_util::Move(source_path, dest_path);
else if (file_operation_type == GDataCache::FILE_OPERATION_COPY)
success = file_util::CopyFile(source_path, dest_path);
if (!success) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error "
<< (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"moving " : "copying ")
<< source_path.value()
<< " to " << dest_path.value();
return error;
} else {
DVLOG(1) << (file_operation_type == GDataCache::FILE_OPERATION_MOVE ?
"Moved " : "Copied ")
<< source_path.value()
<< " to " << dest_path.value();
}
} else {
DVLOG(1) << "No need to move file: source = destination";
}
if (symlink_path.empty())
return base::PLATFORM_FILE_OK;
// Cannot use file_util::Delete which uses stat64 to check if path exists
// before deleting it. If path is a symlink, stat64 dereferences it to the
// target file, so it's in essence checking if the target file exists.
// Here in this function, if |symlink_path| references |source_path| and
// |source_path| has just been moved to |dest_path| (e.g. during unpinning),
// symlink will dereference to a non-existent file. This results in stat64
// failing and file_util::Delete bailing out without deleting the symlink.
// We clearly want the symlink deleted even if it dereferences to nothing.
// Unfortunately, deleting the symlink before moving the files won't work for
// the case where move operation fails, but the symlink has already been
// deleted, which shouldn't happen. An example scenario is where an existing
// file is stored to cache and pinned for a specific resource id and md5, then
// a non-existent file is stored to cache for the same resource id and md5.
// The 2nd store-to-cache operation fails when moving files, but the symlink
// created by previous pin operation has already been deleted.
// We definitely want to keep the pinned state of the symlink if subsequent
// operations fail.
// This problem is filed at http://crbug.com/119430.
bool deleted = HANDLE_EINTR(unlink(symlink_path.value().c_str())) == 0;
if (deleted) {
DVLOG(1) << "Deleted symlink " << symlink_path.value();
} else {
if (errno != ENOENT)
PLOG(WARNING) << "Error deleting symlink " << symlink_path.value();
}
if (!create_symlink)
return base::PLATFORM_FILE_OK;
if (!file_util::CreateSymbolicLink(dest_path, symlink_path)) {
base::PlatformFileError error = SystemToPlatformError(errno);
PLOG(ERROR) << "Error creating symlink " << symlink_path.value()
<< " for " << dest_path.value();
return error;
} else {
DVLOG(1) << "Created symlink " << symlink_path.value()
<< " to " << dest_path.value();
}
return base::PLATFORM_FILE_OK;
}
| 170,863 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::SafeToDisplayAsUnicode(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;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(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(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: IDN display: Block U+0307 after i or U+0131
U+0307 (dot above) after i, j, l, or U+0131 (dotless i) would be
very hard to see if possible at all. This is not blocked
by the 'repeated diacritic' check because i is not decomposed
into dotless-i + U+0307. So, it has to be blocked separately.
Also, change the indentation in the output of
idn_test_case_generator.py .
This change blocks 80+ domains out of a million IDNs in .com TLD.
BUG=750239
TEST=components_unittests --gtest_filter=*IDN*
Change-Id: I4950aeb7aa080f92e38a2b5dea46ef4e5c25b65b
Reviewed-on: https://chromium-review.googlesource.com/607907
Reviewed-by: Peter Kasting <[email protected]>
Reviewed-by: Tom Sepez <[email protected]>
Reviewed-by: Matt Giuca <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#502987}
CWE ID: CWE-20 | bool IDNSpoofChecker::SafeToDisplayAsUnicode(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;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(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) {
// - Disallow U+0307 (dot above) after 'i', 'j', 'l' or dotless i (U+0131).
// Dotless j (U+0237) is not in the allowed set to begin with.
dangerous_pattern = new icu::RegexMatcher(
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4|)"
R"([ijl\u0131]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,955 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(SplDoublyLinkedList, offsetSet)
{
zval *zindex, *value;
spl_dllist_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) {
return;
}
intern = Z_SPLDLLIST_P(getThis());
if (Z_TYPE_P(zindex) == IS_NULL) {
/* $obj[] = ... */
spl_ptr_llist_push(intern->llist, value);
} else {
/* $obj[$foo] = ... */
zend_long index;
spl_ptr_llist_element *element;
index = spl_offset_convert_to_long(zindex);
if (index < 0 || index >= intern->llist->count) {
zval_ptr_dtor(value);
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0);
return;
}
element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);
if (element != NULL) {
/* call dtor on the old element as in spl_ptr_llist_pop */
if (intern->llist->dtor) {
intern->llist->dtor(element);
}
/* the element is replaced, delref the old one as in
* SplDoublyLinkedList::pop() */
zval_ptr_dtor(&element->data);
ZVAL_COPY_VALUE(&element->data, value);
/* new element, call ctor as in spl_ptr_llist_push */
if (intern->llist->ctor) {
intern->llist->ctor(element);
}
} else {
zval_ptr_dtor(value);
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0);
return;
}
}
} /* }}} */
/* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)
Commit Message: Fix bug #71735: Double-free in SplDoublyLinkedList::offsetSet
CWE ID: CWE-415 | SPL_METHOD(SplDoublyLinkedList, offsetSet)
{
zval *zindex, *value;
spl_dllist_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) {
return;
}
intern = Z_SPLDLLIST_P(getThis());
if (Z_TYPE_P(zindex) == IS_NULL) {
/* $obj[] = ... */
spl_ptr_llist_push(intern->llist, value);
} else {
/* $obj[$foo] = ... */
zend_long index;
spl_ptr_llist_element *element;
index = spl_offset_convert_to_long(zindex);
if (index < 0 || index >= intern->llist->count) {
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0);
return;
}
element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);
if (element != NULL) {
/* call dtor on the old element as in spl_ptr_llist_pop */
if (intern->llist->dtor) {
intern->llist->dtor(element);
}
/* the element is replaced, delref the old one as in
* SplDoublyLinkedList::pop() */
zval_ptr_dtor(&element->data);
ZVAL_COPY_VALUE(&element->data, value);
/* new element, call ctor as in spl_ptr_llist_push */
if (intern->llist->ctor) {
intern->llist->ctor(element);
}
} else {
zval_ptr_dtor(value);
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0);
return;
}
}
} /* }}} */
/* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)
| 167,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition)
{
ASSERT(m_document);
ASSERT(!hasParserBlockingScript());
{
ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script);
ASSERT(scriptLoader);
if (!scriptLoader)
return;
ASSERT(scriptLoader->isParserInserted());
if (!isExecutingScript())
Microtask::performCheckpoint();
InsertionPointRecord insertionPointRecord(m_host->inputStream());
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
scriptLoader->prepareScript(scriptStartPosition);
if (!scriptLoader->willBeParserExecuted())
return;
if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) {
requestDeferredScript(script);
} else if (scriptLoader->readyToBeParserExecuted()) {
if (m_scriptNestingLevel == 1) {
m_parserBlockingScript.setElement(script);
m_parserBlockingScript.setStartingPosition(scriptStartPosition);
} else {
ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition);
scriptLoader->executeScript(sourceCode);
}
} else {
requestParsingBlockingScript(script);
}
}
}
Commit Message: Correctly keep track of isolates for microtask execution
BUG=487155
[email protected]
Review URL: https://codereview.chromium.org/1161823002
git-svn-id: svn://svn.chromium.org/blink/trunk@195985 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-254 | void HTMLScriptRunner::runScript(Element* script, const TextPosition& scriptStartPosition)
{
ASSERT(m_document);
ASSERT(!hasParserBlockingScript());
{
ScriptLoader* scriptLoader = toScriptLoaderIfPossible(script);
ASSERT(scriptLoader);
if (!scriptLoader)
return;
ASSERT(scriptLoader->isParserInserted());
if (!isExecutingScript())
Microtask::performCheckpoint(V8PerIsolateData::mainThreadIsolate());
InsertionPointRecord insertionPointRecord(m_host->inputStream());
NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
scriptLoader->prepareScript(scriptStartPosition);
if (!scriptLoader->willBeParserExecuted())
return;
if (scriptLoader->willExecuteWhenDocumentFinishedParsing()) {
requestDeferredScript(script);
} else if (scriptLoader->readyToBeParserExecuted()) {
if (m_scriptNestingLevel == 1) {
m_parserBlockingScript.setElement(script);
m_parserBlockingScript.setStartingPosition(scriptStartPosition);
} else {
ScriptSourceCode sourceCode(script->textContent(), documentURLForScriptExecution(m_document), scriptStartPosition);
scriptLoader->executeScript(sourceCode);
}
} else {
requestParsingBlockingScript(script);
}
}
}
| 171,947 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::string16 GetRelyingPartyIdString(
AuthenticatorRequestDialogModel* dialog_model) {
static constexpr char kRpIdUrlPrefix[] = "https://";
static constexpr int kDialogWidth = 300;
const auto& rp_id = dialog_model->relying_party_id();
DCHECK(!rp_id.empty());
GURL rp_id_url(kRpIdUrlPrefix + rp_id);
auto max_static_string_length = gfx::GetStringWidthF(
l10n_util::GetStringUTF16(IDS_WEBAUTHN_GENERIC_TITLE), gfx::FontList(),
gfx::Typesetter::DEFAULT);
return url_formatter::ElideHost(rp_id_url, gfx::FontList(),
kDialogWidth - max_static_string_length);
}
Commit Message: chrome/browser/ui/webauthn: long domains may cause a line break.
As requested by UX in [1], allow long host names to split a title into
two lines. This allows us to show more of the name before eliding,
although sufficiently long names will still trigger elision.
Screenshot at
https://drive.google.com/open?id=1_V6t2CeZDAVazy3Px-OET2LnB__aEW1r.
[1] https://docs.google.com/presentation/d/1TtxkPUchyVZulqgdMcfui-68B0W-DWaFFVJEffGIbLA/edit#slide=id.g5913c4105f_1_12
Change-Id: I70f6541e0db3e9942239304de43b487a7561ca34
Bug: 870892
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1601812
Auto-Submit: Adam Langley <[email protected]>
Commit-Queue: Nina Satragno <[email protected]>
Reviewed-by: Nina Satragno <[email protected]>
Cr-Commit-Position: refs/heads/master@{#658114}
CWE ID: CWE-119 | base::string16 GetRelyingPartyIdString(
AuthenticatorRequestDialogModel* dialog_model) {
static constexpr char kRpIdUrlPrefix[] = "https://";
static constexpr int kDialogWidth = 300;
const auto& rp_id = dialog_model->relying_party_id();
DCHECK(!rp_id.empty());
GURL rp_id_url(kRpIdUrlPrefix + rp_id);
return url_formatter::ElideHost(rp_id_url, gfx::FontList(), kDialogWidth);
}
| 172,561 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tt_cmap4_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_UInt length;
FT_Byte *ends, *starts, *offsets, *deltas, *glyph_ids;
FT_UInt num_segs;
FT_Error error = FT_Err_Ok;
if ( table + 2 + 2 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 2; /* skip format */
length = TT_NEXT_USHORT( p );
if ( length < 16 )
FT_INVALID_TOO_SHORT;
/* in certain fonts, the `length' field is invalid and goes */
/* out of bound. We try to correct this here... */
if ( table + length > valid->limit )
/* in certain fonts, the `length' field is invalid and goes */
/* out of bound. We try to correct this here... */
if ( table + length > valid->limit )
{
length = (FT_UInt)( valid->limit - table );
}
p = table + 6;
num_segs = TT_NEXT_USHORT( p ); /* read segCountX2 */
if ( valid->level >= FT_VALIDATE_PARANOID )
{
/* check that we have an even value here */
if ( num_segs & 1 )
FT_INVALID_DATA;
}
num_segs /= 2;
if ( length < 16 + num_segs * 2 * 4 )
FT_INVALID_TOO_SHORT;
/* check the search parameters - even though we never use them */
/* */
if ( valid->level >= FT_VALIDATE_PARANOID )
{
/* check the values of `searchRange', `entrySelector', `rangeShift' */
FT_UInt search_range = TT_NEXT_USHORT( p );
FT_UInt entry_selector = TT_NEXT_USHORT( p );
FT_UInt range_shift = TT_NEXT_USHORT( p );
if ( ( search_range | range_shift ) & 1 ) /* must be even values */
FT_INVALID_DATA;
search_range /= 2;
range_shift /= 2;
/* `search range' is the greatest power of 2 that is <= num_segs */
if ( search_range > num_segs ||
search_range * 2 < num_segs ||
search_range + range_shift != num_segs ||
search_range != ( 1U << entry_selector ) )
FT_INVALID_DATA;
}
ends = table + 14;
starts = table + 16 + num_segs * 2;
deltas = starts + num_segs * 2;
offsets = deltas + num_segs * 2;
glyph_ids = offsets + num_segs * 2;
/* check last segment; its end count value must be 0xFFFF */
if ( valid->level >= FT_VALIDATE_PARANOID )
{
p = ends + ( num_segs - 1 ) * 2;
if ( TT_PEEK_USHORT( p ) != 0xFFFFU )
FT_INVALID_DATA;
}
{
FT_UInt start, end, offset, n;
FT_UInt last_start = 0, last_end = 0;
FT_Int delta;
FT_Byte* p_start = starts;
FT_Byte* p_end = ends;
FT_Byte* p_delta = deltas;
FT_Byte* p_offset = offsets;
for ( n = 0; n < num_segs; n++ )
{
p = p_offset;
start = TT_NEXT_USHORT( p_start );
end = TT_NEXT_USHORT( p_end );
delta = TT_NEXT_SHORT( p_delta );
offset = TT_NEXT_USHORT( p_offset );
if ( start > end )
FT_INVALID_DATA;
/* this test should be performed at default validation level; */
/* unfortunately, some popular Asian fonts have overlapping */
/* ranges in their charmaps */
/* */
if ( start <= last_end && n > 0 )
{
if ( valid->level >= FT_VALIDATE_TIGHT )
FT_INVALID_DATA;
else
{
/* allow overlapping segments, provided their start points */
/* and end points, respectively, are in ascending order */
/* */
if ( last_start > start || last_end > end )
error |= TT_CMAP_FLAG_UNSORTED;
else
error |= TT_CMAP_FLAG_OVERLAPPING;
}
}
if ( offset && offset != 0xFFFFU )
{
p += offset; /* start of glyph ID array */
/* check that we point within the glyph IDs table only */
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( p < glyph_ids ||
p + ( end - start + 1 ) * 2 > table + length )
FT_INVALID_DATA;
}
/* Some fonts handle the last segment incorrectly. In */
/* theory, 0xFFFF might point to an ordinary glyph -- */
/* a cmap 4 is versatile and could be used for any */
/* encoding, not only Unicode. However, reality shows */
/* that far too many fonts are sloppy and incorrectly */
/* set all fields but `start' and `end' for the last */
/* segment if it contains only a single character. */
/* */
/* We thus omit the test here, delaying it to the */
/* routines which actually access the cmap. */
else if ( n != num_segs - 1 ||
!( start == 0xFFFFU && end == 0xFFFFU ) )
{
if ( p < glyph_ids ||
p + ( end - start + 1 ) * 2 > valid->limit )
FT_INVALID_DATA;
}
/* check glyph indices within the segment range */
if ( valid->level >= FT_VALIDATE_TIGHT )
{
FT_UInt i, idx;
for ( i = start; i < end; i++ )
{
idx = FT_NEXT_USHORT( p );
if ( idx != 0 )
{
idx = (FT_UInt)( idx + delta ) & 0xFFFFU;
if ( idx >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
}
}
else if ( offset == 0xFFFFU )
{
/* some fonts (erroneously?) use a range offset of 0xFFFF */
/* to mean missing glyph in cmap table */
/* */
if ( valid->level >= FT_VALIDATE_PARANOID ||
n != num_segs - 1 ||
!( start == 0xFFFFU && end == 0xFFFFU ) )
FT_INVALID_DATA;
}
last_start = start;
last_end = end;
}
}
return error;
}
Commit Message:
CWE ID: CWE-119 | tt_cmap4_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_UInt length;
FT_Byte *ends, *starts, *offsets, *deltas, *glyph_ids;
FT_UInt num_segs;
FT_Error error = FT_Err_Ok;
if ( table + 2 + 2 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 2; /* skip format */
length = TT_NEXT_USHORT( p );
/* in certain fonts, the `length' field is invalid and goes */
/* out of bound. We try to correct this here... */
if ( table + length > valid->limit )
/* in certain fonts, the `length' field is invalid and goes */
/* out of bound. We try to correct this here... */
if ( table + length > valid->limit )
{
length = (FT_UInt)( valid->limit - table );
}
if ( length < 16 )
FT_INVALID_TOO_SHORT;
p = table + 6;
num_segs = TT_NEXT_USHORT( p ); /* read segCountX2 */
if ( valid->level >= FT_VALIDATE_PARANOID )
{
/* check that we have an even value here */
if ( num_segs & 1 )
FT_INVALID_DATA;
}
num_segs /= 2;
if ( length < 16 + num_segs * 2 * 4 )
FT_INVALID_TOO_SHORT;
/* check the search parameters - even though we never use them */
/* */
if ( valid->level >= FT_VALIDATE_PARANOID )
{
/* check the values of `searchRange', `entrySelector', `rangeShift' */
FT_UInt search_range = TT_NEXT_USHORT( p );
FT_UInt entry_selector = TT_NEXT_USHORT( p );
FT_UInt range_shift = TT_NEXT_USHORT( p );
if ( ( search_range | range_shift ) & 1 ) /* must be even values */
FT_INVALID_DATA;
search_range /= 2;
range_shift /= 2;
/* `search range' is the greatest power of 2 that is <= num_segs */
if ( search_range > num_segs ||
search_range * 2 < num_segs ||
search_range + range_shift != num_segs ||
search_range != ( 1U << entry_selector ) )
FT_INVALID_DATA;
}
ends = table + 14;
starts = table + 16 + num_segs * 2;
deltas = starts + num_segs * 2;
offsets = deltas + num_segs * 2;
glyph_ids = offsets + num_segs * 2;
/* check last segment; its end count value must be 0xFFFF */
if ( valid->level >= FT_VALIDATE_PARANOID )
{
p = ends + ( num_segs - 1 ) * 2;
if ( TT_PEEK_USHORT( p ) != 0xFFFFU )
FT_INVALID_DATA;
}
{
FT_UInt start, end, offset, n;
FT_UInt last_start = 0, last_end = 0;
FT_Int delta;
FT_Byte* p_start = starts;
FT_Byte* p_end = ends;
FT_Byte* p_delta = deltas;
FT_Byte* p_offset = offsets;
for ( n = 0; n < num_segs; n++ )
{
p = p_offset;
start = TT_NEXT_USHORT( p_start );
end = TT_NEXT_USHORT( p_end );
delta = TT_NEXT_SHORT( p_delta );
offset = TT_NEXT_USHORT( p_offset );
if ( start > end )
FT_INVALID_DATA;
/* this test should be performed at default validation level; */
/* unfortunately, some popular Asian fonts have overlapping */
/* ranges in their charmaps */
/* */
if ( start <= last_end && n > 0 )
{
if ( valid->level >= FT_VALIDATE_TIGHT )
FT_INVALID_DATA;
else
{
/* allow overlapping segments, provided their start points */
/* and end points, respectively, are in ascending order */
/* */
if ( last_start > start || last_end > end )
error |= TT_CMAP_FLAG_UNSORTED;
else
error |= TT_CMAP_FLAG_OVERLAPPING;
}
}
if ( offset && offset != 0xFFFFU )
{
p += offset; /* start of glyph ID array */
/* check that we point within the glyph IDs table only */
if ( valid->level >= FT_VALIDATE_TIGHT )
{
if ( p < glyph_ids ||
p + ( end - start + 1 ) * 2 > table + length )
FT_INVALID_DATA;
}
/* Some fonts handle the last segment incorrectly. In */
/* theory, 0xFFFF might point to an ordinary glyph -- */
/* a cmap 4 is versatile and could be used for any */
/* encoding, not only Unicode. However, reality shows */
/* that far too many fonts are sloppy and incorrectly */
/* set all fields but `start' and `end' for the last */
/* segment if it contains only a single character. */
/* */
/* We thus omit the test here, delaying it to the */
/* routines which actually access the cmap. */
else if ( n != num_segs - 1 ||
!( start == 0xFFFFU && end == 0xFFFFU ) )
{
if ( p < glyph_ids ||
p + ( end - start + 1 ) * 2 > valid->limit )
FT_INVALID_DATA;
}
/* check glyph indices within the segment range */
if ( valid->level >= FT_VALIDATE_TIGHT )
{
FT_UInt i, idx;
for ( i = start; i < end; i++ )
{
idx = FT_NEXT_USHORT( p );
if ( idx != 0 )
{
idx = (FT_UInt)( idx + delta ) & 0xFFFFU;
if ( idx >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
}
}
else if ( offset == 0xFFFFU )
{
/* some fonts (erroneously?) use a range offset of 0xFFFF */
/* to mean missing glyph in cmap table */
/* */
if ( valid->level >= FT_VALIDATE_PARANOID ||
n != num_segs - 1 ||
!( start == 0xFFFFU && end == 0xFFFFU ) )
FT_INVALID_DATA;
}
last_start = start;
last_end = end;
}
}
return error;
}
| 164,859 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree)
{
int i;
switch (tree->operation) {
case LDB_OP_AND:
case LDB_OP_OR:
asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1));
for (i=0; i<tree->u.list.num_elements; i++) {
if (!ldap_push_filter(data, tree->u.list.elements[i])) {
return false;
}
}
asn1_pop_tag(data);
break;
case LDB_OP_NOT:
asn1_push_tag(data, ASN1_CONTEXT(2));
if (!ldap_push_filter(data, tree->u.isnot.child)) {
return false;
}
asn1_pop_tag(data);
break;
case LDB_OP_EQUALITY:
/* equality test */
asn1_push_tag(data, ASN1_CONTEXT(3));
asn1_write_OctetString(data, tree->u.equality.attr,
strlen(tree->u.equality.attr));
asn1_write_OctetString(data, tree->u.equality.value.data,
tree->u.equality.value.length);
asn1_pop_tag(data);
break;
case LDB_OP_SUBSTRING:
/*
SubstringFilter ::= SEQUENCE {
type AttributeDescription,
-- at least one must be present
substrings SEQUENCE OF CHOICE {
initial [0] LDAPString,
any [1] LDAPString,
final [2] LDAPString } }
*/
asn1_push_tag(data, ASN1_CONTEXT(4));
asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr));
asn1_push_tag(data, ASN1_SEQUENCE(0));
if (tree->u.substring.chunks && tree->u.substring.chunks[0]) {
i = 0;
if (!tree->u.substring.start_with_wildcard) {
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0));
asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]);
asn1_pop_tag(data);
i++;
}
while (tree->u.substring.chunks[i]) {
int ctx;
if (( ! tree->u.substring.chunks[i + 1]) &&
(tree->u.substring.end_with_wildcard == 0)) {
ctx = 2;
} else {
ctx = 1;
}
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx));
asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]);
asn1_pop_tag(data);
i++;
}
}
asn1_pop_tag(data);
asn1_pop_tag(data);
break;
case LDB_OP_GREATER:
/* greaterOrEqual test */
asn1_push_tag(data, ASN1_CONTEXT(5));
asn1_write_OctetString(data, tree->u.comparison.attr,
strlen(tree->u.comparison.attr));
asn1_write_OctetString(data, tree->u.comparison.value.data,
tree->u.comparison.value.length);
asn1_pop_tag(data);
break;
case LDB_OP_LESS:
/* lessOrEqual test */
asn1_push_tag(data, ASN1_CONTEXT(6));
asn1_write_OctetString(data, tree->u.comparison.attr,
strlen(tree->u.comparison.attr));
asn1_write_OctetString(data, tree->u.comparison.value.data,
tree->u.comparison.value.length);
asn1_pop_tag(data);
break;
case LDB_OP_PRESENT:
/* present test */
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7));
asn1_write_LDAPString(data, tree->u.present.attr);
asn1_pop_tag(data);
return !data->has_error;
case LDB_OP_APPROX:
/* approx test */
asn1_push_tag(data, ASN1_CONTEXT(8));
asn1_write_OctetString(data, tree->u.comparison.attr,
strlen(tree->u.comparison.attr));
asn1_write_OctetString(data, tree->u.comparison.value.data,
tree->u.comparison.value.length);
asn1_pop_tag(data);
break;
case LDB_OP_EXTENDED:
/*
MatchingRuleAssertion ::= SEQUENCE {
matchingRule [1] MatchingRuleID OPTIONAL,
type [2] AttributeDescription OPTIONAL,
matchValue [3] AssertionValue,
dnAttributes [4] BOOLEAN DEFAULT FALSE
}
*/
asn1_push_tag(data, ASN1_CONTEXT(9));
if (tree->u.extended.rule_id) {
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1));
asn1_write_LDAPString(data, tree->u.extended.rule_id);
asn1_pop_tag(data);
}
if (tree->u.extended.attr) {
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2));
asn1_write_LDAPString(data, tree->u.extended.attr);
asn1_pop_tag(data);
}
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3));
asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value);
asn1_pop_tag(data);
asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4));
asn1_write_uint8(data, tree->u.extended.dnAttributes);
asn1_pop_tag(data);
asn1_pop_tag(data);
break;
default:
return false;
}
return !data->has_error;
}
Commit Message:
CWE ID: CWE-399 | static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree)
{
int i;
switch (tree->operation) {
case LDB_OP_AND:
case LDB_OP_OR:
if (!asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1))) return false;
for (i=0; i<tree->u.list.num_elements; i++) {
if (!ldap_push_filter(data, tree->u.list.elements[i])) {
return false;
}
}
if (!asn1_pop_tag(data)) return false;
break;
case LDB_OP_NOT:
if (!asn1_push_tag(data, ASN1_CONTEXT(2))) return false;
if (!ldap_push_filter(data, tree->u.isnot.child)) {
return false;
}
if (!asn1_pop_tag(data)) return false;
break;
case LDB_OP_EQUALITY:
/* equality test */
if (!asn1_push_tag(data, ASN1_CONTEXT(3))) return false;
if (!asn1_write_OctetString(data, tree->u.equality.attr,
strlen(tree->u.equality.attr))) return false;
if (!asn1_write_OctetString(data, tree->u.equality.value.data,
tree->u.equality.value.length)) return false;
if (!asn1_pop_tag(data)) return false;
break;
case LDB_OP_SUBSTRING:
/*
SubstringFilter ::= SEQUENCE {
type AttributeDescription,
-- at least one must be present
substrings SEQUENCE OF CHOICE {
initial [0] LDAPString,
any [1] LDAPString,
final [2] LDAPString } }
*/
if (!asn1_push_tag(data, ASN1_CONTEXT(4))) return false;
if (!asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr))) return false;
if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) return false;
if (tree->u.substring.chunks && tree->u.substring.chunks[0]) {
i = 0;
if (!tree->u.substring.start_with_wildcard) {
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) return false;
if (!asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i])) return false;
if (!asn1_pop_tag(data)) return false;
i++;
}
while (tree->u.substring.chunks[i]) {
int ctx;
if (( ! tree->u.substring.chunks[i + 1]) &&
(tree->u.substring.end_with_wildcard == 0)) {
ctx = 2;
} else {
ctx = 1;
}
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx))) return false;
if (!asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i])) return false;
if (!asn1_pop_tag(data)) return false;
i++;
}
}
if (!asn1_pop_tag(data)) return false;
if (!asn1_pop_tag(data)) return false;
break;
case LDB_OP_GREATER:
/* greaterOrEqual test */
if (!asn1_push_tag(data, ASN1_CONTEXT(5))) return false;
if (!asn1_write_OctetString(data, tree->u.comparison.attr,
strlen(tree->u.comparison.attr))) return false;
if (!asn1_write_OctetString(data, tree->u.comparison.value.data,
tree->u.comparison.value.length)) return false;
if (!asn1_pop_tag(data)) return false;
break;
case LDB_OP_LESS:
/* lessOrEqual test */
if (!asn1_push_tag(data, ASN1_CONTEXT(6))) return false;
if (!asn1_write_OctetString(data, tree->u.comparison.attr,
strlen(tree->u.comparison.attr))) return false;
if (!asn1_write_OctetString(data, tree->u.comparison.value.data,
tree->u.comparison.value.length)) return false;
if (!asn1_pop_tag(data)) return false;
break;
case LDB_OP_PRESENT:
/* present test */
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7))) return false;
if (!asn1_write_LDAPString(data, tree->u.present.attr)) return false;
if (!asn1_pop_tag(data)) return false;
return !data->has_error;
case LDB_OP_APPROX:
/* approx test */
if (!asn1_push_tag(data, ASN1_CONTEXT(8))) return false;
if (!asn1_write_OctetString(data, tree->u.comparison.attr,
strlen(tree->u.comparison.attr))) return false;
if (!asn1_write_OctetString(data, tree->u.comparison.value.data,
tree->u.comparison.value.length)) return false;
if (!asn1_pop_tag(data)) return false;
break;
case LDB_OP_EXTENDED:
/*
MatchingRuleAssertion ::= SEQUENCE {
matchingRule [1] MatchingRuleID OPTIONAL,
type [2] AttributeDescription OPTIONAL,
matchValue [3] AssertionValue,
dnAttributes [4] BOOLEAN DEFAULT FALSE
}
*/
if (!asn1_push_tag(data, ASN1_CONTEXT(9))) return false;
if (tree->u.extended.rule_id) {
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1))) return false;
if (!asn1_write_LDAPString(data, tree->u.extended.rule_id)) return false;
if (!asn1_pop_tag(data)) return false;
}
if (tree->u.extended.attr) {
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2))) return false;
if (!asn1_write_LDAPString(data, tree->u.extended.attr)) return false;
if (!asn1_pop_tag(data)) return false;
}
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3))) return false;
if (!asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value)) return false;
if (!asn1_pop_tag(data)) return false;
if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4))) return false;
if (!asn1_write_uint8(data, tree->u.extended.dnAttributes)) return false;
if (!asn1_pop_tag(data)) return false;
if (!asn1_pop_tag(data)) return false;
break;
default:
return false;
}
return !data->has_error;
}
| 164,594 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __init pcd_init(void)
{
struct pcd_unit *cd;
int unit;
if (disable)
return -EINVAL;
pcd_init_units();
if (pcd_detect())
return -ENODEV;
/* get the atapi capabilities page */
pcd_probe_capabilities();
if (register_blkdev(major, name)) {
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++)
put_disk(cd->disk);
return -EBUSY;
}
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (cd->present) {
register_cdrom(&cd->info);
cd->disk->private_data = cd;
add_disk(cd->disk);
}
}
return 0;
}
Commit Message: paride/pcd: Fix potential NULL pointer dereference and mem leak
Syzkaller report this:
pcd: pcd version 1.07, major 46, nice 0
pcd0: Autoprobe failed
pcd: No CD-ROM drive found
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 1 PID: 4525 Comm: syz-executor.0 Not tainted 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pcd_init+0x95c/0x1000 [pcd]
Code: c4 ab f7 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 56 a3 da f7 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 39 a3 da f7 49 8b bc 24 80 05 00 00 e8 cc b2
RSP: 0018:ffff8881e84df880 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc155a088 RCX: ffffffffc1508935
RDX: 0000000000040000 RSI: ffffc900014f0000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee658b8 R09: ffffed103ee658b8
R10: 0000000000000001 R11: ffffed103ee658b7 R12: 0000000000000000
R13: ffffffffc155a778 R14: ffffffffc155a4a8 R15: 0000000000000003
FS: 00007fe71bee3700(0000) GS:ffff8881f7300000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 000055a7334441a8 CR3: 00000001e9674003 CR4: 00000000007606e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1508000
? 0xffffffffc1508000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fe71bee2c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007fe71bee2c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007fe71bee36bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pcd(+) paride solos_pci atm ts_fsm rtc_mt6397 mac80211 nhc_mobility nhc_udp nhc_ipv6 nhc_hop nhc_dest nhc_fragment nhc_routing 6lowpan rtc_cros_ec memconsole intel_xhci_usb_role_switch roles rtc_wm8350 usbcore industrialio_triggered_buffer kfifo_buf industrialio asc7621 dm_era dm_persistent_data dm_bufio dm_mod tpm gnss_ubx gnss_serial serdev gnss max2165 cpufreq_dt hid_penmount hid menf21bmc_wdt rc_core n_tracesink ide_gd_mod cdns_csi2tx v4l2_fwnode videodev media pinctrl_lewisburg pinctrl_intel iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun joydev mousedev ppdev kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel aes_x86_64 crypto_simd
ide_pci_generic piix input_leds cryptd glue_helper psmouse ide_core intel_agp serio_raw intel_gtt ata_generic i2c_piix4 agpgart pata_acpi parport_pc parport floppy rtc_cmos sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: bmc150_magn]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace d873691c3cd69f56 ]---
If alloc_disk fails in pcd_init_units, cd->disk will be
NULL, however in pcd_detect and pcd_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 81b74ac68c28 ("paride/pcd: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-476 | static int __init pcd_init(void)
{
struct pcd_unit *cd;
int unit;
if (disable)
return -EINVAL;
pcd_init_units();
if (pcd_detect())
return -ENODEV;
/* get the atapi capabilities page */
pcd_probe_capabilities();
if (register_blkdev(major, name)) {
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (!cd->disk)
continue;
blk_cleanup_queue(cd->disk->queue);
blk_mq_free_tag_set(&cd->tag_set);
put_disk(cd->disk);
}
return -EBUSY;
}
for (unit = 0, cd = pcd; unit < PCD_UNITS; unit++, cd++) {
if (cd->present) {
register_cdrom(&cd->info);
cd->disk->private_data = cd;
add_disk(cd->disk);
}
}
return 0;
}
| 169,519 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rawv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name;
struct sk_buff *skb;
size_t copied;
int err;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
if (addr_len)
*addr_len=sizeof(*sin6);
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
if (skb_csum_unnecessary(skb)) {
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
} else if (msg->msg_flags&MSG_TRUNC) {
if (__skb_checksum_complete(skb))
goto csum_copy_err;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
} else {
err = skb_copy_and_csum_datagram_iovec(skb, 0, msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (err)
goto out_free;
/* Copy the address. */
if (sin6) {
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_flowinfo = 0;
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
}
sock_recv_ts_and_drops(msg, sk, skb);
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = skb->len;
out_free:
skb_free_datagram(sk, skb);
out:
return err;
csum_copy_err:
skb_kill_datagram(sk, skb, flags);
/* Error for blocking case is chosen to masquerade
as some normal condition.
*/
err = (flags&MSG_DONTWAIT) ? -EAGAIN : -EHOSTUNREACH;
goto out;
}
Commit Message: inet: prevent leakage of uninitialized memory to user in recv syscalls
Only update *addr_len when we actually fill in sockaddr, otherwise we
can return uninitialized memory from the stack to the caller in the
recvfrom, recvmmsg and recvmsg syscalls. Drop the the (addr_len == NULL)
checks because we only get called with a valid addr_len pointer either
from sock_common_recvmsg or inet_recvmsg.
If a blocking read waits on a socket which is concurrently shut down we
now return zero and set msg_msgnamelen to 0.
Reported-by: mpb <[email protected]>
Suggested-by: Eric Dumazet <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | static int rawv6_recvmsg(struct kiocb *iocb, struct sock *sk,
struct msghdr *msg, size_t len,
int noblock, int flags, int *addr_len)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)msg->msg_name;
struct sk_buff *skb;
size_t copied;
int err;
if (flags & MSG_OOB)
return -EOPNOTSUPP;
if (flags & MSG_ERRQUEUE)
return ipv6_recv_error(sk, msg, len);
if (np->rxpmtu && np->rxopt.bits.rxpmtu)
return ipv6_recv_rxpmtu(sk, msg, len);
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
if (skb_csum_unnecessary(skb)) {
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
} else if (msg->msg_flags&MSG_TRUNC) {
if (__skb_checksum_complete(skb))
goto csum_copy_err;
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
} else {
err = skb_copy_and_csum_datagram_iovec(skb, 0, msg->msg_iov);
if (err == -EINVAL)
goto csum_copy_err;
}
if (err)
goto out_free;
/* Copy the address. */
if (sin6) {
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ipv6_hdr(skb)->saddr;
sin6->sin6_flowinfo = 0;
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
*addr_len = sizeof(*sin6);
}
sock_recv_ts_and_drops(msg, sk, skb);
if (np->rxopt.all)
ip6_datagram_recv_ctl(sk, msg, skb);
err = copied;
if (flags & MSG_TRUNC)
err = skb->len;
out_free:
skb_free_datagram(sk, skb);
out:
return err;
csum_copy_err:
skb_kill_datagram(sk, skb, flags);
/* Error for blocking case is chosen to masquerade
as some normal condition.
*/
err = (flags&MSG_DONTWAIT) ? -EAGAIN : -EHOSTUNREACH;
goto out;
}
| 166,480 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_unregister_sysfs(sb);
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
ext4_xattr_put_super(sb);
if (!(sb->s_flags & MS_RDONLY)) {
ext4_clear_feature_journal_needs_recovery(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | static void ext4_put_super(struct super_block *sb)
{
struct ext4_sb_info *sbi = EXT4_SB(sb);
struct ext4_super_block *es = sbi->s_es;
int i, err;
ext4_unregister_li_request(sb);
dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED);
flush_workqueue(sbi->rsv_conversion_wq);
destroy_workqueue(sbi->rsv_conversion_wq);
if (sbi->s_journal) {
err = jbd2_journal_destroy(sbi->s_journal);
sbi->s_journal = NULL;
if (err < 0)
ext4_abort(sb, "Couldn't clean up the journal");
}
ext4_unregister_sysfs(sb);
ext4_es_unregister_shrinker(sbi);
del_timer_sync(&sbi->s_err_report);
ext4_release_system_zone(sb);
ext4_mb_release(sb);
ext4_ext_release(sb);
if (!(sb->s_flags & MS_RDONLY)) {
ext4_clear_feature_journal_needs_recovery(sb);
es->s_state = cpu_to_le16(sbi->s_mount_state);
}
if (!(sb->s_flags & MS_RDONLY))
ext4_commit_super(sb, 1);
for (i = 0; i < sbi->s_gdb_count; i++)
brelse(sbi->s_group_desc[i]);
kvfree(sbi->s_group_desc);
kvfree(sbi->s_flex_groups);
percpu_counter_destroy(&sbi->s_freeclusters_counter);
percpu_counter_destroy(&sbi->s_freeinodes_counter);
percpu_counter_destroy(&sbi->s_dirs_counter);
percpu_counter_destroy(&sbi->s_dirtyclusters_counter);
brelse(sbi->s_sbh);
#ifdef CONFIG_QUOTA
for (i = 0; i < EXT4_MAXQUOTAS; i++)
kfree(sbi->s_qf_names[i]);
#endif
/* Debugging code just in case the in-memory inode orphan list
* isn't empty. The on-disk one can be non-empty if we've
* detected an error and taken the fs readonly, but the
* in-memory list had better be clean by this point. */
if (!list_empty(&sbi->s_orphan))
dump_orphan_list(sb, sbi);
J_ASSERT(list_empty(&sbi->s_orphan));
sync_blockdev(sb->s_bdev);
invalidate_bdev(sb->s_bdev);
if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) {
/*
* Invalidate the journal device's buffers. We don't want them
* floating about in memory - the physical journal device may
* hotswapped, and it breaks the `ro-after' testing code.
*/
sync_blockdev(sbi->journal_bdev);
invalidate_bdev(sbi->journal_bdev);
ext4_blkdev_remove(sbi);
}
if (sbi->s_mb_cache) {
ext4_xattr_destroy_cache(sbi->s_mb_cache);
sbi->s_mb_cache = NULL;
}
if (sbi->s_mmp_tsk)
kthread_stop(sbi->s_mmp_tsk);
sb->s_fs_info = NULL;
/*
* Now that we are completely done shutting down the
* superblock, we need to actually destroy the kobject.
*/
kobject_put(&sbi->s_kobj);
wait_for_completion(&sbi->s_kobj_unregister);
if (sbi->s_chksum_driver)
crypto_free_shash(sbi->s_chksum_driver);
kfree(sbi->s_blockgroup_lock);
kfree(sbi);
}
| 169,987 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) |
(buffer[1] << 8 ) | (buffer[0]));
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) |
(buffer[2] << 8) | buffer[3]);
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed int ReadPropertySignedLong(const EndianType endian,
const unsigned char *buffer)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
unsigned int
value;
if (endian == LSBEndian)
{
value=(unsigned int) buffer[3] << 24;
value|=(unsigned int) buffer[2] << 16;
value|=(unsigned int) buffer[1] << 8;
value|=(unsigned int) buffer[0];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,954 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: scoped_refptr<BrowserContext> BrowserContextImpl::GetOffTheRecordContext() {
if (!otr_context_) {
OTRBrowserContextImpl* context = new OTRBrowserContextImpl(
this,
static_cast<BrowserContextIODataImpl *>(io_data()));
otr_context_ = context->GetWeakPtr();
}
return make_scoped_refptr(otr_context_.get());
}
Commit Message:
CWE ID: CWE-20 | scoped_refptr<BrowserContext> BrowserContextImpl::GetOffTheRecordContext() {
BrowserContext* BrowserContextImpl::GetOffTheRecordContext() {
if (!otr_context_) {
otr_context_ =
base::MakeUnique<OTRBrowserContextImpl>(
this,
static_cast<BrowserContextIODataImpl*>(io_data()));
}
return otr_context_.get();
}
BrowserContextImpl::~BrowserContextImpl() {
CHECK(!otr_context_);
}
| 165,413 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg)
{
unsigned char *buffer;
unsigned int *dest;
int x, y;
ImageStream *imgStr;
Guchar *pix;
int i;
double *ctm;
QMatrix matrix;
int is_identity_transform;
buffer = (unsigned char *)gmalloc (width * height * 4);
/* TODO: Do we want to cache these? */
imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgStr->reset();
/* ICCBased color space doesn't do any color correction
* so check its underlying color space as well */
is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB ||
(colorMap->getColorSpace()->getMode() == csICCBased &&
((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB);
if (maskColors) {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
for (x = 0; x < width; x++) {
for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
if (pix[i] < maskColors[2*i] * 255||
pix[i] > maskColors[2*i+1] * 255) {
*dest = *dest | 0xff000000;
break;
}
}
pix += colorMap->getNumPixelComps();
dest++;
}
}
m_image = new QImage(buffer, width, height, QImage::Format_ARGB32);
}
else {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
}
m_image = new QImage(buffer, width, height, QImage::Format_RGB32);
}
if (m_image == NULL || m_image->isNull()) {
qDebug() << "Null image";
delete imgStr;
return;
}
ctm = state->getCTM();
matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]);
m_painter->setMatrix(matrix, true);
m_painter->drawImage( QPoint(0,0), *m_image );
delete m_image;
m_image = 0;
free (buffer);
delete imgStr;
}
Commit Message:
CWE ID: CWE-189 | void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg)
{
unsigned char *buffer;
unsigned int *dest;
int x, y;
ImageStream *imgStr;
Guchar *pix;
int i;
double *ctm;
QMatrix matrix;
int is_identity_transform;
buffer = (unsigned char *)gmallocn3(width, height, 4);
/* TODO: Do we want to cache these? */
imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgStr->reset();
/* ICCBased color space doesn't do any color correction
* so check its underlying color space as well */
is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB ||
(colorMap->getColorSpace()->getMode() == csICCBased &&
((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB);
if (maskColors) {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
for (x = 0; x < width; x++) {
for (i = 0; i < colorMap->getNumPixelComps(); ++i) {
if (pix[i] < maskColors[2*i] * 255||
pix[i] > maskColors[2*i+1] * 255) {
*dest = *dest | 0xff000000;
break;
}
}
pix += colorMap->getNumPixelComps();
dest++;
}
}
m_image = new QImage(buffer, width, height, QImage::Format_ARGB32);
}
else {
for (y = 0; y < height; y++) {
dest = (unsigned int *) (buffer + y * 4 * width);
pix = imgStr->getLine();
colorMap->getRGBLine (pix, dest, width);
}
m_image = new QImage(buffer, width, height, QImage::Format_RGB32);
}
if (m_image == NULL || m_image->isNull()) {
qDebug() << "Null image";
delete imgStr;
return;
}
ctm = state->getCTM();
matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]);
m_painter->setMatrix(matrix, true);
m_painter->drawImage( QPoint(0,0), *m_image );
delete m_image;
m_image = 0;
free (buffer);
delete imgStr;
}
| 164,603 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RuntimeCustomBindings::RuntimeCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetManifest",
base::Bind(&RuntimeCustomBindings::GetManifest, base::Unretained(this)));
RouteFunction("OpenChannelToExtension",
base::Bind(&RuntimeCustomBindings::OpenChannelToExtension,
base::Unretained(this)));
RouteFunction("OpenChannelToNativeApp",
base::Bind(&RuntimeCustomBindings::OpenChannelToNativeApp,
base::Unretained(this)));
RouteFunction("GetExtensionViews",
base::Bind(&RuntimeCustomBindings::GetExtensionViews,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | RuntimeCustomBindings::RuntimeCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetManifest",
base::Bind(&RuntimeCustomBindings::GetManifest, base::Unretained(this)));
RouteFunction("OpenChannelToExtension", "runtime.connect",
base::Bind(&RuntimeCustomBindings::OpenChannelToExtension,
base::Unretained(this)));
RouteFunction("OpenChannelToNativeApp", "runtime.connectNative",
base::Bind(&RuntimeCustomBindings::OpenChannelToNativeApp,
base::Unretained(this)));
RouteFunction("GetExtensionViews",
base::Bind(&RuntimeCustomBindings::GetExtensionViews,
base::Unretained(this)));
}
| 172,253 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserViewRenderer::SetTotalRootLayerScrollOffset(
gfx::Vector2dF scroll_offset_dip) {
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2d scroll_offset;
if (max_scroll_offset_dip_.x()) {
scroll_offset.set_x((scroll_offset_dip.x() * max_offset.x()) /
max_scroll_offset_dip_.x());
}
if (max_scroll_offset_dip_.y()) {
scroll_offset.set_y((scroll_offset_dip.y() * max_offset.y()) /
max_scroll_offset_dip_.y());
}
DCHECK_LE(0, scroll_offset.x());
DCHECK_LE(0, scroll_offset.y());
DCHECK_LE(scroll_offset.x(), max_offset.x());
DCHECK_LE(scroll_offset.y(), max_offset.y());
client_->ScrollContainerViewTo(scroll_offset);
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | void BrowserViewRenderer::SetTotalRootLayerScrollOffset(
const gfx::Vector2dF& scroll_offset_dip) {
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2d scroll_offset;
if (max_scroll_offset_dip_.x()) {
scroll_offset.set_x((scroll_offset_dip.x() * max_offset.x()) /
max_scroll_offset_dip_.x());
}
if (max_scroll_offset_dip_.y()) {
scroll_offset.set_y((scroll_offset_dip.y() * max_offset.y()) /
max_scroll_offset_dip_.y());
}
DCHECK_LE(0, scroll_offset.x());
DCHECK_LE(0, scroll_offset.y());
DCHECK_LE(scroll_offset.x(), max_offset.x());
DCHECK_LE(scroll_offset.y(), max_offset.y());
client_->ScrollContainerViewTo(scroll_offset);
}
| 171,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ParseCommon(map_string_t *settings, const char *conf_filename)
{
const char *value;
value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir");
if (value)
{
g_settings_sWatchCrashdumpArchiveDir = xstrdup(value);
remove_map_string_item(settings, "WatchCrashdumpArchiveDir");
}
value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize");
if (value)
{
char *end;
errno = 0;
unsigned long ul = strtoul(value, &end, 10);
if (errno || end == value || *end != '\0' || ul > INT_MAX)
error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value);
else
g_settings_nMaxCrashReportsSize = ul;
remove_map_string_item(settings, "MaxCrashReportsSize");
}
value = get_map_string_item_or_NULL(settings, "DumpLocation");
if (value)
{
g_settings_dump_location = xstrdup(value);
remove_map_string_item(settings, "DumpLocation");
}
else
g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION);
value = get_map_string_item_or_NULL(settings, "DeleteUploaded");
if (value)
{
g_settings_delete_uploaded = string_to_bool(value);
remove_map_string_item(settings, "DeleteUploaded");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled");
if (value)
{
g_settings_autoreporting = string_to_bool(value);
remove_map_string_item(settings, "AutoreportingEnabled");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEvent");
if (value)
{
g_settings_autoreporting_event = xstrdup(value);
remove_map_string_item(settings, "AutoreportingEvent");
}
else
g_settings_autoreporting_event = xstrdup("report_uReport");
value = get_map_string_item_or_NULL(settings, "ShortenedReporting");
if (value)
{
g_settings_shortenedreporting = string_to_bool(value);
remove_map_string_item(settings, "ShortenedReporting");
}
else
g_settings_shortenedreporting = 0;
GHashTableIter iter;
const char *name;
/*char *value; - already declared */
init_map_string_iter(&iter, settings);
while (next_map_string_iter(&iter, &name, &value))
{
error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename);
}
}
Commit Message: make the dump directories owned by root by default
It was discovered that the abrt event scripts create a user-readable
copy of a sosreport file in abrt problem directories, and include
excerpts of /var/log/messages selected by the user-controlled process
name, leading to an information disclosure.
This issue was discovered by Florian Weimer of Red Hat Product Security.
Related: #1212868
Signed-off-by: Jakub Filak <[email protected]>
CWE ID: CWE-200 | static void ParseCommon(map_string_t *settings, const char *conf_filename)
{
const char *value;
value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir");
if (value)
{
g_settings_sWatchCrashdumpArchiveDir = xstrdup(value);
remove_map_string_item(settings, "WatchCrashdumpArchiveDir");
}
value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize");
if (value)
{
char *end;
errno = 0;
unsigned long ul = strtoul(value, &end, 10);
if (errno || end == value || *end != '\0' || ul > INT_MAX)
error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value);
else
g_settings_nMaxCrashReportsSize = ul;
remove_map_string_item(settings, "MaxCrashReportsSize");
}
value = get_map_string_item_or_NULL(settings, "DumpLocation");
if (value)
{
g_settings_dump_location = xstrdup(value);
remove_map_string_item(settings, "DumpLocation");
}
else
g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION);
value = get_map_string_item_or_NULL(settings, "DeleteUploaded");
if (value)
{
g_settings_delete_uploaded = string_to_bool(value);
remove_map_string_item(settings, "DeleteUploaded");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled");
if (value)
{
g_settings_autoreporting = string_to_bool(value);
remove_map_string_item(settings, "AutoreportingEnabled");
}
value = get_map_string_item_or_NULL(settings, "AutoreportingEvent");
if (value)
{
g_settings_autoreporting_event = xstrdup(value);
remove_map_string_item(settings, "AutoreportingEvent");
}
else
g_settings_autoreporting_event = xstrdup("report_uReport");
value = get_map_string_item_or_NULL(settings, "ShortenedReporting");
if (value)
{
g_settings_shortenedreporting = string_to_bool(value);
remove_map_string_item(settings, "ShortenedReporting");
}
else
g_settings_shortenedreporting = 0;
value = get_map_string_item_or_NULL(settings, "PrivateReports");
if (value)
{
g_settings_privatereports = string_to_bool(value);
remove_map_string_item(settings, "PrivateReports");
}
GHashTableIter iter;
const char *name;
/*char *value; - already declared */
init_map_string_iter(&iter, settings);
while (next_map_string_iter(&iter, &name, &value))
{
error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename);
}
}
| 170,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: static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator);
object->u.dir.index++;
do {
spl_filesystem_dir_read(object TSRMLS_CC);
} while (spl_filesystem_is_dot(object->u.dir.entry.d_name));
if (object->file_name) {
efree(object->file_name);
object->file_name = NULL;
}
if (iterator->current) {
zval_ptr_dtor(&iterator->current);
iterator->current = NULL;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC)
{
spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter;
spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator);
object->u.dir.index++;
do {
spl_filesystem_dir_read(object TSRMLS_CC);
} while (spl_filesystem_is_dot(object->u.dir.entry.d_name));
if (object->file_name) {
efree(object->file_name);
object->file_name = NULL;
}
if (iterator->current) {
zval_ptr_dtor(&iterator->current);
iterator->current = NULL;
}
}
| 167,087 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_METHOD(Phar, offsetExists)
{
char *fname;
size_t fname_len;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &fname, &fname_len) == FAILURE) {
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_FALSE;
}
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
/* none of these are real files, so they don't exist */
RETURN_FALSE;
}
RETURN_TRUE;
} else {
if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
}
Commit Message:
CWE ID: CWE-20 | PHP_METHOD(Phar, offsetExists)
{
char *fname;
size_t fname_len;
phar_entry_info *entry;
PHAR_ARCHIVE_OBJECT();
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &fname, &fname_len) == FAILURE) {
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_FALSE;
}
}
if (fname_len >= sizeof(".phar")-1 && !memcmp(fname, ".phar", sizeof(".phar")-1)) {
/* none of these are real files, so they don't exist */
RETURN_FALSE;
}
RETURN_TRUE;
} else {
if (zend_hash_str_exists(&phar_obj->archive->virtual_dirs, fname, (uint) fname_len)) {
RETURN_TRUE;
}
RETURN_FALSE;
}
}
| 165,065 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FolderHeaderView::Update() {
if (!folder_item_)
return;
folder_name_view_->SetVisible(folder_name_visible_);
if (folder_name_visible_)
folder_name_view_->SetText(base::UTF8ToUTF16(folder_item_->name()));
Layout();
}
Commit Message: Enforce the maximum length of the folder name in UI.
BUG=355797
[email protected]
Review URL: https://codereview.chromium.org/203863005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260156 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void FolderHeaderView::Update() {
if (!folder_item_)
return;
folder_name_view_->SetVisible(folder_name_visible_);
if (folder_name_visible_) {
folder_name_view_->SetText(base::UTF8ToUTF16(folder_item_->name()));
folder_name_view_->Update();
}
Layout();
}
| 171,202 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: file_continue(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
es_ptr pscratch = esp - 2;
file_enum *pfen = r_ptr(esp - 1, file_enum);
int devlen = esp[-3].value.intval;
gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);
uint len = r_size(pscratch);
uint code;
if (len < devlen)
return_error(gs_error_rangecheck); /* not even room for device len */
do {
memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);
code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,
len - devlen);
if (code == ~(uint) 0) { /* all done */
esp -= 5; /* pop proc, pfen, devlen, iodev , mark */
return o_pop_estack;
} else if (code > len) /* overran string */
return_error(gs_error_rangecheck);
else if (iodev != iodev_default(imemory)
|| (check_file_permissions_reduced(i_ctx_p, (char *)pscratch->value.bytes, code + devlen, iodev, "PermitFileReading")) == 0) {
push(1);
ref_assign(op, pscratch);
r_set_size(op, code + devlen);
push_op_estack(file_continue); /* come again */
*++esp = pscratch[2]; /* proc */
return o_push_estack;
}
} while(1);
}
Commit Message:
CWE ID: CWE-200 | file_continue(i_ctx_t *i_ctx_p)
{
os_ptr op = osp;
es_ptr pscratch = esp - 2;
file_enum *pfen = r_ptr(esp - 1, file_enum);
int devlen = esp[-3].value.intval;
gx_io_device *iodev = r_ptr(esp - 4, gx_io_device);
uint len = r_size(pscratch);
uint code;
if (len < devlen)
return_error(gs_error_rangecheck); /* not even room for device len */
do {
memcpy((char *)pscratch->value.bytes, iodev->dname, devlen);
code = iodev->procs.enumerate_next(pfen, (char *)pscratch->value.bytes + devlen,
len - devlen);
if (code == ~(uint) 0) { /* all done */
esp -= 5; /* pop proc, pfen, devlen, iodev , mark */
return o_pop_estack;
} else if (code > len) /* overran string */
return_error(gs_error_rangecheck);
else if (iodev != iodev_default(imemory)
|| (check_file_permissions(i_ctx_p, (char *)pscratch->value.bytes, code + devlen, iodev, "PermitFileReading")) == 0) {
push(1);
ref_assign(op, pscratch);
r_set_size(op, code + devlen);
push_op_estack(file_continue); /* come again */
*++esp = pscratch[2]; /* proc */
return o_push_estack;
}
} while(1);
}
| 165,389 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ClipboardMessageFilter::OnWriteObjectsAsync(
const ui::Clipboard::ObjectMap& objects) {
scoped_ptr<ui::Clipboard::ObjectMap> sanitized_objects(
new ui::Clipboard::ObjectMap(objects));
sanitized_objects->erase(ui::Clipboard::CBF_SMBITMAP);
#if defined(OS_WIN)
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(
&WriteObjectsOnUIThread, base::Owned(sanitized_objects.release())));
#else
GetClipboard()->WriteObjects(
ui::CLIPBOARD_TYPE_COPY_PASTE, *sanitized_objects.get());
#endif
}
Commit Message: Refactor ui::Clipboard::ObjectMap sanitization in ClipboardMsgFilter.
BUG=352395
[email protected]
[email protected]
Review URL: https://codereview.chromium.org/200523004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@257164 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ClipboardMessageFilter::OnWriteObjectsAsync(
const ui::Clipboard::ObjectMap& objects) {
scoped_ptr<ui::Clipboard::ObjectMap> sanitized_objects(
new ui::Clipboard::ObjectMap(objects));
SanitizeObjectMap(sanitized_objects.get(), kFilterBitmap);
#if defined(OS_WIN)
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(
&WriteObjectsOnUIThread, base::Owned(sanitized_objects.release())));
#else
GetClipboard()->WriteObjects(
ui::CLIPBOARD_TYPE_COPY_PASTE, *sanitized_objects.get());
#endif
}
| 171,691 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_wrap_aead(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
gss_buffer_t input_assoc_buffer,
gss_buffer_t input_payload_buffer,
int *conf_state,
gss_buffer_t output_message_buffer)
{
OM_uint32 ret;
ret = gss_wrap_aead(minor_status,
context_handle,
conf_req_flag,
qop_req,
input_assoc_buffer,
input_payload_buffer,
conf_state,
output_message_buffer);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_wrap_aead(OM_uint32 *minor_status,
gss_ctx_id_t context_handle,
int conf_req_flag,
gss_qop_t qop_req,
gss_buffer_t input_assoc_buffer,
gss_buffer_t input_payload_buffer,
int *conf_state,
gss_buffer_t output_message_buffer)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
ret = gss_wrap_aead(minor_status,
sc->ctx_handle,
conf_req_flag,
qop_req,
input_assoc_buffer,
input_payload_buffer,
conf_state,
output_message_buffer);
return (ret);
}
| 166,672 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 VP8XChunk::height(XMP_Uns32 val)
{
PutLE24(&this->data[7], val - 1);
}
Commit Message:
CWE ID: CWE-20 | void VP8XChunk::height(XMP_Uns32 val)
{
PutLE24(&this->data[7], val > 0 ? val - 1 : 0);
}
| 165,365 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 php_handler(request_rec *r)
{
php_struct * volatile ctx;
void *conf;
apr_bucket_brigade * volatile brigade;
apr_bucket *bucket;
apr_status_t rv;
request_rec * volatile parent_req = NULL;
TSRMLS_FETCH();
#define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC);
conf = ap_get_module_config(r->per_dir_config, &php5_module);
/* apply_config() needs r in some cases, so allocate server_context early */
ctx = SG(server_context);
if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
normal:
ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
/* register a cleanup so we clear out the SG(server_context)
* after each request. Note: We pass in the pointer to the
* server_context in case this is handled by a different thread.
*/
apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
ctx->r = r;
ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
} else {
parent_req = ctx->r;
ctx->r = r;
}
apply_config(conf);
if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
/* Check for xbithack in this case. */
if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
PHPAP_INI_OFF;
return DECLINED;
}
}
/* Give a 404 if PATH_INFO is used but is explicitly disabled in
* the configuration; default behaviour is to accept. */
if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
&& r->path_info && r->path_info[0]) {
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
/* handle situations where user turns the engine off */
if (!AP2(engine)) {
PHPAP_INI_OFF;
return DECLINED;
}
if (r->finfo.filetype == 0) {
php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
if (r->finfo.filetype == APR_DIR) {
php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_FORBIDDEN;
}
/* Setup the CGI variables if this is the main request */
if (r->main == NULL ||
/* .. or if the sub-request environment differs from the main-request. */
r->subprocess_env != r->main->subprocess_env
) {
/* setup standard CGI variables */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
}
zend_first_try {
if (ctx == NULL) {
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
ctx = SG(server_context);
ctx->brigade = brigade;
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
} else {
if (!parent_req) {
parent_req = ctx->r;
}
if (parent_req && parent_req->handler &&
strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SCRIPT)) {
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
}
/*
* check if coming due to ErrorDocument
* We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
* during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting
* PHP instance to handle the request rather then creating a new one.
*/
if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
parent_req = NULL;
goto normal;
}
ctx->r = r;
brigade = ctx->brigade;
}
if (AP2(last_modified)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
/* Determine if we need to parse the file or show the source */
if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
zend_syntax_highlighter_ini syntax_highlighter_ini;
php_get_highlight_struct(&syntax_highlighter_ini);
highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC);
} else {
zend_file_handle zfd;
zfd.type = ZEND_HANDLE_FILENAME;
zfd.filename = (char *) r->filename;
zfd.free_filename = 0;
zfd.opened_path = NULL;
if (!parent_req) {
php_execute_script(&zfd TSRMLS_CC);
} else {
zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd);
}
apr_table_set(r->notes, "mod_php_memory_usage",
apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC)));
}
} zend_end_try();
if (!parent_req) {
php_apache_request_dtor(r TSRMLS_CC);
ctx->request_processed = 1;
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
rv = ap_pass_brigade(r->output_filters, brigade);
if (rv != APR_SUCCESS || r->connection->aborted) {
zend_first_try {
php_handle_aborted_connection();
} zend_end_try();
}
apr_brigade_cleanup(brigade);
apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
} else {
ctx->r = parent_req;
}
return OK;
}
Commit Message: Fix for bug #76582
The brigade seems to end up in a messed up state if something fails
in shutdown, so we clean it up.
CWE ID: CWE-79 | static int php_handler(request_rec *r)
{
php_struct * volatile ctx;
void *conf;
apr_bucket_brigade * volatile brigade;
apr_bucket *bucket;
apr_status_t rv;
request_rec * volatile parent_req = NULL;
TSRMLS_FETCH();
#define PHPAP_INI_OFF php_apache_ini_dtor(r, parent_req TSRMLS_CC);
conf = ap_get_module_config(r->per_dir_config, &php5_module);
/* apply_config() needs r in some cases, so allocate server_context early */
ctx = SG(server_context);
if (ctx == NULL || (ctx && ctx->request_processed && !strcmp(r->protocol, "INCLUDED"))) {
normal:
ctx = SG(server_context) = apr_pcalloc(r->pool, sizeof(*ctx));
/* register a cleanup so we clear out the SG(server_context)
* after each request. Note: We pass in the pointer to the
* server_context in case this is handled by a different thread.
*/
apr_pool_cleanup_register(r->pool, (void *)&SG(server_context), php_server_context_cleanup, apr_pool_cleanup_null);
ctx->r = r;
ctx = NULL; /* May look weird to null it here, but it is to catch the right case in the first_try later on */
} else {
parent_req = ctx->r;
ctx->r = r;
}
apply_config(conf);
if (strcmp(r->handler, PHP_MAGIC_TYPE) && strcmp(r->handler, PHP_SOURCE_MAGIC_TYPE) && strcmp(r->handler, PHP_SCRIPT)) {
/* Check for xbithack in this case. */
if (!AP2(xbithack) || strcmp(r->handler, "text/html") || !(r->finfo.protection & APR_UEXECUTE)) {
PHPAP_INI_OFF;
return DECLINED;
}
}
/* Give a 404 if PATH_INFO is used but is explicitly disabled in
* the configuration; default behaviour is to accept. */
if (r->used_path_info == AP_REQ_REJECT_PATH_INFO
&& r->path_info && r->path_info[0]) {
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
/* handle situations where user turns the engine off */
if (!AP2(engine)) {
PHPAP_INI_OFF;
return DECLINED;
}
if (r->finfo.filetype == 0) {
php_apache_sapi_log_message_ex("script '%s' not found or unable to stat", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_NOT_FOUND;
}
if (r->finfo.filetype == APR_DIR) {
php_apache_sapi_log_message_ex("attempt to invoke directory '%s' as script", r TSRMLS_CC);
PHPAP_INI_OFF;
return HTTP_FORBIDDEN;
}
/* Setup the CGI variables if this is the main request */
if (r->main == NULL ||
/* .. or if the sub-request environment differs from the main-request. */
r->subprocess_env != r->main->subprocess_env
) {
/* setup standard CGI variables */
ap_add_common_vars(r);
ap_add_cgi_vars(r);
}
zend_first_try {
if (ctx == NULL) {
brigade = apr_brigade_create(r->pool, r->connection->bucket_alloc);
ctx = SG(server_context);
ctx->brigade = brigade;
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
} else {
if (!parent_req) {
parent_req = ctx->r;
}
if (parent_req && parent_req->handler &&
strcmp(parent_req->handler, PHP_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SOURCE_MAGIC_TYPE) &&
strcmp(parent_req->handler, PHP_SCRIPT)) {
if (php_apache_request_ctor(r, ctx TSRMLS_CC)!=SUCCESS) {
zend_bailout();
}
}
/*
* check if coming due to ErrorDocument
* We make a special exception of 413 (Invalid POST request) as the invalidity of the request occurs
* during processing of the request by PHP during POST processing. Therefor we need to re-use the exiting
* PHP instance to handle the request rather then creating a new one.
*/
if (parent_req && parent_req->status != HTTP_OK && parent_req->status != 413 && strcmp(r->protocol, "INCLUDED")) {
parent_req = NULL;
goto normal;
}
ctx->r = r;
brigade = ctx->brigade;
}
if (AP2(last_modified)) {
ap_update_mtime(r, r->finfo.mtime);
ap_set_last_modified(r);
}
/* Determine if we need to parse the file or show the source */
if (strncmp(r->handler, PHP_SOURCE_MAGIC_TYPE, sizeof(PHP_SOURCE_MAGIC_TYPE) - 1) == 0) {
zend_syntax_highlighter_ini syntax_highlighter_ini;
php_get_highlight_struct(&syntax_highlighter_ini);
highlight_file((char *)r->filename, &syntax_highlighter_ini TSRMLS_CC);
} else {
zend_file_handle zfd;
zfd.type = ZEND_HANDLE_FILENAME;
zfd.filename = (char *) r->filename;
zfd.free_filename = 0;
zfd.opened_path = NULL;
if (!parent_req) {
php_execute_script(&zfd TSRMLS_CC);
} else {
zend_execute_scripts(ZEND_INCLUDE TSRMLS_CC, NULL, 1, &zfd);
}
apr_table_set(r->notes, "mod_php_memory_usage",
apr_psprintf(ctx->r->pool, "%" APR_SIZE_T_FMT, zend_memory_peak_usage(1 TSRMLS_CC)));
}
} zend_end_try();
if (!parent_req) {
php_apache_request_dtor(r TSRMLS_CC);
ctx->request_processed = 1;
apr_brigade_cleanup(brigade);
bucket = apr_bucket_eos_create(r->connection->bucket_alloc);
APR_BRIGADE_INSERT_TAIL(brigade, bucket);
rv = ap_pass_brigade(r->output_filters, brigade);
if (rv != APR_SUCCESS || r->connection->aborted) {
zend_first_try {
php_handle_aborted_connection();
} zend_end_try();
}
apr_brigade_cleanup(brigade);
apr_pool_cleanup_run(r->pool, (void *)&SG(server_context), php_server_context_cleanup);
} else {
ctx->r = parent_req;
}
return OK;
}
| 169,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool tight_can_send_png_rect(VncState *vs, int w, int h)
{
if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) {
return false;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->clientds.pf.bytes_per_pixel == 1) {
return false;
}
return true;
}
Commit Message:
CWE ID: CWE-125 | static bool tight_can_send_png_rect(VncState *vs, int w, int h)
{
if (vs->tight.type != VNC_ENCODING_TIGHT_PNG) {
return false;
}
if (ds_get_bytes_per_pixel(vs->ds) == 1 ||
vs->client_pf.bytes_per_pixel == 1) {
return false;
}
return true;
}
| 165,463 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: parse_charstrings( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_Int n, num_glyphs;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
num_glyphs = (FT_Int)T1_ToInt( parser );
if ( num_glyphs < 0 )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* some fonts like Optima-Oblique not only define the /CharStrings */
/* array but access it also */
if ( num_glyphs == 0 || parser->root.error )
return;
/* initialize tables, leaving space for addition of .notdef, */
/* if necessary, and a few other glyphs to handle buggy */
/* fonts which have more glyphs than specified. */
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( !loader->num_glyphs )
{
error = psaux->ps_table_funcs->init(
code_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init(
name_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
}
n = 0;
for (;;)
{
FT_Long size;
FT_Byte* base;
/* the format is simple: */
/* `/glyphname' + binary data */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* we stop when we find a `def' or `end' keyword */
if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) )
{
if ( cur[0] == 'd' &&
cur[1] == 'e' &&
cur[2] == 'f' )
{
/* There are fonts which have this: */
/* */
/* /CharStrings 118 dict def */
/* Private begin */
/* CharStrings begin */
/* ... */
/* */
/* To catch this we ignore `def' if */
/* no charstring has actually been */
/* seen. */
if ( n )
break;
}
if ( cur[0] == 'e' &&
cur[1] == 'n' &&
cur[2] == 'd' )
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.error )
return;
if ( cur + 2 >= limit )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) )
return;
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( loader->num_glyphs )
continue;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
if ( face->type1.private_dict.lenIV >= 0 &&
n < num_glyphs + TABLE_EXTEND )
{
FT_Byte* temp;
if ( size <= face->type1.private_dict.lenIV )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* t1_decrypt() shouldn't write to base -- make temporary copy */
if ( FT_ALLOC( temp, size ) )
goto Fail;
FT_MEM_COPY( temp, base, size );
psaux->t1_decrypt( temp, size, 4330 );
size -= face->type1.private_dict.lenIV;
error = T1_Add_Table( code_table, n,
temp + face->type1.private_dict.lenIV, size );
FT_FREE( temp );
}
else
error = T1_Add_Table( code_table, n, base, size );
if ( error )
goto Fail;
n++;
}
}
Commit Message:
CWE ID: CWE-119 | parse_charstrings( T1_Face face,
T1_Loader loader )
{
T1_Parser parser = &loader->parser;
PS_Table code_table = &loader->charstrings;
PS_Table name_table = &loader->glyph_names;
PS_Table swap_table = &loader->swap_table;
FT_Memory memory = parser->root.memory;
FT_Error error;
PSAux_Service psaux = (PSAux_Service)face->psaux;
FT_Byte* cur;
FT_Byte* limit = parser->root.limit;
FT_Int n, num_glyphs;
FT_UInt notdef_index = 0;
FT_Byte notdef_found = 0;
num_glyphs = (FT_Int)T1_ToInt( parser );
if ( num_glyphs < 0 )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* some fonts like Optima-Oblique not only define the /CharStrings */
/* array but access it also */
if ( num_glyphs == 0 || parser->root.error )
return;
/* initialize tables, leaving space for addition of .notdef, */
/* if necessary, and a few other glyphs to handle buggy */
/* fonts which have more glyphs than specified. */
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( !loader->num_glyphs )
{
error = psaux->ps_table_funcs->init(
code_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
error = psaux->ps_table_funcs->init(
name_table, num_glyphs + 1 + TABLE_EXTEND, memory );
if ( error )
goto Fail;
/* Initialize table for swapping index notdef_index and */
/* index 0 names and codes (if necessary). */
error = psaux->ps_table_funcs->init( swap_table, 4, memory );
if ( error )
goto Fail;
}
n = 0;
for (;;)
{
FT_Long size;
FT_Byte* base;
/* the format is simple: */
/* `/glyphname' + binary data */
T1_Skip_Spaces( parser );
cur = parser->root.cursor;
if ( cur >= limit )
break;
/* we stop when we find a `def' or `end' keyword */
if ( cur + 3 < limit && IS_PS_DELIM( cur[3] ) )
{
if ( cur[0] == 'd' &&
cur[1] == 'e' &&
cur[2] == 'f' )
{
/* There are fonts which have this: */
/* */
/* /CharStrings 118 dict def */
/* Private begin */
/* CharStrings begin */
/* ... */
/* */
/* To catch this we ignore `def' if */
/* no charstring has actually been */
/* seen. */
if ( n )
break;
}
if ( cur[0] == 'e' &&
cur[1] == 'n' &&
cur[2] == 'd' )
break;
}
T1_Skip_PS_Token( parser );
if ( parser->root.cursor >= limit )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
if ( parser->root.error )
return;
if ( cur + 2 >= limit )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
cur++; /* skip `/' */
len = parser->root.cursor - cur;
if ( !read_binary_data( parser, &size, &base, IS_INCREMENTAL ) )
return;
/* for some non-standard fonts like `Optima' which provides */
/* different outlines depending on the resolution it is */
/* possible to get here twice */
if ( loader->num_glyphs )
continue;
error = T1_Add_Table( name_table, n, cur, len + 1 );
if ( error )
goto Fail;
/* add a trailing zero to the name table */
name_table->elements[n][len] = '\0';
/* record index of /.notdef */
if ( *cur == '.' &&
ft_strcmp( ".notdef",
(const char*)(name_table->elements[n]) ) == 0 )
{
notdef_index = n;
notdef_found = 1;
}
if ( face->type1.private_dict.lenIV >= 0 &&
n < num_glyphs + TABLE_EXTEND )
{
FT_Byte* temp;
if ( size <= face->type1.private_dict.lenIV )
{
error = FT_THROW( Invalid_File_Format );
goto Fail;
}
/* t1_decrypt() shouldn't write to base -- make temporary copy */
if ( FT_ALLOC( temp, size ) )
goto Fail;
FT_MEM_COPY( temp, base, size );
psaux->t1_decrypt( temp, size, 4330 );
size -= face->type1.private_dict.lenIV;
error = T1_Add_Table( code_table, n,
temp + face->type1.private_dict.lenIV, size );
FT_FREE( temp );
}
else
error = T1_Add_Table( code_table, n, base, size );
if ( error )
goto Fail;
n++;
}
}
| 164,857 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
mime_type_(options->hasMimeType() ? options->mimeType()
: kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
state_(State::kInactive),
dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
this,
&MediaRecorder::DispatchScheduledEvent,
context->GetTaskRunner(TaskType::kDOMManipulation))) {
DCHECK(stream_->getTracks().size());
recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
context->GetTaskRunner(TaskType::kInternalMediaRealTime));
DCHECK(recorder_handler_);
if (!recorder_handler_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No MediaRecorder handler can be created.");
return;
}
AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
&audio_bits_per_second_,
&video_bits_per_second_);
const ContentType content_type(mime_type_);
if (!recorder_handler_->Initialize(
this, stream->Descriptor(), content_type.GetType(),
content_type.Parameter("codecs"), audio_bits_per_second_,
video_bits_per_second_)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Failed to initialize native MediaRecorder the type provided (" +
mime_type_ + ") is not supported.");
return;
}
if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
}
stopped_ = false;
}
Commit Message: Check context is attached before creating MediaRecorder
Bug: 896736
Change-Id: I3ccfd2188fb15704af14c8af050e0a5667855d34
Reviewed-on: https://chromium-review.googlesource.com/c/1324231
Commit-Queue: Emircan Uysaler <[email protected]>
Reviewed-by: Miguel Casas <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606242}
CWE ID: CWE-119 | MediaRecorder::MediaRecorder(ExecutionContext* context,
MediaStream* stream,
const MediaRecorderOptions* options,
ExceptionState& exception_state)
: PausableObject(context),
stream_(stream),
mime_type_(options->hasMimeType() ? options->mimeType()
: kDefaultMimeType),
stopped_(true),
audio_bits_per_second_(0),
video_bits_per_second_(0),
state_(State::kInactive),
dispatch_scheduled_event_runner_(AsyncMethodRunner<MediaRecorder>::Create(
this,
&MediaRecorder::DispatchScheduledEvent,
context->GetTaskRunner(TaskType::kDOMManipulation))) {
if (context->IsContextDestroyed()) {
exception_state.ThrowDOMException(DOMExceptionCode::kNotAllowedError,
"Execution context is detached.");
return;
}
DCHECK(stream_->getTracks().size());
recorder_handler_ = Platform::Current()->CreateMediaRecorderHandler(
context->GetTaskRunner(TaskType::kInternalMediaRealTime));
DCHECK(recorder_handler_);
if (!recorder_handler_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"No MediaRecorder handler can be created.");
return;
}
AllocateVideoAndAudioBitrates(exception_state, context, options, stream,
&audio_bits_per_second_,
&video_bits_per_second_);
const ContentType content_type(mime_type_);
if (!recorder_handler_->Initialize(
this, stream->Descriptor(), content_type.GetType(),
content_type.Parameter("codecs"), audio_bits_per_second_,
video_bits_per_second_)) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Failed to initialize native MediaRecorder the type provided (" +
mime_type_ + ") is not supported.");
return;
}
if (options->mimeType().IsEmpty()) {
const String actual_mime_type = recorder_handler_->ActualMimeType();
if (!actual_mime_type.IsEmpty())
mime_type_ = actual_mime_type;
}
stopped_ = false;
}
| 172,605 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GLSurfaceEGLSurfaceControl::Resize(const gfx::Size& size,
float scale_factor,
ColorSpace color_space,
bool has_alpha) {
return true;
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | bool GLSurfaceEGLSurfaceControl::Resize(const gfx::Size& size,
float scale_factor,
ColorSpace color_space,
bool has_alpha) {
window_rect_ = gfx::Rect(0, 0, size.width(), size.height());
return true;
}
| 172,110 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 DocumentLoader::DidInstallNewDocument(
Document* document,
const ContentSecurityPolicy* previous_csp) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(content_security_policy_.Release(),
nullptr, previous_csp);
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(http_names::kXDNSPrefetchControl);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(http_names::kContentLanguage);
if (!header_content_language.IsEmpty()) {
wtf_size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(http_names::kReferrerPolicy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
Commit Message: Inherit the navigation initiator when navigating instead of the parent/opener
Spec PR: https://github.com/w3c/webappsec-csp/pull/358
Bug: 905301, 894228, 836148
Change-Id: I43ada2266d42d1cd56dbe3c6dd89d115e878a83a
Reviewed-on: https://chromium-review.googlesource.com/c/1314633
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Mike West <[email protected]>
Cr-Commit-Position: refs/heads/master@{#610850}
CWE ID: CWE-20 | void DocumentLoader::DidInstallNewDocument(
void DocumentLoader::DidInstallNewDocument(Document* document) {
document->SetReadyState(Document::kLoading);
if (content_security_policy_) {
document->InitContentSecurityPolicy(
content_security_policy_.Release(),
GetFrameLoader().GetLastOriginDocument());
}
if (history_item_ && IsBackForwardLoadType(load_type_))
document->SetStateForNewFormElements(history_item_->GetDocumentState());
DCHECK(document->GetFrame());
document->GetFrame()->GetClientHintsPreferences().UpdateFrom(
client_hints_preferences_);
Settings* settings = document->GetSettings();
fetcher_->SetImagesEnabled(settings->GetImagesEnabled());
fetcher_->SetAutoLoadImages(settings->GetLoadsImagesAutomatically());
const AtomicString& dns_prefetch_control =
response_.HttpHeaderField(http_names::kXDNSPrefetchControl);
if (!dns_prefetch_control.IsEmpty())
document->ParseDNSPrefetchControlHeader(dns_prefetch_control);
String header_content_language =
response_.HttpHeaderField(http_names::kContentLanguage);
if (!header_content_language.IsEmpty()) {
wtf_size_t comma_index = header_content_language.find(',');
header_content_language.Truncate(comma_index);
header_content_language =
header_content_language.StripWhiteSpace(IsHTMLSpace<UChar>);
if (!header_content_language.IsEmpty())
document->SetContentLanguage(AtomicString(header_content_language));
}
String referrer_policy_header =
response_.HttpHeaderField(http_names::kReferrerPolicy);
if (!referrer_policy_header.IsNull()) {
UseCounter::Count(*document, WebFeature::kReferrerPolicyHeader);
document->ParseAndSetReferrerPolicy(referrer_policy_header);
}
if (response_.IsSignedExchangeInnerResponse())
UseCounter::Count(*document, WebFeature::kSignedExchangeInnerResponse);
GetLocalFrameClient().DidCreateNewDocument();
}
| 173,056 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void XMLHttpRequest::genericError()
{
clearResponse();
clearRequest();
m_error = true;
changeState(DONE);
}
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::genericError()
void XMLHttpRequest::handleDidFailGeneric()
{
clearResponse();
clearRequest();
m_error = true;
}
| 171,168 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int add_post_vars(zval *arr, post_var_data_t *vars, zend_bool eof TSRMLS_DC)
{
uint64_t max_vars = PG(max_input_vars);
vars->ptr = vars->str.c;
vars->end = vars->str.c + vars->str.len;
while (add_post_var(arr, vars, eof TSRMLS_CC)) {
if (++vars->cnt > max_vars) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Input variables exceeded %" PRIu64 ". "
"To increase the limit change max_input_vars in php.ini.",
max_vars);
return FAILURE;
}
}
if (!eof) {
memmove(vars->str.c, vars->ptr, vars->str.len = vars->end - vars->ptr);
}
return SUCCESS;
}
Commit Message: Fix bug #73807
CWE ID: CWE-400 | static inline int add_post_vars(zval *arr, post_var_data_t *vars, zend_bool eof TSRMLS_DC)
{
uint64_t max_vars = PG(max_input_vars);
vars->ptr = vars->str.c;
vars->end = vars->str.c + vars->str.len;
while (add_post_var(arr, vars, eof TSRMLS_CC)) {
if (++vars->cnt > max_vars) {
php_error_docref(NULL TSRMLS_CC, E_WARNING,
"Input variables exceeded %" PRIu64 ". "
"To increase the limit change max_input_vars in php.ini.",
max_vars);
return FAILURE;
}
}
if (!eof && vars->str.c != vars->ptr) {
memmove(vars->str.c, vars->ptr, vars->str.len = vars->end - vars->ptr);
}
return SUCCESS;
}
| 168,055 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: huff_get_next_word(Jbig2HuffmanState *hs, int offset)
{
uint32_t word = 0;
Jbig2WordStream *ws = hs->ws;
if ((ws->get_next_word(ws, offset, &word)) && ((hs->offset_limit == 0) || (offset < hs->offset_limit)))
hs->offset_limit = offset;
return word;
}
Commit Message:
CWE ID: CWE-119 | huff_get_next_word(Jbig2HuffmanState *hs, int offset)
huff_get_next_word(Jbig2HuffmanState *hs, uint32_t offset)
{
uint32_t word = 0;
Jbig2WordStream *ws = hs->ws;
if ((ws->get_next_word(ws, offset, &word)) && ((hs->offset_limit == 0) || (offset < hs->offset_limit)))
hs->offset_limit = offset;
return word;
}
| 165,488 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 blk_init_allocated_queue(struct request_queue *q)
{
WARN_ON_ONCE(q->mq_ops);
q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);
if (!q->fq)
return -ENOMEM;
if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))
goto out_free_flush_queue;
if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
goto out_exit_flush_rq;
INIT_WORK(&q->timeout_work, blk_timeout_work);
q->queue_flags |= QUEUE_FLAG_DEFAULT;
/*
* This also sets hw/phys segments, boundary and size
*/
blk_queue_make_request(q, blk_queue_bio);
q->sg_reserved_size = INT_MAX;
if (elevator_init(q))
goto out_exit_flush_rq;
return 0;
out_exit_flush_rq:
if (q->exit_rq_fn)
q->exit_rq_fn(q, q->fq->flush_rq);
out_free_flush_queue:
blk_free_flush_queue(q->fq);
return -ENOMEM;
}
Commit Message: block: blk_init_allocated_queue() set q->fq as NULL in the fail case
We find the memory use-after-free issue in __blk_drain_queue()
on the kernel 4.14. After read the latest kernel 4.18-rc6 we
think it has the same problem.
Memory is allocated for q->fq in the blk_init_allocated_queue().
If the elevator init function called with error return, it will
run into the fail case to free the q->fq.
Then the __blk_drain_queue() uses the same memory after the free
of the q->fq, it will lead to the unpredictable event.
The patch is to set q->fq as NULL in the fail case of
blk_init_allocated_queue().
Fixes: commit 7c94e1c157a2 ("block: introduce blk_flush_queue to drive flush machinery")
Cc: <[email protected]>
Reviewed-by: Ming Lei <[email protected]>
Reviewed-by: Bart Van Assche <[email protected]>
Signed-off-by: xiao jin <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-416 | int blk_init_allocated_queue(struct request_queue *q)
{
WARN_ON_ONCE(q->mq_ops);
q->fq = blk_alloc_flush_queue(q, NUMA_NO_NODE, q->cmd_size);
if (!q->fq)
return -ENOMEM;
if (q->init_rq_fn && q->init_rq_fn(q, q->fq->flush_rq, GFP_KERNEL))
goto out_free_flush_queue;
if (blk_init_rl(&q->root_rl, q, GFP_KERNEL))
goto out_exit_flush_rq;
INIT_WORK(&q->timeout_work, blk_timeout_work);
q->queue_flags |= QUEUE_FLAG_DEFAULT;
/*
* This also sets hw/phys segments, boundary and size
*/
blk_queue_make_request(q, blk_queue_bio);
q->sg_reserved_size = INT_MAX;
if (elevator_init(q))
goto out_exit_flush_rq;
return 0;
out_exit_flush_rq:
if (q->exit_rq_fn)
q->exit_rq_fn(q, q->fq->flush_rq);
out_free_flush_queue:
blk_free_flush_queue(q->fq);
q->fq = NULL;
return -ENOMEM;
}
| 169,762 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
unsigned code_point;
ReadUTFChar(spec, &i, end, &code_point);
AppendUTF8Value(code_point, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
Commit Message: Percent-encode UTF8 characters in URL fragment identifiers.
This brings us into line with Firefox, Safari, and the spec.
Bug: 758523
Change-Id: I7e354ab441222d9fd08e45f0e70f91ad4e35fafe
Reviewed-on: https://chromium-review.googlesource.com/668363
Commit-Queue: Mike West <[email protected]>
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507481}
CWE ID: CWE-79 | void DoCanonicalizeRef(const CHAR* spec,
const Component& ref,
CanonOutput* output,
Component* out_ref) {
if (ref.len < 0) {
*out_ref = Component();
return;
}
output->push_back('#');
out_ref->begin = output->length();
int end = ref.end();
for (int i = ref.begin; i < end; i++) {
if (spec[i] == 0) {
continue;
} else if (static_cast<UCHAR>(spec[i]) < 0x20) {
AppendEscapedChar(static_cast<unsigned char>(spec[i]), output);
} else if (static_cast<UCHAR>(spec[i]) < 0x80) {
output->push_back(static_cast<char>(spec[i]));
} else {
AppendUTF8EscapedChar(spec, &i, end, output);
}
}
out_ref->len = output->length() - out_ref->begin;
}
| 172,903 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) {
UNUSED(p_org_set);
BTIF_TRACE_DEBUG("entering %s",__FUNCTION__);
for (const list_node_t *node = list_begin(soc_queue);
node != list_end(soc_queue); node = list_next(node)) {
btif_hl_soc_cb_t *p_scb = list_node(node);
if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) {
if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) {
BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ");
btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx,
p_scb->mcl_idx, p_scb->mdl_idx);
assert(p_dcb != NULL);
if (p_dcb->p_tx_pkt) {
BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been"
" sent tx_size=%d", p_dcb->tx_size);
btif_hl_free_buf((void **) &p_dcb->p_tx_pkt);
}
p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu);
if (p_dcb) {
int r = (int)recv(p_scb->socket_id[1], p_dcb->p_tx_pkt,
p_dcb->mtu, MSG_DONTWAIT);
if (r > 0) {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r);
p_dcb->tx_size = r;
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size );
BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size);
} else {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r);
BTA_HlDchClose(p_dcb->mdl_handle);
}
}
}
}
}
if (list_is_empty(soc_queue))
BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty");
BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
}
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 | void btif_hl_select_monitor_callback(fd_set *p_cur_set ,fd_set *p_org_set) {
UNUSED(p_org_set);
BTIF_TRACE_DEBUG("entering %s",__FUNCTION__);
for (const list_node_t *node = list_begin(soc_queue);
node != list_end(soc_queue); node = list_next(node)) {
btif_hl_soc_cb_t *p_scb = list_node(node);
if (btif_hl_get_socket_state(p_scb) == BTIF_HL_SOC_STATE_W4_READ) {
if (FD_ISSET(p_scb->socket_id[1], p_cur_set)) {
BTIF_TRACE_DEBUG("read data state= BTIF_HL_SOC_STATE_W4_READ");
btif_hl_mdl_cb_t *p_dcb = BTIF_HL_GET_MDL_CB_PTR(p_scb->app_idx,
p_scb->mcl_idx, p_scb->mdl_idx);
assert(p_dcb != NULL);
if (p_dcb->p_tx_pkt) {
BTIF_TRACE_ERROR("Rcv new pkt but the last pkt is still not been"
" sent tx_size=%d", p_dcb->tx_size);
btif_hl_free_buf((void **) &p_dcb->p_tx_pkt);
}
p_dcb->p_tx_pkt = btif_hl_get_buf (p_dcb->mtu);
if (p_dcb) {
int r = (int)TEMP_FAILURE_RETRY(recv(p_scb->socket_id[1], p_dcb->p_tx_pkt,
p_dcb->mtu, MSG_DONTWAIT));
if (r > 0) {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data r =%d", r);
p_dcb->tx_size = r;
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback send data tx_size=%d", p_dcb->tx_size );
BTA_HlSendData(p_dcb->mdl_handle, p_dcb->tx_size);
} else {
BTIF_TRACE_DEBUG("btif_hl_select_monitor_callback receive failed r=%d",r);
BTA_HlDchClose(p_dcb->mdl_handle);
}
}
}
}
}
if (list_is_empty(soc_queue))
BTIF_TRACE_DEBUG("btif_hl_select_monitor_queue is empty");
BTIF_TRACE_DEBUG("leaving %s",__FUNCTION__);
}
| 173,441 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + (rlen + 1);
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
if (ch <= chend) {
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
Commit Message:
CWE ID: CWE-682 | XListFonts(
register Display *dpy,
_Xconst char *pattern, /* null-terminated */
int maxNames,
int *actualCount) /* RETURN */
{
register long nbytes;
register unsigned i;
register int length;
char **flist = NULL;
char *ch = NULL;
char *chstart;
char *chend;
int count = 0;
xListFontsReply rep;
register xListFontsReq *req;
unsigned long rlen = 0;
LockDisplay(dpy);
GetReq(ListFonts, req);
req->maxNames = maxNames;
nbytes = req->nbytes = pattern ? strlen (pattern) : 0;
req->length += (nbytes + 3) >> 2;
_XSend (dpy, pattern, nbytes);
/* use _XSend instead of Data, since following _XReply will flush buffer */
if (!_XReply (dpy, (xReply *)&rep, 0, xFalse)) {
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
if (rep.nFonts) {
flist = Xmalloc (rep.nFonts * sizeof(char *));
if (rep.length > 0 && rep.length < (INT_MAX >> 2)) {
rlen = rep.length << 2;
ch = Xmalloc(rlen + 1);
/* +1 to leave room for last null-terminator */
}
if ((! flist) || (! ch)) {
Xfree(flist);
Xfree(ch);
_XEatDataWords(dpy, rep.length);
*actualCount = 0;
UnlockDisplay(dpy);
SyncHandle();
return (char **) NULL;
}
_XReadPad (dpy, ch, rlen);
/*
* unpack into null terminated strings.
*/
chstart = ch;
chend = ch + rlen;
length = *(unsigned char *)ch;
*ch = 1; /* make sure it is non-zero for XFreeFontNames */
for (i = 0; i < rep.nFonts; i++) {
if (ch + length < chend) {
flist[i] = ch + 1; /* skip over length */
ch += length + 1; /* find next length ... */
length = *(unsigned char *)ch;
*ch = '\0'; /* and replace with null-termination */
count++;
} else {
Xfree(chstart);
Xfree(flist);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
} else {
Xfree(chstart);
Xfree(flist);
flist = NULL;
count = 0;
break;
}
}
}
| 164,747 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 PrintPreviewUI::GetPrintPreviewDataForIndex(
int index,
scoped_refptr<base::RefCountedBytes>* data) {
print_preview_data_service()->GetDataEntry(preview_ui_addr_str_, index, data);
}
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 PrintPreviewUI::GetPrintPreviewDataForIndex(
int index,
scoped_refptr<base::RefCountedBytes>* data) {
print_preview_data_service()->GetDataEntry(id_, index, data);
}
| 170,834 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u", nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
Commit Message: fix build
Change-Id: I9bb8c659d3fc97a8e748451d82d0f3448faa242b
CWE ID: CWE-119 | bool SoftVPX::outputBufferSafe(OMX_BUFFERHEADERTYPE *outHeader) {
uint32_t width = outputBufferWidth();
uint32_t height = outputBufferHeight();
uint64_t nFilledLen = width;
nFilledLen *= height;
if (nFilledLen > UINT32_MAX / 3) {
ALOGE("b/29421675, nFilledLen overflow %llu w %u h %u",
(unsigned long long)nFilledLen, width, height);
android_errorWriteLog(0x534e4554, "29421675");
return false;
} else if (outHeader->nAllocLen < outHeader->nFilledLen) {
ALOGE("b/27597103, buffer too small");
android_errorWriteLog(0x534e4554, "27597103");
return false;
}
return true;
}
| 173,414 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp =
&pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno,
++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp
<< r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,
pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp
<< r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,
pi->pirlvl->prcheightexpn);
pi->prcno = prcvind *
pi->pirlvl->numhprcs +
prchind;
assert(pi->prcno <
pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno <
pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
Commit Message: Fixed numerous integer overflow problems in the code for packet iterators
in the JPC decoder.
CWE ID: CWE-125 | static int jpc_pi_nextcprl(register jpc_pi_t *pi)
{
int rlvlno;
jpc_pirlvl_t *pirlvl;
jpc_pchg_t *pchg;
int prchind;
int prcvind;
int *prclyrno;
uint_fast32_t trx0;
uint_fast32_t try0;
uint_fast32_t r;
uint_fast32_t rpx;
uint_fast32_t rpy;
pchg = pi->pchg;
if (!pi->prgvolfirst) {
goto skip;
} else {
pi->prgvolfirst = 0;
}
for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno];
pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps;
++pi->compno, ++pi->picomp) {
pirlvl = pi->picomp->pirlvls;
// Check for the potential for overflow problems.
if (pirlvl->prcwidthexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2 ||
pirlvl->prcheightexpn + pi->picomp->numrlvls >
JAS_UINTFAST32_NUMBITS - 2) {
return -1;
}
pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1));
pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) <<
(pirlvl->prcheightexpn + pi->picomp->numrlvls - 1));
for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1];
rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) {
pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn +
pi->picomp->numrlvls - rlvlno - 1)));
pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp *
(JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn +
pi->picomp->numrlvls - rlvlno - 1)));
}
for (pi->y = pi->ystart; pi->y < pi->yend;
pi->y += pi->ystep - (pi->y % pi->ystep)) {
for (pi->x = pi->xstart; pi->x < pi->xend;
pi->x += pi->xstep - (pi->x % pi->xstep)) {
for (pi->rlvlno = pchg->rlvlnostart,
pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];
pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno <
pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) {
if (pi->pirlvl->numprcs == 0) {
continue;
}
r = pi->picomp->numrlvls - 1 - pi->rlvlno;
trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);
try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);
rpx = r + pi->pirlvl->prcwidthexpn;
rpy = r + pi->pirlvl->prcheightexpn;
if (((pi->x == pi->xstart &&
((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) ||
!(pi->x % (pi->picomp->hsamp << rpx))) &&
((pi->y == pi->ystart &&
((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) ||
!(pi->y % (pi->picomp->vsamp << rpy)))) {
prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x,
pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) -
JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn);
prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y,
pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) -
JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn);
pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;
assert(pi->prcno < pi->pirlvl->numprcs);
for (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&
pi->lyrno < JAS_CAST(int, pchg->lyrnoend);
++pi->lyrno) {
prclyrno = &pi->pirlvl->prclyrnos[pi->prcno];
if (pi->lyrno >= *prclyrno) {
++(*prclyrno);
return 0;
}
skip:
;
}
}
}
}
}
}
return 1;
}
| 169,439 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
void *resp_buf;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
int ret = -ENOMEM, npages, i, acl_len = 0;
npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
if (npages > 1) {
/* for decoding across pages */
res.acl_scratch = alloc_page(GFP_KERNEL);
if (!res.acl_scratch)
goto out_free;
}
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
/* Let decode_getfacl know not to fail if the ACL data is larger than
* the page we send as a guess */
if (buf == NULL)
res.acl_flags |= NFS4_ACL_LEN_REQUEST;
resp_buf = page_address(pages[0]);
dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
acl_len = res.acl_len - res.acl_data_offset;
if (acl_len > args.acl_len)
nfs4_write_cached_acl(inode, NULL, acl_len);
else
nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset,
acl_len);
if (buf) {
ret = -ERANGE;
if (acl_len > buflen)
goto out_free;
_copy_from_pages(buf, pages, res.acl_data_offset,
res.acl_len);
}
ret = acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (res.acl_scratch)
__free_page(res.acl_scratch);
return ret;
}
Commit Message: Fix length of buffer copied in __nfs4_get_acl_uncached
_copy_from_pages() used to copy data from the temporary buffer to the
user passed buffer is passed the wrong size parameter when copying
data. res.acl_len contains both the bitmap and acl lenghts while
acl_len contains the acl length after adjusting for the bitmap size.
Signed-off-by: Sachin Prabhu <[email protected]>
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: CWE-189 | static ssize_t __nfs4_get_acl_uncached(struct inode *inode, void *buf, size_t buflen)
{
struct page *pages[NFS4ACL_MAXPAGES] = {NULL, };
struct nfs_getaclargs args = {
.fh = NFS_FH(inode),
.acl_pages = pages,
.acl_len = buflen,
};
struct nfs_getaclres res = {
.acl_len = buflen,
};
void *resp_buf;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_GETACL],
.rpc_argp = &args,
.rpc_resp = &res,
};
int ret = -ENOMEM, npages, i, acl_len = 0;
npages = (buflen + PAGE_SIZE - 1) >> PAGE_SHIFT;
/* As long as we're doing a round trip to the server anyway,
* let's be prepared for a page of acl data. */
if (npages == 0)
npages = 1;
for (i = 0; i < npages; i++) {
pages[i] = alloc_page(GFP_KERNEL);
if (!pages[i])
goto out_free;
}
if (npages > 1) {
/* for decoding across pages */
res.acl_scratch = alloc_page(GFP_KERNEL);
if (!res.acl_scratch)
goto out_free;
}
args.acl_len = npages * PAGE_SIZE;
args.acl_pgbase = 0;
/* Let decode_getfacl know not to fail if the ACL data is larger than
* the page we send as a guess */
if (buf == NULL)
res.acl_flags |= NFS4_ACL_LEN_REQUEST;
resp_buf = page_address(pages[0]);
dprintk("%s buf %p buflen %zu npages %d args.acl_len %zu\n",
__func__, buf, buflen, npages, args.acl_len);
ret = nfs4_call_sync(NFS_SERVER(inode)->client, NFS_SERVER(inode),
&msg, &args.seq_args, &res.seq_res, 0);
if (ret)
goto out_free;
acl_len = res.acl_len - res.acl_data_offset;
if (acl_len > args.acl_len)
nfs4_write_cached_acl(inode, NULL, acl_len);
else
nfs4_write_cached_acl(inode, resp_buf + res.acl_data_offset,
acl_len);
if (buf) {
ret = -ERANGE;
if (acl_len > buflen)
goto out_free;
_copy_from_pages(buf, pages, res.acl_data_offset,
acl_len);
}
ret = acl_len;
out_free:
for (i = 0; i < npages; i++)
if (pages[i])
__free_page(pages[i]);
if (res.acl_scratch)
__free_page(res.acl_scratch);
return ret;
}
| 165,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Block* SimpleBlock::GetBlock() const
{
return &m_block;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Block* SimpleBlock::GetBlock() const
| 174,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *isk = inet_sk(sk);
int family = sk->sk_family;
struct sk_buff *skb;
int copied, err;
pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
err = -EOPNOTSUPP;
if (flags & MSG_OOB)
goto out;
if (flags & MSG_ERRQUEUE) {
if (family == AF_INET) {
return ip_recv_error(sk, msg, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
return pingv6_ops.ipv6_recv_error(sk, msg, len);
#endif
}
}
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* Don't bother checking the checksum */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address and add cmsg data. */
if (family == AF_INET) {
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
sin->sin_family = AF_INET;
sin->sin_port = 0 /* skb->h.uh->source */;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
if (isk->cmsg_flags)
ip_cmsg_recv(msg, skb);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6hdr *ip6 = ipv6_hdr(skb);
struct sockaddr_in6 *sin6 =
(struct sockaddr_in6 *)msg->msg_name;
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ip6->saddr;
sin6->sin6_flowinfo = 0;
if (np->sndflow)
sin6->sin6_flowinfo = ip6_flowinfo(ip6);
sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
*addr_len = sizeof(*sin6);
if (inet6_sk(sk)->rxopt.all)
pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);
#endif
} else {
BUG();
}
err = copied;
done:
skb_free_datagram(sk, skb);
out:
pr_debug("ping_recvmsg -> %d\n", err);
return err;
}
Commit Message: ping: prevent NULL pointer dereference on write to msg_name
A plain read() on a socket does set msg->msg_name to NULL. So check for
NULL pointer first.
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *isk = inet_sk(sk);
int family = sk->sk_family;
struct sk_buff *skb;
int copied, err;
pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
err = -EOPNOTSUPP;
if (flags & MSG_OOB)
goto out;
if (flags & MSG_ERRQUEUE) {
if (family == AF_INET) {
return ip_recv_error(sk, msg, len);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
return pingv6_ops.ipv6_recv_error(sk, msg, len);
#endif
}
}
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
/* Don't bother checking the checksum */
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address and add cmsg data. */
if (family == AF_INET) {
struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
if (sin) {
sin->sin_family = AF_INET;
sin->sin_port = 0 /* skb->h.uh->source */;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (isk->cmsg_flags)
ip_cmsg_recv(msg, skb);
#if IS_ENABLED(CONFIG_IPV6)
} else if (family == AF_INET6) {
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6hdr *ip6 = ipv6_hdr(skb);
struct sockaddr_in6 *sin6 =
(struct sockaddr_in6 *)msg->msg_name;
if (sin6) {
sin6->sin6_family = AF_INET6;
sin6->sin6_port = 0;
sin6->sin6_addr = ip6->saddr;
sin6->sin6_flowinfo = 0;
if (np->sndflow)
sin6->sin6_flowinfo = ip6_flowinfo(ip6);
sin6->sin6_scope_id =
ipv6_iface_scope_id(&sin6->sin6_addr,
IP6CB(skb)->iif);
*addr_len = sizeof(*sin6);
}
if (inet6_sk(sk)->rxopt.all)
pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);
#endif
} else {
BUG();
}
err = copied;
done:
skb_free_datagram(sk, skb);
out:
pr_debug("ping_recvmsg -> %d\n", err);
return err;
}
| 165,937 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ndp_sock_open(struct ndp *ndp)
{
int sock;
int ret;
int err;
int val;
sock = socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
if (sock == -1) {
err(ndp, "Failed to create ICMP6 socket.");
return -errno;
}
val = 1;
ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
&val, sizeof(val));
if (ret == -1) {
err(ndp, "Failed to setsockopt IPV6_RECVPKTINFO.");
err = -errno;
goto close_sock;
}
val = 255;
ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
&val, sizeof(val));
if (ret == -1) {
err(ndp, "Failed to setsockopt IPV6_MULTICAST_HOPS.");
err = -errno;
goto close_sock;
}
ndp->sock = sock;
return 0;
close_sock:
close(sock);
return err;
}
Commit Message: libndp: validate the IPv6 hop limit
None of the NDP messages should ever come from a non-local network; as
stated in RFC4861's 6.1.1 (RS), 6.1.2 (RA), 7.1.1 (NS), 7.1.2 (NA),
and 8.1. (redirect):
- The IP Hop Limit field has a value of 255, i.e., the packet
could not possibly have been forwarded by a router.
This fixes CVE-2016-3698.
Reported by: Julien BERNARD <[email protected]>
Signed-off-by: Lubomir Rintel <[email protected]>
Signed-off-by: Jiri Pirko <[email protected]>
CWE ID: CWE-284 | static int ndp_sock_open(struct ndp *ndp)
{
int sock;
int ret;
int err;
int val;
sock = socket(PF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
if (sock == -1) {
err(ndp, "Failed to create ICMP6 socket.");
return -errno;
}
val = 1;
ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO,
&val, sizeof(val));
if (ret == -1) {
err(ndp, "Failed to setsockopt IPV6_RECVPKTINFO.");
err = -errno;
goto close_sock;
}
val = 255;
ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
&val, sizeof(val));
if (ret == -1) {
err(ndp, "Failed to setsockopt IPV6_MULTICAST_HOPS.");
err = -errno;
goto close_sock;
}
val = 1;
ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT,
&val, sizeof(val));
if (ret == -1) {
err(ndp, "Failed to setsockopt IPV6_RECVHOPLIMIT,.");
err = -errno;
goto close_sock;
}
ndp->sock = sock;
return 0;
close_sock:
close(sock);
return err;
}
| 167,349 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t NuPlayer::GenericSource::initFromDataSource() {
sp<MediaExtractor> extractor;
String8 mimeType;
float confidence;
sp<AMessage> dummy;
bool isWidevineStreaming = false;
CHECK(mDataSource != NULL);
if (mIsWidevine) {
isWidevineStreaming = SniffWVM(
mDataSource, &mimeType, &confidence, &dummy);
if (!isWidevineStreaming ||
strcasecmp(
mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) {
ALOGE("unsupported widevine mime: %s", mimeType.string());
return UNKNOWN_ERROR;
}
} else if (mIsStreaming) {
if (!mDataSource->sniff(&mimeType, &confidence, &dummy)) {
return UNKNOWN_ERROR;
}
isWidevineStreaming = !strcasecmp(
mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM);
}
if (isWidevineStreaming) {
mCachedSource.clear();
mDataSource = mHttpSource;
mWVMExtractor = new WVMExtractor(mDataSource);
mWVMExtractor->setAdaptiveStreamingMode(true);
if (mUIDValid) {
mWVMExtractor->setUID(mUID);
}
extractor = mWVMExtractor;
} else {
extractor = MediaExtractor::Create(mDataSource,
mimeType.isEmpty() ? NULL : mimeType.string());
}
if (extractor == NULL) {
return UNKNOWN_ERROR;
}
if (extractor->getDrmFlag()) {
checkDrmStatus(mDataSource);
}
mFileMeta = extractor->getMetaData();
if (mFileMeta != NULL) {
int64_t duration;
if (mFileMeta->findInt64(kKeyDuration, &duration)) {
mDurationUs = duration;
}
if (!mIsWidevine) {
const char *fileMime;
if (mFileMeta->findCString(kKeyMIMEType, &fileMime)
&& !strncasecmp(fileMime, "video/wvm", 9)) {
mIsWidevine = true;
}
}
}
int32_t totalBitrate = 0;
size_t numtracks = extractor->countTracks();
if (numtracks == 0) {
return UNKNOWN_ERROR;
}
for (size_t i = 0; i < numtracks; ++i) {
sp<MediaSource> track = extractor->getTrack(i);
sp<MetaData> meta = extractor->getTrackMetaData(i);
const char *mime;
CHECK(meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp(mime, "audio/", 6)) {
if (mAudioTrack.mSource == NULL) {
mAudioTrack.mIndex = i;
mAudioTrack.mSource = track;
mAudioTrack.mPackets =
new AnotherPacketSource(mAudioTrack.mSource->getFormat());
if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) {
mAudioIsVorbis = true;
} else {
mAudioIsVorbis = false;
}
}
} else if (!strncasecmp(mime, "video/", 6)) {
if (mVideoTrack.mSource == NULL) {
mVideoTrack.mIndex = i;
mVideoTrack.mSource = track;
mVideoTrack.mPackets =
new AnotherPacketSource(mVideoTrack.mSource->getFormat());
int32_t secure;
if (meta->findInt32(kKeyRequiresSecureBuffers, &secure)
&& secure) {
mIsSecure = true;
if (mUIDValid) {
extractor->setUID(mUID);
}
}
}
}
if (track != NULL) {
mSources.push(track);
int64_t durationUs;
if (meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > mDurationUs) {
mDurationUs = durationUs;
}
}
int32_t bitrate;
if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) {
totalBitrate += bitrate;
} else {
totalBitrate = -1;
}
}
}
mBitrate = totalBitrate;
return OK;
}
Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track.
GenericSource: return error when no track exists.
SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor.
Bug: 21657957
Bug: 23705695
Bug: 22802344
Bug: 28799341
Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04
(cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13)
CWE ID: CWE-119 | status_t NuPlayer::GenericSource::initFromDataSource() {
sp<MediaExtractor> extractor;
String8 mimeType;
float confidence;
sp<AMessage> dummy;
bool isWidevineStreaming = false;
CHECK(mDataSource != NULL);
if (mIsWidevine) {
isWidevineStreaming = SniffWVM(
mDataSource, &mimeType, &confidence, &dummy);
if (!isWidevineStreaming ||
strcasecmp(
mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM)) {
ALOGE("unsupported widevine mime: %s", mimeType.string());
return UNKNOWN_ERROR;
}
} else if (mIsStreaming) {
if (!mDataSource->sniff(&mimeType, &confidence, &dummy)) {
return UNKNOWN_ERROR;
}
isWidevineStreaming = !strcasecmp(
mimeType.string(), MEDIA_MIMETYPE_CONTAINER_WVM);
}
if (isWidevineStreaming) {
mCachedSource.clear();
mDataSource = mHttpSource;
mWVMExtractor = new WVMExtractor(mDataSource);
mWVMExtractor->setAdaptiveStreamingMode(true);
if (mUIDValid) {
mWVMExtractor->setUID(mUID);
}
extractor = mWVMExtractor;
} else {
extractor = MediaExtractor::Create(mDataSource,
mimeType.isEmpty() ? NULL : mimeType.string());
}
if (extractor == NULL) {
return UNKNOWN_ERROR;
}
if (extractor->getDrmFlag()) {
checkDrmStatus(mDataSource);
}
mFileMeta = extractor->getMetaData();
if (mFileMeta != NULL) {
int64_t duration;
if (mFileMeta->findInt64(kKeyDuration, &duration)) {
mDurationUs = duration;
}
if (!mIsWidevine) {
const char *fileMime;
if (mFileMeta->findCString(kKeyMIMEType, &fileMime)
&& !strncasecmp(fileMime, "video/wvm", 9)) {
mIsWidevine = true;
}
}
}
int32_t totalBitrate = 0;
size_t numtracks = extractor->countTracks();
if (numtracks == 0) {
return UNKNOWN_ERROR;
}
for (size_t i = 0; i < numtracks; ++i) {
sp<MediaSource> track = extractor->getTrack(i);
if (track == NULL) {
continue;
}
sp<MetaData> meta = extractor->getTrackMetaData(i);
const char *mime;
CHECK(meta->findCString(kKeyMIMEType, &mime));
if (!strncasecmp(mime, "audio/", 6)) {
if (mAudioTrack.mSource == NULL) {
mAudioTrack.mIndex = i;
mAudioTrack.mSource = track;
mAudioTrack.mPackets =
new AnotherPacketSource(mAudioTrack.mSource->getFormat());
if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) {
mAudioIsVorbis = true;
} else {
mAudioIsVorbis = false;
}
}
} else if (!strncasecmp(mime, "video/", 6)) {
if (mVideoTrack.mSource == NULL) {
mVideoTrack.mIndex = i;
mVideoTrack.mSource = track;
mVideoTrack.mPackets =
new AnotherPacketSource(mVideoTrack.mSource->getFormat());
int32_t secure;
if (meta->findInt32(kKeyRequiresSecureBuffers, &secure)
&& secure) {
mIsSecure = true;
if (mUIDValid) {
extractor->setUID(mUID);
}
}
}
}
mSources.push(track);
int64_t durationUs;
if (meta->findInt64(kKeyDuration, &durationUs)) {
if (durationUs > mDurationUs) {
mDurationUs = durationUs;
}
}
int32_t bitrate;
if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) {
totalBitrate += bitrate;
} else {
totalBitrate = -1;
}
}
if (mSources.size() == 0) {
ALOGE("b/23705695");
return UNKNOWN_ERROR;
}
mBitrate = totalBitrate;
return OK;
}
| 173,762 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev,
struct ib_udata *udata)
{
int ret = 0;
struct hns_roce_ucontext *context;
struct hns_roce_ib_alloc_ucontext_resp resp;
struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev);
resp.qp_tab_size = hr_dev->caps.num_qps;
context = kmalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
ret = hns_roce_uar_alloc(hr_dev, &context->uar);
if (ret)
goto error_fail_uar_alloc;
if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) {
INIT_LIST_HEAD(&context->page_list);
mutex_init(&context->page_mutex);
}
ret = ib_copy_to_udata(udata, &resp, sizeof(resp));
if (ret)
goto error_fail_copy_to_udata;
return &context->ibucontext;
error_fail_copy_to_udata:
hns_roce_uar_free(hr_dev, &context->uar);
error_fail_uar_alloc:
kfree(context);
return ERR_PTR(ret);
}
Commit Message: RDMA/hns: Fix init resp when alloc ucontext
The data in resp will be copied from kernel to userspace, thus it needs to
be initialized to zeros to avoid copying uninited stack memory.
Reported-by: Dan Carpenter <[email protected]>
Fixes: e088a685eae9 ("RDMA/hns: Support rq record doorbell for the user space")
Signed-off-by: Yixian Liu <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
CWE ID: CWE-665 | static struct ib_ucontext *hns_roce_alloc_ucontext(struct ib_device *ib_dev,
struct ib_udata *udata)
{
int ret = 0;
struct hns_roce_ucontext *context;
struct hns_roce_ib_alloc_ucontext_resp resp = {};
struct hns_roce_dev *hr_dev = to_hr_dev(ib_dev);
resp.qp_tab_size = hr_dev->caps.num_qps;
context = kmalloc(sizeof(*context), GFP_KERNEL);
if (!context)
return ERR_PTR(-ENOMEM);
ret = hns_roce_uar_alloc(hr_dev, &context->uar);
if (ret)
goto error_fail_uar_alloc;
if (hr_dev->caps.flags & HNS_ROCE_CAP_FLAG_RECORD_DB) {
INIT_LIST_HEAD(&context->page_list);
mutex_init(&context->page_mutex);
}
ret = ib_copy_to_udata(udata, &resp, sizeof(resp));
if (ret)
goto error_fail_copy_to_udata;
return &context->ibucontext;
error_fail_copy_to_udata:
hns_roce_uar_free(hr_dev, &context->uar);
error_fail_uar_alloc:
kfree(context);
return ERR_PTR(ret);
}
| 169,504 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unset_and_free_gvalue (gpointer val)
{
g_value_unset (val);
g_free (val);
}
Commit Message:
CWE ID: CWE-264 | unset_and_free_gvalue (gpointer val)
| 165,127 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static size_t ZSTD_encodeSequences(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)
{
#if DYNAMIC_BMI2
if (bmi2) {
return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
#endif
(void)bmi2;
return ZSTD_encodeSequences_default(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
Commit Message: fixed T36302429
CWE ID: CWE-362 | static size_t ZSTD_encodeSequences(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2)
{
DEBUGLOG(5, "ZSTD_encodeSequences: dstCapacity = %u", (unsigned)dstCapacity);
#if DYNAMIC_BMI2
if (bmi2) {
return ZSTD_encodeSequences_bmi2(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
#endif
(void)bmi2;
return ZSTD_encodeSequences_default(dst, dstCapacity,
CTable_MatchLength, mlCodeTable,
CTable_OffsetBits, ofCodeTable,
CTable_LitLength, llCodeTable,
sequences, nbSeq, longOffsets);
}
| 169,673 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: acc_ctx_cont(OM_uint32 *minstat,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 ret, tmpmin;
gss_OID supportedMech;
spnego_gss_ctx_id_t sc;
unsigned int len;
unsigned char *ptr, *bufstart;
sc = (spnego_gss_ctx_id_t)*ctx;
ret = GSS_S_DEFECTIVE_TOKEN;
*negState = REJECT;
*minstat = 0;
supportedMech = GSS_C_NO_OID;
*return_token = ERROR_TOKEN_SEND;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
#define REMAIN (buf->length - (ptr - bufstart))
if (REMAIN > INT_MAX)
return GSS_S_DEFECTIVE_TOKEN;
/*
* Attempt to work with old Sun SPNEGO.
*/
if (*ptr == HEADER_ID) {
ret = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (ret) {
*minstat = ret;
return GSS_S_DEFECTIVE_TOKEN;
}
}
if (*ptr != (CONTEXT | 0x01)) {
return GSS_S_DEFECTIVE_TOKEN;
}
ret = get_negTokenResp(minstat, ptr, REMAIN,
negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (*responseToken == GSS_C_NO_BUFFER &&
*mechListMIC == GSS_C_NO_BUFFER) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
if (supportedMech != GSS_C_NO_OID) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
sc->firstpass = 0;
*negState = ACCEPT_INCOMPLETE;
*return_token = CONT_TOKEN_SEND;
cleanup:
if (supportedMech != GSS_C_NO_OID) {
generic_gss_release_oid(&tmpmin, &supportedMech);
}
return ret;
#undef REMAIN
}
Commit Message: Fix null deref in SPNEGO acceptor [CVE-2014-4344]
When processing a continuation token, acc_ctx_cont was dereferencing
the initial byte of the token without checking the length. This could
result in a null dereference.
CVE-2014-4344:
In MIT krb5 1.5 and newer, an unauthenticated or partially
authenticated remote attacker can cause a NULL dereference and
application crash during a SPNEGO negotiation by sending an empty
token as the second or later context token from initiator to acceptor.
The attacker must provide at least one valid context token in the
security context negotiation before sending the empty token. This can
be done by an unauthenticated attacker by forcing SPNEGO to
renegotiate the underlying mechanism, or by using IAKERB to wrap an
unauthenticated AS-REQ as the first token.
CVSSv2 Vector: AV:N/AC:L/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: CVE summary, CVSSv2 vector]
(cherry picked from commit 524688ce87a15fc75f87efc8c039ba4c7d5c197b)
ticket: 7970
version_fixed: 1.12.2
status: resolved
CWE ID: CWE-476 | acc_ctx_cont(OM_uint32 *minstat,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 ret, tmpmin;
gss_OID supportedMech;
spnego_gss_ctx_id_t sc;
unsigned int len;
unsigned char *ptr, *bufstart;
sc = (spnego_gss_ctx_id_t)*ctx;
ret = GSS_S_DEFECTIVE_TOKEN;
*negState = REJECT;
*minstat = 0;
supportedMech = GSS_C_NO_OID;
*return_token = ERROR_TOKEN_SEND;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
#define REMAIN (buf->length - (ptr - bufstart))
if (REMAIN == 0 || REMAIN > INT_MAX)
return GSS_S_DEFECTIVE_TOKEN;
/*
* Attempt to work with old Sun SPNEGO.
*/
if (*ptr == HEADER_ID) {
ret = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (ret) {
*minstat = ret;
return GSS_S_DEFECTIVE_TOKEN;
}
}
if (*ptr != (CONTEXT | 0x01)) {
return GSS_S_DEFECTIVE_TOKEN;
}
ret = get_negTokenResp(minstat, ptr, REMAIN,
negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (*responseToken == GSS_C_NO_BUFFER &&
*mechListMIC == GSS_C_NO_BUFFER) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
if (supportedMech != GSS_C_NO_OID) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
sc->firstpass = 0;
*negState = ACCEPT_INCOMPLETE;
*return_token = CONT_TOKEN_SEND;
cleanup:
if (supportedMech != GSS_C_NO_OID) {
generic_gss_release_oid(&tmpmin, &supportedMech);
}
return ret;
#undef REMAIN
}
| 166,310 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) {
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
RBuffer *tbuf = r_buf_new ();
r_buf_set_bytes (tbuf, buf, sz);
struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf);
r_buf_free (tbuf);
return res ? res : NULL;
}
Commit Message: Fix #6829 oob write because of using wrong struct
CWE ID: CWE-119 | static void *load_bytes(RBinFile *arch, const ut8 *buf, ut64 sz, ut64 loaddr, Sdb *sdb) {
if (!buf || !sz || sz == UT64_MAX) {
return NULL;
}
RBuffer *tbuf = r_buf_new ();
if (!tbuf) {
return NULL;
}
r_buf_set_bytes (tbuf, buf, sz);
struct r_bin_bflt_obj *res = r_bin_bflt_new_buf (tbuf);
r_buf_free (tbuf);
return res ? res : NULL;
}
| 168,363 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.