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: PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } 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; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, offsetUnset) { char *fname, *error; size_t fname_len; phar_entry_info *entry; PHAR_ARCHIVE_OBJECT(); if (PHAR_G(readonly) && !phar_obj->archive->is_data) { zend_throw_exception_ex(spl_ce_BadMethodCallException, 0, "Write operations disabled by the php.ini setting phar.readonly"); return; } 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; } if (phar_obj->archive->is_persistent) { if (FAILURE == phar_copy_on_write(&(phar_obj->archive))) { zend_throw_exception_ex(phar_ce_PharException, 0, "phar \"%s\" is persistent, unable to copy on write", phar_obj->archive->fname); return; } /* re-populate entry after copy on write */ entry = zend_hash_str_find_ptr(&phar_obj->archive->manifest, fname, (uint) fname_len); } entry->is_modified = 0; entry->is_deleted = 1; /* we need to "flush" the stream to save the newly deleted file on disk */ phar_flush(phar_obj->archive, 0, 0, 0, &error); if (error) { zend_throw_exception_ex(phar_ce_PharException, 0, "%s", error); efree(error); } RETURN_TRUE; } } else { RETURN_FALSE; } }
165,068
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_policy_2_svc(cpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, NULL, NULL)) { ret.code = KADM5_AUTH_ADD; log_unauth("kadm5_create_policy", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_create_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
create_policy_2_svc(cpol_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } prime_arg = arg->rec.policy; if (CHANGEPW_SERVICE(rqstp) || !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD, NULL, NULL)) { ret.code = KADM5_AUTH_ADD; log_unauth("kadm5_create_policy", prime_arg, &client_name, &service_name, rqstp); } else { ret.code = kadm5_create_policy((void *)handle, &arg->rec, arg->mask); if( ret.code != 0 ) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_create_policy", ((prime_arg == NULL) ? "(null)" : prime_arg), errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,508
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(readlink) { char *link; int link_len; char buff[MAXPATHLEN]; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &link, &link_len) == FAILURE) { return; } if (php_check_open_basedir(link TSRMLS_CC)) { RETURN_FALSE; } ret = php_sys_readlink(link, buff, MAXPATHLEN-1); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } /* Append NULL to the end of the string */ buff[ret] = '\0'; RETURN_STRING(buff, 1); } Commit Message: CWE ID: CWE-254
PHP_FUNCTION(readlink) { char *link; int link_len; char buff[MAXPATHLEN]; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p", &link, &link_len) == FAILURE) { return; } if (php_check_open_basedir(link TSRMLS_CC)) { RETURN_FALSE; } ret = php_sys_readlink(link, buff, MAXPATHLEN-1); if (ret == -1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", strerror(errno)); RETURN_FALSE; } /* Append NULL to the end of the string */ buff[ret] = '\0'; RETURN_STRING(buff, 1); }
165,316
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void usage() { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, " by Willem van Schaik, 1999\n"); #ifdef __TURBOC__ fprintf (stderr, " for Turbo-C and Borland-C compilers\n"); #else fprintf (stderr, " for Linux (and Unix) compilers\n"); #endif fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n"); fprintf (stderr, " or: ... | png2pnm [options]\n"); fprintf (stderr, "Options:\n"); fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n"); fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n"); fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n"); fprintf (stderr, " -h | -? print this help-information\n"); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
void usage() { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, " by Willem van Schaik, 1999\n"); #ifdef __TURBOC__ fprintf (stderr, " for Turbo-C and Borland-C compilers\n"); #else fprintf (stderr, " for Linux (and Unix) compilers\n"); #endif fprintf (stderr, "Usage: png2pnm [options] <file>.png [<file>.pnm]\n"); fprintf (stderr, " or: ... | png2pnm [options]\n"); fprintf (stderr, "Options:\n"); fprintf (stderr, " -r[aw] write pnm-file in binary format (P4/P5/P6) (default)\n"); fprintf (stderr, " -n[oraw] write pnm-file in ascii format (P1/P2/P3)\n"); fprintf (stderr, " -a[lpha] <file>.pgm write PNG alpha channel as pgm-file\n"); fprintf (stderr, " -h | -? print this help-information\n"); }
173,724
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); TestNode* imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); } Commit Message: document.location bindings fix BUG=352374 [email protected] Review URL: https://codereview.chromium.org/196343011 git-svn-id: svn://svn.chromium.org/blink/trunk@169176 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
static void locationWithPerWorldBindingsAttributeSetter(v8::Local<v8::Value> jsValue, const v8::PropertyCallbackInfo<void>& info) { TestObjectPython* proxyImp = V8TestObjectPython::toNative(info.Holder()); RefPtr<TestNode> imp = WTF::getPtr(proxyImp->locationWithPerWorldBindings()); if (!imp) return; V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, cppValue, jsValue); imp->setHref(cppValue); }
171,689
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void fht4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { vp9_fht4x4_c(in, out, stride, tx_type); } Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478 DO NOT MERGE - libvpx: Pull from upstream Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06 BUG=23452792 Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec CWE ID: CWE-119
void fht4x4_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { void fht4x4_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { vp9_fht4x4_c(in, out, stride, tx_type); }
174,558
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = wpmd->data; wpc->version_five = 1; // just having this block signals version 5.0 wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0; if (wpc->channel_reordering) { free (wpc->channel_reordering); wpc->channel_reordering = NULL; } if (bytecnt) { wpc->file_format = *byteptr++; wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++; bytecnt -= 2; if (bytecnt) { int nchans, i; wpc->channel_layout = (int32_t) *byteptr++ << 16; bytecnt--; if (bytecnt) { wpc->channel_layout += nchans = *byteptr++; bytecnt--; if (bytecnt) { if (bytecnt > nchans) return FALSE; wpc->channel_reordering = malloc (nchans); if (wpc->channel_reordering) { for (i = 0; i < nchans; ++i) if (bytecnt) { wpc->channel_reordering [i] = *byteptr++; bytecnt--; } else wpc->channel_reordering [i] = i; } } } else wpc->channel_layout += wpc->config.num_channels; } } return TRUE; } Commit Message: fixes for 4 fuzz failures posted to SourceForge mailing list CWE ID: CWE-125
static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd) { int bytecnt = wpmd->byte_length; unsigned char *byteptr = wpmd->data; wpc->version_five = 1; // just having this block signals version 5.0 wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0; if (wpc->channel_reordering) { free (wpc->channel_reordering); wpc->channel_reordering = NULL; } if (bytecnt >= 2) { wpc->file_format = *byteptr++; wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++; bytecnt -= 2; if (bytecnt) { int nchans, i; wpc->channel_layout = (int32_t) *byteptr++ << 16; bytecnt--; if (bytecnt) { wpc->channel_layout += nchans = *byteptr++; bytecnt--; if (bytecnt) { if (bytecnt > nchans) return FALSE; wpc->channel_reordering = malloc (nchans); if (wpc->channel_reordering) { for (i = 0; i < nchans; ++i) if (bytecnt) { wpc->channel_reordering [i] = *byteptr++; if (wpc->channel_reordering [i] >= nchans) // make sure index is in range wpc->channel_reordering [i] = 0; bytecnt--; } else wpc->channel_reordering [i] = i; } } } else wpc->channel_layout += wpc->config.num_channels; } } return TRUE; }
168,507
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void NavigatorImpl::DidFailProvisionalLoadWithError( RenderFrameHostImpl* render_frame_host, const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << render_frame_host->GetRoutingID(); GURL validated_url(params.url); RenderProcessHost* render_process_host = render_frame_host->GetProcess(); render_process_host->FilterURL(false, &validated_url); if (net::ERR_ABORTED == params.error_code) { FrameTreeNode* root = render_frame_host->frame_tree_node()->frame_tree()->root(); if (root->render_manager()->interstitial_page() != NULL) { LOG(WARNING) << "Discarding message during interstitial."; return; } } int expected_pending_entry_id = render_frame_host->navigation_handle() ? render_frame_host->navigation_handle()->pending_nav_entry_id() : 0; DiscardPendingEntryIfNeeded(expected_pending_entry_id); } Commit Message: Don't show current RenderWidgetHostView while interstitial is showing. Also moves interstitial page tracking from RenderFrameHostManager to WebContents, since interstitial pages are not frame-specific. This was necessary for subframes to detect if an interstitial page is showing. BUG=729105 TEST=See comment 13 of bug for repro steps CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation Review-Url: https://codereview.chromium.org/2938313002 Cr-Commit-Position: refs/heads/master@{#480117} CWE ID: CWE-20
void NavigatorImpl::DidFailProvisionalLoadWithError( RenderFrameHostImpl* render_frame_host, const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) { VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec() << ", error_code: " << params.error_code << ", error_description: " << params.error_description << ", showing_repost_interstitial: " << params.showing_repost_interstitial << ", frame_id: " << render_frame_host->GetRoutingID(); GURL validated_url(params.url); RenderProcessHost* render_process_host = render_frame_host->GetProcess(); render_process_host->FilterURL(false, &validated_url); if (net::ERR_ABORTED == params.error_code) { if (delegate_ && delegate_->ShowingInterstitialPage()) { LOG(WARNING) << "Discarding message during interstitial."; return; } } int expected_pending_entry_id = render_frame_host->navigation_handle() ? render_frame_host->navigation_handle()->pending_nav_entry_id() : 0; DiscardPendingEntryIfNeeded(expected_pending_entry_id); }
172,319
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { flush_fp_to_thread(src); flush_altivec_to_thread(src); flush_vsx_to_thread(src); flush_spe_to_thread(src); *dst = *src; clear_task_ebb(dst); return 0; } Commit Message: powerpc/tm: Fix crash when forking inside a transaction When we fork/clone we currently don't copy any of the TM state to the new thread. This results in a TM bad thing (program check) when the new process is switched in as the kernel does a tmrechkpt with TEXASR FS not set. Also, since R1 is from userspace, we trigger the bad kernel stack pointer detection. So we end up with something like this: Bad kernel stack pointer 0 at c0000000000404fc cpu 0x2: Vector: 700 (Program Check) at [c00000003ffefd40] pc: c0000000000404fc: restore_gprs+0xc0/0x148 lr: 0000000000000000 sp: 0 msr: 9000000100201030 current = 0xc000001dd1417c30 paca = 0xc00000000fe00800 softe: 0 irq_happened: 0x01 pid = 0, comm = swapper/2 WARNING: exception is not recoverable, can't continue The below fixes this by flushing the TM state before we copy the task_struct to the clone. To do this we go through the tmreclaim patch, which removes the checkpointed registers from the CPU and transitions the CPU out of TM suspend mode. Hence we need to call tmrechkpt after to restore the checkpointed state and the TM mode for the current task. To make this fail from userspace is simply: tbegin li r0, 2 sc <boom> Kudos to Adhemerval Zanella Neto for finding this. Signed-off-by: Michael Neuling <[email protected]> cc: Adhemerval Zanella Neto <[email protected]> cc: [email protected] Signed-off-by: Benjamin Herrenschmidt <[email protected]> CWE ID: CWE-20
int arch_dup_task_struct(struct task_struct *dst, struct task_struct *src) { flush_fp_to_thread(src); flush_altivec_to_thread(src); flush_vsx_to_thread(src); flush_spe_to_thread(src); /* * Flush TM state out so we can copy it. __switch_to_tm() does this * flush but it removes the checkpointed state from the current CPU and * transitions the CPU out of TM mode. Hence we need to call * tm_recheckpoint_new_task() (on the same task) to restore the * checkpointed state back and the TM mode. */ __switch_to_tm(src); tm_recheckpoint_new_task(src); *dst = *src; clear_task_ebb(dst); return 0; }
166,394
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 hci_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct hci_ufilter uf; struct sock *sk = sock->sk; int len, opt, err = 0; BT_DBG("sk %p, opt %d", sk, optname); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) { err = -EINVAL; goto done; } switch (optname) { case HCI_DATA_DIR: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_DIR) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_TIME_STAMP: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_TSTAMP) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_FILTER: { struct hci_filter *f = &hci_pi(sk)->filter; uf.type_mask = f->type_mask; uf.opcode = f->opcode; uf.event_mask[0] = *((u32 *) f->event_mask + 0); uf.event_mask[1] = *((u32 *) f->event_mask + 1); } len = min_t(unsigned int, len, sizeof(uf)); if (copy_to_user(optval, &uf, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } done: release_sock(sk); return err; } Commit Message: Bluetooth: HCI - Fix info leak in getsockopt(HCI_FILTER) The HCI code fails to initialize the two padding bytes of struct hci_ufilter before copying it to userland -- that for leaking two bytes kernel stack. Add an explicit memset(0) before filling the structure to avoid the info leak. Signed-off-by: Mathias Krause <[email protected]> Cc: Marcel Holtmann <[email protected]> Cc: Gustavo Padovan <[email protected]> Cc: Johan Hedberg <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int hci_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct hci_ufilter uf; struct sock *sk = sock->sk; int len, opt, err = 0; BT_DBG("sk %p, opt %d", sk, optname); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) { err = -EINVAL; goto done; } switch (optname) { case HCI_DATA_DIR: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_DIR) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_TIME_STAMP: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_TSTAMP) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_FILTER: { struct hci_filter *f = &hci_pi(sk)->filter; memset(&uf, 0, sizeof(uf)); uf.type_mask = f->type_mask; uf.opcode = f->opcode; uf.event_mask[0] = *((u32 *) f->event_mask + 0); uf.event_mask[1] = *((u32 *) f->event_mask + 1); } len = min_t(unsigned int, len, sizeof(uf)); if (copy_to_user(optval, &uf, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } done: release_sock(sk); return err; }
166,182
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int hashtable_init(hashtable_t *hashtable) { size_t i; hashtable->size = 0; hashtable->num_buckets = 0; /* index to primes[] */ hashtable->buckets = jsonp_malloc(num_buckets(hashtable) * sizeof(bucket_t)); if(!hashtable->buckets) return -1; list_init(&hashtable->list); for(i = 0; i < num_buckets(hashtable); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } return 0; } Commit Message: CVE-2013-6401: Change hash function, randomize hashes Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing and testing. CWE ID: CWE-310
int hashtable_init(hashtable_t *hashtable) { size_t i; hashtable->size = 0; hashtable->order = 3; hashtable->buckets = jsonp_malloc(hashsize(hashtable->order) * sizeof(bucket_t)); if(!hashtable->buckets) return -1; list_init(&hashtable->list); for(i = 0; i < hashsize(hashtable->order); i++) { hashtable->buckets[i].first = hashtable->buckets[i].last = &hashtable->list; } return 0; }
166,531
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: ProcXFixesSetCursorName(ClientPtr client) { CursorPtr pCursor; char *tchar; REQUEST(xXFixesSetCursorNameReq); REQUEST(xXFixesSetCursorNameReq); Atom atom; REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq); VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); tchar = (char *) &stuff[1]; atom = MakeAtom(tchar, stuff->nbytes, TRUE); return BadAlloc; pCursor->name = atom; return Success; } Commit Message: CWE ID: CWE-20
ProcXFixesSetCursorName(ClientPtr client) { CursorPtr pCursor; char *tchar; REQUEST(xXFixesSetCursorNameReq); REQUEST(xXFixesSetCursorNameReq); Atom atom; REQUEST_FIXED_SIZE(xXFixesSetCursorNameReq, stuff->nbytes); VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); tchar = (char *) &stuff[1]; atom = MakeAtom(tchar, stuff->nbytes, TRUE); return BadAlloc; pCursor->name = atom; return Success; }
165,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 int mpage_da_map_blocks(struct mpage_da_data *mpd) { int err, blks, get_blocks_flags; struct buffer_head new; sector_t next = mpd->b_blocknr; unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits; loff_t disksize = EXT4_I(mpd->inode)->i_disksize; handle_t *handle = NULL; /* * We consider only non-mapped and non-allocated blocks */ if ((mpd->b_state & (1 << BH_Mapped)) && !(mpd->b_state & (1 << BH_Delay)) && !(mpd->b_state & (1 << BH_Unwritten))) return 0; /* * If we didn't accumulate anything to write simply return */ if (!mpd->b_size) return 0; handle = ext4_journal_current_handle(); BUG_ON(!handle); /* * Call ext4_get_blocks() to allocate any delayed allocation * blocks, or to convert an uninitialized extent to be * initialized (in the case where we have written into * one or more preallocated blocks). * * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to * indicate that we are on the delayed allocation path. This * affects functions in many different parts of the allocation * call path. This flag exists primarily because we don't * want to change *many* call functions, so ext4_get_blocks() * will set the magic i_delalloc_reserved_flag once the * inode's allocation semaphore is taken. * * If the blocks in questions were delalloc blocks, set * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting * variables are updated after the blocks have been allocated. */ new.b_state = 0; get_blocks_flags = EXT4_GET_BLOCKS_CREATE; if (mpd->b_state & (1 << BH_Delay)) get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks, &new, get_blocks_flags); if (blks < 0) { err = blks; /* * If get block returns with error we simply * return. Later writepage will redirty the page and * writepages will find the dirty page again */ if (err == -EAGAIN) return 0; if (err == -ENOSPC && ext4_count_free_blocks(mpd->inode->i_sb)) { mpd->retval = err; return 0; } /* * get block failure will cause us to loop in * writepages, because a_ops->writepage won't be able * to make progress. The page will be redirtied by * writepage and writepages will again try to write * the same. */ ext4_msg(mpd->inode->i_sb, KERN_CRIT, "delayed block allocation failed for inode %lu at " "logical offset %llu with max blocks %zd with " "error %d\n", mpd->inode->i_ino, (unsigned long long) next, mpd->b_size >> mpd->inode->i_blkbits, err); printk(KERN_CRIT "This should not happen!! " "Data will be lost\n"); if (err == -ENOSPC) { ext4_print_free_blocks(mpd->inode); } /* invalidate all the pages */ ext4_da_block_invalidatepages(mpd, next, mpd->b_size >> mpd->inode->i_blkbits); return err; } BUG_ON(blks == 0); new.b_size = (blks << mpd->inode->i_blkbits); if (buffer_new(&new)) __unmap_underlying_blocks(mpd->inode, &new); /* * If blocks are delayed marked, we need to * put actual blocknr and drop delayed bit */ if ((mpd->b_state & (1 << BH_Delay)) || (mpd->b_state & (1 << BH_Unwritten))) mpage_put_bnr_to_bhs(mpd, next, &new); if (ext4_should_order_data(mpd->inode)) { err = ext4_jbd2_file_inode(handle, mpd->inode); if (err) return err; } /* * Update on-disk size along with block allocation. */ disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits; if (disksize > i_size_read(mpd->inode)) disksize = i_size_read(mpd->inode); if (disksize > EXT4_I(mpd->inode)->i_disksize) { ext4_update_i_disksize(mpd->inode, disksize); return ext4_mark_inode_dirty(handle, mpd->inode); } return 0; } Commit Message: ext4: use ext4_get_block_write in buffer write Allocate uninitialized extent before ext4 buffer write and convert the extent to initialized after io completes. The purpose is to make sure an extent can only be marked initialized after it has been written with new data so we can safely drop the i_mutex lock in ext4 DIO read without exposing stale data. This helps to improve multi-thread DIO read performance on high-speed disks. Skip the nobh and data=journal mount cases to make things simple for now. Signed-off-by: Jiaying Zhang <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> CWE ID:
static int mpage_da_map_blocks(struct mpage_da_data *mpd) { int err, blks, get_blocks_flags; struct buffer_head new; sector_t next = mpd->b_blocknr; unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits; loff_t disksize = EXT4_I(mpd->inode)->i_disksize; handle_t *handle = NULL; /* * We consider only non-mapped and non-allocated blocks */ if ((mpd->b_state & (1 << BH_Mapped)) && !(mpd->b_state & (1 << BH_Delay)) && !(mpd->b_state & (1 << BH_Unwritten))) return 0; /* * If we didn't accumulate anything to write simply return */ if (!mpd->b_size) return 0; handle = ext4_journal_current_handle(); BUG_ON(!handle); /* * Call ext4_get_blocks() to allocate any delayed allocation * blocks, or to convert an uninitialized extent to be * initialized (in the case where we have written into * one or more preallocated blocks). * * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to * indicate that we are on the delayed allocation path. This * affects functions in many different parts of the allocation * call path. This flag exists primarily because we don't * want to change *many* call functions, so ext4_get_blocks() * will set the magic i_delalloc_reserved_flag once the * inode's allocation semaphore is taken. * * If the blocks in questions were delalloc blocks, set * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting * variables are updated after the blocks have been allocated. */ new.b_state = 0; get_blocks_flags = EXT4_GET_BLOCKS_CREATE; if (ext4_should_dioread_nolock(mpd->inode)) get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT; if (mpd->b_state & (1 << BH_Delay)) get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks, &new, get_blocks_flags); if (blks < 0) { err = blks; /* * If get block returns with error we simply * return. Later writepage will redirty the page and * writepages will find the dirty page again */ if (err == -EAGAIN) return 0; if (err == -ENOSPC && ext4_count_free_blocks(mpd->inode->i_sb)) { mpd->retval = err; return 0; } /* * get block failure will cause us to loop in * writepages, because a_ops->writepage won't be able * to make progress. The page will be redirtied by * writepage and writepages will again try to write * the same. */ ext4_msg(mpd->inode->i_sb, KERN_CRIT, "delayed block allocation failed for inode %lu at " "logical offset %llu with max blocks %zd with " "error %d\n", mpd->inode->i_ino, (unsigned long long) next, mpd->b_size >> mpd->inode->i_blkbits, err); printk(KERN_CRIT "This should not happen!! " "Data will be lost\n"); if (err == -ENOSPC) { ext4_print_free_blocks(mpd->inode); } /* invalidate all the pages */ ext4_da_block_invalidatepages(mpd, next, mpd->b_size >> mpd->inode->i_blkbits); return err; } BUG_ON(blks == 0); new.b_size = (blks << mpd->inode->i_blkbits); if (buffer_new(&new)) __unmap_underlying_blocks(mpd->inode, &new); /* * If blocks are delayed marked, we need to * put actual blocknr and drop delayed bit */ if ((mpd->b_state & (1 << BH_Delay)) || (mpd->b_state & (1 << BH_Unwritten))) mpage_put_bnr_to_bhs(mpd, next, &new); if (ext4_should_order_data(mpd->inode)) { err = ext4_jbd2_file_inode(handle, mpd->inode); if (err) return err; } /* * Update on-disk size along with block allocation. */ disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits; if (disksize > i_size_read(mpd->inode)) disksize = i_size_read(mpd->inode); if (disksize > EXT4_I(mpd->inode)->i_disksize) { ext4_update_i_disksize(mpd->inode, disksize); return ext4_mark_inode_dirty(handle, mpd->inode); } return 0; }
167,551
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FileMetricsProviderTest() : create_large_files_(GetParam()), task_runner_(new base::TestSimpleTaskRunner()), thread_task_runner_handle_(task_runner_), statistics_recorder_( base::StatisticsRecorder::CreateTemporaryForTesting()), prefs_(new TestingPrefServiceSimple) { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName); FileMetricsProvider::SetTaskRunnerForTesting(task_runner_); base::GlobalHistogramAllocator::GetCreateHistogramResultHistogram(); } Commit Message: Remove UMA.CreatePersistentHistogram.Result This histogram isn't showing anything meaningful and the problems it could show are better observed by looking at the allocators directly. Bug: 831013 Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9 Reviewed-on: https://chromium-review.googlesource.com/1008047 Commit-Queue: Brian White <[email protected]> Reviewed-by: Alexei Svitkine <[email protected]> Cr-Commit-Position: refs/heads/master@{#549986} CWE ID: CWE-264
FileMetricsProviderTest() : create_large_files_(GetParam()), task_runner_(new base::TestSimpleTaskRunner()), thread_task_runner_handle_(task_runner_), statistics_recorder_( base::StatisticsRecorder::CreateTemporaryForTesting()), prefs_(new TestingPrefServiceSimple) { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); FileMetricsProvider::RegisterPrefs(prefs_->registry(), kMetricsName); FileMetricsProvider::SetTaskRunnerForTesting(task_runner_); }
172,141
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 snd_timer_user_ccallback(struct snd_timer_instance *timeri, int event, struct timespec *tstamp, unsigned long resolution) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread r1; unsigned long flags; if (event >= SNDRV_TIMER_EVENT_START && event <= SNDRV_TIMER_EVENT_PAUSE) tu->tstamp = *tstamp; if ((tu->filter & (1 << event)) == 0 || !tu->tread) return; r1.event = event; r1.tstamp = *tstamp; r1.val = resolution; spin_lock_irqsave(&tu->qlock, flags); snd_timer_user_append_to_tqueue(tu, &r1); spin_unlock_irqrestore(&tu->qlock, flags); kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); } Commit Message: ALSA: timer: Fix leak in events via snd_timer_user_ccallback The stack object “r1” has a total size of 32 bytes. Its field “event” and “val” both contain 4 bytes padding. These 8 bytes padding bytes are sent to user without being initialized. Signed-off-by: Kangjie Lu <[email protected]> Signed-off-by: Takashi Iwai <[email protected]> CWE ID: CWE-200
static void snd_timer_user_ccallback(struct snd_timer_instance *timeri, int event, struct timespec *tstamp, unsigned long resolution) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread r1; unsigned long flags; if (event >= SNDRV_TIMER_EVENT_START && event <= SNDRV_TIMER_EVENT_PAUSE) tu->tstamp = *tstamp; if ((tu->filter & (1 << event)) == 0 || !tu->tread) return; memset(&r1, 0, sizeof(r1)); r1.event = event; r1.tstamp = *tstamp; r1.val = resolution; spin_lock_irqsave(&tu->qlock, flags); snd_timer_user_append_to_tqueue(tu, &r1); spin_unlock_irqrestore(&tu->qlock, flags); kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); }
169,969
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 send_reply_chunks(struct svcxprt_rdma *xprt, struct rpcrdma_write_array *rp_ary, struct rpcrdma_msg *rdma_resp, struct svc_rqst *rqstp, struct svc_rdma_req_map *vec) { u32 xfer_len = rqstp->rq_res.len; int write_len; u32 xdr_off; int chunk_no; int chunk_off; int nchunks; struct rpcrdma_segment *ch; struct rpcrdma_write_array *res_ary; int ret; /* XXX: need to fix when reply lists occur with read-list and or * write-list */ res_ary = (struct rpcrdma_write_array *) &rdma_resp->rm_body.rm_chunks[2]; /* xdr offset starts at RPC message */ nchunks = be32_to_cpu(rp_ary->wc_nchunks); for (xdr_off = 0, chunk_no = 0; xfer_len && chunk_no < nchunks; chunk_no++) { u64 rs_offset; ch = &rp_ary->wc_array[chunk_no].wc_target; write_len = min(xfer_len, be32_to_cpu(ch->rs_length)); /* Prepare the reply chunk given the length actually * written */ xdr_decode_hyper((__be32 *)&ch->rs_offset, &rs_offset); svc_rdma_xdr_encode_array_chunk(res_ary, chunk_no, ch->rs_handle, ch->rs_offset, write_len); chunk_off = 0; while (write_len) { ret = send_write(xprt, rqstp, be32_to_cpu(ch->rs_handle), rs_offset + chunk_off, xdr_off, write_len, vec); if (ret <= 0) goto out_err; chunk_off += ret; xdr_off += ret; xfer_len -= ret; write_len -= ret; } } /* Update the req with the number of chunks actually used */ svc_rdma_xdr_encode_reply_array(res_ary, chunk_no); return rqstp->rq_res.len; out_err: pr_err("svcrdma: failed to send reply chunks, rc=%d\n", ret); return -EIO; } Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux Pull nfsd updates from Bruce Fields: "Another RDMA update from Chuck Lever, and a bunch of miscellaneous bugfixes" * tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits) nfsd: Fix up the "supattr_exclcreat" attributes nfsd: encoders mustn't use unitialized values in error cases nfsd: fix undefined behavior in nfsd4_layout_verify lockd: fix lockd shutdown race NFSv4: Fix callback server shutdown SUNRPC: Refactor svc_set_num_threads() NFSv4.x/callback: Create the callback service through svc_create_pooled lockd: remove redundant check on block svcrdma: Clean out old XDR encoders svcrdma: Remove the req_map cache svcrdma: Remove unused RDMA Write completion handler svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt svcrdma: Clean up RPC-over-RDMA backchannel reply processing svcrdma: Report Write/Reply chunk overruns svcrdma: Clean up RDMA_ERROR path svcrdma: Use rdma_rw API in RPC reply path svcrdma: Introduce local rdma_rw API helpers svcrdma: Clean up svc_rdma_get_inv_rkey() svcrdma: Add helper to save pages under I/O svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT ... CWE ID: CWE-404
static int send_reply_chunks(struct svcxprt_rdma *xprt, /* The svc_rqst and all resources it owns are released as soon as * svc_rdma_sendto returns. Transfer pages under I/O to the ctxt * so they are released by the Send completion handler. */ static void svc_rdma_save_io_pages(struct svc_rqst *rqstp, struct svc_rdma_op_ctxt *ctxt) { int i, pages = rqstp->rq_next_page - rqstp->rq_respages; ctxt->count += pages; for (i = 0; i < pages; i++) { ctxt->pages[i + 1] = rqstp->rq_respages[i]; rqstp->rq_respages[i] = NULL; } rqstp->rq_next_page = rqstp->rq_respages + 1; } /** * svc_rdma_post_send_wr - Set up and post one Send Work Request * @rdma: controlling transport * @ctxt: op_ctxt for transmitting the Send WR * @num_sge: number of SGEs to send * @inv_rkey: R_key argument to Send With Invalidate, or zero * * Returns: * %0 if the Send* was posted successfully, * %-ENOTCONN if the connection was lost or dropped, * %-EINVAL if there was a problem with the Send we built, * %-ENOMEM if ib_post_send failed. */ int svc_rdma_post_send_wr(struct svcxprt_rdma *rdma, struct svc_rdma_op_ctxt *ctxt, int num_sge, u32 inv_rkey) { struct ib_send_wr *send_wr = &ctxt->send_wr; dprintk("svcrdma: posting Send WR with %u sge(s)\n", num_sge); send_wr->next = NULL; ctxt->cqe.done = svc_rdma_wc_send; send_wr->wr_cqe = &ctxt->cqe; send_wr->sg_list = ctxt->sge; send_wr->num_sge = num_sge; send_wr->send_flags = IB_SEND_SIGNALED; if (inv_rkey) { send_wr->opcode = IB_WR_SEND_WITH_INV; send_wr->ex.invalidate_rkey = inv_rkey; } else { send_wr->opcode = IB_WR_SEND; } return svc_rdma_send(rdma, send_wr); }
168,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: void MediaElementAudioSourceHandler::OnCurrentSrcChanged( const KURL& current_src) { DCHECK(IsMainThread()); Locker<MediaElementAudioSourceHandler> locker(*this); passes_current_src_cors_access_check_ = PassesCurrentSrcCORSAccessCheck(current_src); maybe_print_cors_message_ = !passes_current_src_cors_access_check_; current_src_string_ = current_src.GetString(); } Commit Message: Redirect should not circumvent same-origin restrictions Check whether we have access to the audio data when the format is set. At this point we have enough information to determine this. The old approach based on when the src was changed was incorrect because at the point, we only know the new src; none of the response headers have been read yet. This new approach also removes the incorrect message reported in 619114. Bug: 826552, 619114 Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6 Reviewed-on: https://chromium-review.googlesource.com/1069540 Commit-Queue: Raymond Toy <[email protected]> Reviewed-by: Yutaka Hirano <[email protected]> Reviewed-by: Hongchan Choi <[email protected]> Cr-Commit-Position: refs/heads/master@{#564313} CWE ID: CWE-20
void MediaElementAudioSourceHandler::OnCurrentSrcChanged( bool MediaElementAudioSourceHandler::WouldTaintOrigin() { // If we're cross-origin and allowed access vie CORS, we're not tainted. if (MediaElement()->GetWebMediaPlayer()->DidPassCORSAccessCheck()) { return false; } // Handles the case where the url is a redirect to another site that we're not // allowed to access. if (!MediaElement()->HasSingleSecurityOrigin()) { return true; }
173,145
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); add_next_index_stringl(return_value, "MD5", 3, 1); add_next_index_stringl(return_value, "SHA-1", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, "SHA-256", 7, 1); add_next_index_stringl(return_value, "SHA-512", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7, 1); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { add_next_index_stringl(return_value, "OpenSSL", 7, 1); } #endif } Commit Message: CWE ID: CWE-20
PHP_METHOD(Phar, getSupportedSignatures) { if (zend_parse_parameters_none() == FAILURE) { return; } array_init(return_value); add_next_index_stringl(return_value, "MD5", 3, 1); add_next_index_stringl(return_value, "SHA-1", 5, 1); #ifdef PHAR_HASH_OK add_next_index_stringl(return_value, "SHA-256", 7, 1); add_next_index_stringl(return_value, "SHA-512", 7, 1); #endif #if PHAR_HAVE_OPENSSL add_next_index_stringl(return_value, "OpenSSL", 7, 1); #else if (zend_hash_exists(&module_registry, "openssl", sizeof("openssl"))) { add_next_index_stringl(return_value, "OpenSSL", 7, 1); } #endif }
165,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 process_constructors (RBinFile *bf, RList *ret, int bits) { RList *secs = sections (bf); RListIter *iter; RBinSection *sec; int i, type; r_list_foreach (secs, iter, sec) { type = -1; if (!strcmp (sec->name, ".fini_array")) { type = R_BIN_ENTRY_TYPE_FINI; } else if (!strcmp (sec->name, ".init_array")) { type = R_BIN_ENTRY_TYPE_INIT; } else if (!strcmp (sec->name, ".preinit_array")) { type = R_BIN_ENTRY_TYPE_PREINIT; } if (type != -1) { ut8 *buf = calloc (sec->size, 1); if (!buf) { continue; } (void)r_buf_read_at (bf->buf, sec->paddr, buf, sec->size); if (bits == 32) { for (i = 0; i < sec->size; i += 4) { ut32 addr32 = r_read_le32 (buf + i); if (addr32) { RBinAddr *ba = newEntry (sec->paddr + i, (ut64)addr32, type, bits); r_list_append (ret, ba); } } } else { for (i = 0; i < sec->size; i += 8) { ut64 addr64 = r_read_le64 (buf + i); if (addr64) { RBinAddr *ba = newEntry (sec->paddr + i, addr64, type, bits); r_list_append (ret, ba); } } } free (buf); } } r_list_free (secs); } Commit Message: Fix #9904 - crash in r2_hoobr_r_read_le32 (over 9000 entrypoints) and read_le oobread (#9923) CWE ID: CWE-125
static void process_constructors (RBinFile *bf, RList *ret, int bits) { RList *secs = sections (bf); RListIter *iter; RBinSection *sec; int i, type; r_list_foreach (secs, iter, sec) { type = -1; if (!strcmp (sec->name, ".fini_array")) { type = R_BIN_ENTRY_TYPE_FINI; } else if (!strcmp (sec->name, ".init_array")) { type = R_BIN_ENTRY_TYPE_INIT; } else if (!strcmp (sec->name, ".preinit_array")) { type = R_BIN_ENTRY_TYPE_PREINIT; } if (type != -1) { ut8 *buf = calloc (sec->size, 1); if (!buf) { continue; } (void)r_buf_read_at (bf->buf, sec->paddr, buf, sec->size); if (bits == 32) { for (i = 0; (i + 3) < sec->size; i += 4) { ut32 addr32 = r_read_le32 (buf + i); if (addr32) { RBinAddr *ba = newEntry (sec->paddr + i, (ut64)addr32, type, bits); r_list_append (ret, ba); } } } else { for (i = 0; (i + 7) < sec->size; i += 8) { ut64 addr64 = r_read_le64 (buf + i); if (addr64) { RBinAddr *ba = newEntry (sec->paddr + i, addr64, type, bits); r_list_append (ret, ba); } } } free (buf); } } r_list_free (secs); }
169,232
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context) { int i; UINT32 length; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ length = tempWidth * tempHeight + 16; if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) { BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length); if (!tmp) goto fail; context->priv->PlaneBuffers[i] = tmp; } context->priv->PlaneBuffersLength = length; } if (context->ChromaSubsamplingLevel) { context->OrgByteCount[0] = tempWidth * context->height; context->OrgByteCount[1] = tempWidth * tempHeight / 4; context->OrgByteCount[2] = tempWidth * tempHeight / 4; context->OrgByteCount[3] = context->width * context->height; } else { context->OrgByteCount[0] = context->width * context->height; context->OrgByteCount[1] = context->width * context->height; context->OrgByteCount[2] = context->width * context->height; context->OrgByteCount[3] = context->width * context->height; } return TRUE; fail: if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) free(context->priv->PlaneBuffers[i]); } return FALSE; } Commit Message: Fixed CVE-2018-8788 Thanks to Eyal Itkin from Check Point Software Technologies. CWE ID: CWE-787
static BOOL nsc_context_initialize_encode(NSC_CONTEXT* context) { int i; UINT32 length; UINT32 tempWidth; UINT32 tempHeight; tempWidth = ROUND_UP_TO(context->width, 8); tempHeight = ROUND_UP_TO(context->height, 2); /* The maximum length a decoded plane can reach in all cases */ length = tempWidth * tempHeight + 16; if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) { BYTE* tmp = (BYTE*) realloc(context->priv->PlaneBuffers[i], length); if (!tmp) goto fail; context->priv->PlaneBuffers[i] = tmp; } context->priv->PlaneBuffersLength = length; } if (context->ChromaSubsamplingLevel) { context->OrgByteCount[0] = tempWidth * context->height; context->OrgByteCount[1] = tempWidth * tempHeight / 4; context->OrgByteCount[2] = tempWidth * tempHeight / 4; context->OrgByteCount[3] = context->width * context->height; } else { context->OrgByteCount[0] = context->width * context->height; context->OrgByteCount[1] = context->width * context->height; context->OrgByteCount[2] = context->width * context->height; context->OrgByteCount[3] = context->width * context->height; } return TRUE; fail: if (length > context->priv->PlaneBuffersLength) { for (i = 0; i < 5; i++) free(context->priv->PlaneBuffers[i]); } return FALSE; }
169,286
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { ND_TCHECK2(*tptr, 4); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); } Commit Message: CVE-2017-13055/IS-IS: fix an Extended IS Reachability sub-TLV In isis_print_is_reach_subtlv() one of the case blocks did not check that the sub-TLV "V" is actually present and could over-read the input buffer. Add a length check to fix that and remove a useless boundary check from a loop because the boundary is tested for the full length of "V" before the switch block. Update one of the prior test cases as it turns out it depended on this previously incorrect code path to make it to its own malformed structure further down the buffer, the bugfix has changed its output. This fixes a buffer over-read discovered by Bhargava Shastry, SecT/TU Berlin. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
isis_print_is_reach_subtlv(netdissect_options *ndo, const uint8_t *tptr, u_int subt, u_int subl, const char *ident) { u_int te_class,priority_level,gmpls_switch_cap; union { /* int to float conversion buffer for several subTLVs */ float f; uint32_t i; } bw; /* first lets see if we know the subTLVs name*/ ND_PRINT((ndo, "%s%s subTLV #%u, length: %u", ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt), subt, subl)); ND_TCHECK2(*tptr, subl); switch(subt) { case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: if (subl >= 4) { ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr))); if (subl == 8) /* rfc4205 */ ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4))); } break; case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: if (subl >= sizeof(struct in_addr)) ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: if (subl >= 4) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000)); } break; case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : if (subl >= 32) { for (te_class = 0; te_class < 8; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } } break; case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: if (subl == 0) break; ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)", ident, tok2str(diffserv_te_bc_values, "unknown", *tptr), *tptr)); tptr++; /* decode BCs until the subTLV ends */ for (te_class = 0; te_class < (subl-1)/4; te_class++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps", ident, te_class, bw.f * 8 / 1000000)); tptr+=4; } break; case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: if (subl >= 3) ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr))); break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: if (subl == 2) { ND_PRINT((ndo, ", [ %s ] (0x%04x)", bittok2str(isis_subtlv_link_attribute_values, "Unknown", EXTRACT_16BITS(tptr)), EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: if (subl >= 2) { ND_PRINT((ndo, ", %s, Priority %u", bittok2str(gmpls_link_prot_values, "none", *tptr), *(tptr+1))); } break; case ISIS_SUBTLV_SPB_METRIC: if (subl >= 6) { ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr))); tptr=tptr+3; ND_PRINT((ndo, ", P: %u", *(tptr))); tptr++; ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr))); } break; case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: if (subl >= 36) { gmpls_switch_cap = *tptr; ND_PRINT((ndo, "%s Interface Switching Capability:%s", ident, tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap))); ND_PRINT((ndo, ", LSP Encoding: %s", tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1)))); tptr+=4; ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident)); for (priority_level = 0; priority_level < 8; priority_level++) { bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s priority level %d: %.3f Mbps", ident, priority_level, bw.f * 8 / 1000000)); tptr+=4; } subl-=36; switch (gmpls_switch_cap) { case GMPLS_PSC1: case GMPLS_PSC2: case GMPLS_PSC3: case GMPLS_PSC4: ND_TCHECK2(*tptr, 6); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4))); break; case GMPLS_TSC: ND_TCHECK2(*tptr, 8); bw.i = EXTRACT_32BITS(tptr); ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000)); ND_PRINT((ndo, "%s Indication %s", ident, tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4)))); break; default: /* there is some optional stuff left to decode but this is as of yet not specified so just lets hexdump what is left */ if(subl>0){ if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); } } } break; default: if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl)) return(0); break; } return(1); trunc: return(0); }
167,818
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int main(int argc, char *argv[] ) { int i, fails_count=0; CU_pSuite cryptoUtilsTestSuite, parserTestSuite; CU_pSuite *suites[] = { &cryptoUtilsTestSuite, &parserTestSuite, NULL }; if (argc>1) { if (argv[1][0] == '-') { if (strcmp(argv[1], "-verbose") == 0) { verbose = 1; } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } #ifdef HAVE_LIBXML2 xmlInitParser(); #endif /* initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } /* Add the cryptoUtils suite to the registry */ cryptoUtilsTestSuite = CU_add_suite("Bzrtp Crypto Utils", NULL, NULL); CU_add_test(cryptoUtilsTestSuite, "zrtpKDF", test_zrtpKDF); CU_add_test(cryptoUtilsTestSuite, "CRC32", test_CRC32); CU_add_test(cryptoUtilsTestSuite, "algo agreement", test_algoAgreement); CU_add_test(cryptoUtilsTestSuite, "context algo setter and getter", test_algoSetterGetter); CU_add_test(cryptoUtilsTestSuite, "adding mandatory crypto algorithms if needed", test_addMandatoryCryptoTypesIfNeeded); /* Add the parser suite to the registry */ parserTestSuite = CU_add_suite("Bzrtp ZRTP Packet Parser", NULL, NULL); CU_add_test(parserTestSuite, "Parse", test_parser); CU_add_test(parserTestSuite, "Parse Exchange", test_parserComplete); CU_add_test(parserTestSuite, "State machine", test_stateMachine); /* Run all suites */ for(i=0; suites[i]; i++){ CU_basic_run_suite(*suites[i]); fails_count += CU_get_number_of_tests_failed(); } /* cleanup the CUnit registry */ CU_cleanup_registry(); #ifdef HAVE_LIBXML2 /* cleanup libxml2 */ xmlCleanupParser(); #endif return (fails_count == 0 ? 0 : 1); } Commit Message: Add ZRTP Commit packet hvi check on DHPart2 packet reception CWE ID: CWE-254
int main(int argc, char *argv[] ) { int i, fails_count=0; CU_pSuite cryptoUtilsTestSuite, parserTestSuite; CU_pSuite *suites[] = { &cryptoUtilsTestSuite, &parserTestSuite, NULL }; if (argc>1) { if (argv[1][0] == '-') { if (strcmp(argv[1], "-verbose") == 0) { verbose = 1; } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } else { printf ("Usage:\n %s [-verbose] to enable extensive logging\n", argv[0]); return 1; } } #ifdef HAVE_LIBXML2 xmlInitParser(); #endif /* initialize the CUnit test registry */ if (CUE_SUCCESS != CU_initialize_registry()) { return CU_get_error(); } /* Add the cryptoUtils suite to the registry */ cryptoUtilsTestSuite = CU_add_suite("Bzrtp Crypto Utils", NULL, NULL); CU_add_test(cryptoUtilsTestSuite, "zrtpKDF", test_zrtpKDF); CU_add_test(cryptoUtilsTestSuite, "CRC32", test_CRC32); CU_add_test(cryptoUtilsTestSuite, "algo agreement", test_algoAgreement); CU_add_test(cryptoUtilsTestSuite, "context algo setter and getter", test_algoSetterGetter); CU_add_test(cryptoUtilsTestSuite, "adding mandatory crypto algorithms if needed", test_addMandatoryCryptoTypesIfNeeded); /* Add the parser suite to the registry */ parserTestSuite = CU_add_suite("Bzrtp ZRTP Packet Parser", NULL, NULL); CU_add_test(parserTestSuite, "Parse", test_parser); CU_add_test(parserTestSuite, "Parse hvi check fail", test_parser_hvi); CU_add_test(parserTestSuite, "Parse Exchange", test_parserComplete); CU_add_test(parserTestSuite, "State machine", test_stateMachine); /* Run all suites */ for(i=0; suites[i]; i++){ CU_basic_run_suite(*suites[i]); fails_count += CU_get_number_of_tests_failed(); } /* cleanup the CUnit registry */ CU_cleanup_registry(); #ifdef HAVE_LIBXML2 /* cleanup libxml2 */ xmlCleanupParser(); #endif return (fails_count == 0 ? 0 : 1); }
168,830
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct perf_event *event = file->private_data; void (*func)(struct perf_event *); u32 flags = arg; switch (cmd) { case PERF_EVENT_IOC_ENABLE: func = perf_event_enable; break; case PERF_EVENT_IOC_DISABLE: func = perf_event_disable; break; case PERF_EVENT_IOC_RESET: func = perf_event_reset; break; case PERF_EVENT_IOC_REFRESH: return perf_event_refresh(event, arg); case PERF_EVENT_IOC_PERIOD: return perf_event_period(event, (u64 __user *)arg); case PERF_EVENT_IOC_ID: { u64 id = primary_event_id(event); if (copy_to_user((void __user *)arg, &id, sizeof(id))) return -EFAULT; return 0; } case PERF_EVENT_IOC_SET_OUTPUT: { int ret; if (arg != -1) { struct perf_event *output_event; struct fd output; ret = perf_fget_light(arg, &output); if (ret) return ret; output_event = output.file->private_data; ret = perf_event_set_output(event, output_event); fdput(output); } else { ret = perf_event_set_output(event, NULL); } return ret; } case PERF_EVENT_IOC_SET_FILTER: return perf_event_set_filter(event, (void __user *)arg); default: return -ENOTTY; } if (flags & PERF_IOC_FLAG_GROUP) perf_event_for_each(event, func); else perf_event_for_each_child(event, func); return 0; } Commit Message: perf: Fix event->ctx locking There have been a few reported issues wrt. the lack of locking around changing event->ctx. This patch tries to address those. It avoids the whole rwsem thing; and while it appears to work, please give it some thought in review. What I did fail at is sensible runtime checks on the use of event->ctx, the RCU use makes it very hard. Signed-off-by: Peter Zijlstra (Intel) <[email protected]> Cc: Paul E. McKenney <[email protected]> Cc: Jiri Olsa <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Cc: Linus Torvalds <[email protected]> Link: http://lkml.kernel.org/r/[email protected] Signed-off-by: Ingo Molnar <[email protected]> CWE ID: CWE-264
static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg) { void (*func)(struct perf_event *); u32 flags = arg; switch (cmd) { case PERF_EVENT_IOC_ENABLE: func = _perf_event_enable; break; case PERF_EVENT_IOC_DISABLE: func = _perf_event_disable; break; case PERF_EVENT_IOC_RESET: func = _perf_event_reset; break; case PERF_EVENT_IOC_REFRESH: return _perf_event_refresh(event, arg); case PERF_EVENT_IOC_PERIOD: return perf_event_period(event, (u64 __user *)arg); case PERF_EVENT_IOC_ID: { u64 id = primary_event_id(event); if (copy_to_user((void __user *)arg, &id, sizeof(id))) return -EFAULT; return 0; } case PERF_EVENT_IOC_SET_OUTPUT: { int ret; if (arg != -1) { struct perf_event *output_event; struct fd output; ret = perf_fget_light(arg, &output); if (ret) return ret; output_event = output.file->private_data; ret = perf_event_set_output(event, output_event); fdput(output); } else { ret = perf_event_set_output(event, NULL); } return ret; } case PERF_EVENT_IOC_SET_FILTER: return perf_event_set_filter(event, (void __user *)arg); default: return -ENOTTY; } if (flags & PERF_IOC_FLAG_GROUP) perf_event_for_each(event, func); else perf_event_for_each_child(event, func); return 0; }
166,991
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char * Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) // should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = new (std::nothrow) char[len + 1]; if (dst == NULL) return -1; strcpy(dst, src); return 0; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { if (str == static_cast<char * Info::*>(NULL)) return -1; char*& dst = dst_.*str; if (dst) // should be NULL already return -1; const char* const src = this->*str; if (src == NULL) return 0; const size_t len = strlen(src); dst = SafeArrayAlloc<char>(1, len + 1); if (dst == NULL) return -1; strcpy(dst, src); return 0; }
173,803
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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::enableNativeBuffers( OMX_U32 portIndex, OMX_BOOL graphic, OMX_BOOL enable) { Mutex::Autolock autoLock(mLock); CLOG_CONFIG(enableNativeBuffers, "%s:%u%s, %d", portString(portIndex), portIndex, graphic ? ", graphic" : "", enable); OMX_STRING name = const_cast<OMX_STRING>( graphic ? "OMX.google.android.index.enableAndroidNativeBuffers" : "OMX.google.android.index.allocateNativeHandle"); OMX_INDEXTYPE index; OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err == OMX_ErrorNone) { EnableAndroidNativeBuffersParams params; InitOMXParams(&params); params.nPortIndex = portIndex; params.enable = enable; err = OMX_SetParameter(mHandle, index, &params); CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d", name, index, portString(portIndex), portIndex, enable); if (!graphic) { if (err == OMX_ErrorNone) { mSecureBufferType[portIndex] = enable ? kSecureBufferTypeNativeHandle : kSecureBufferTypeOpaque; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } } } else { CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name); if (!graphic) { char value[PROPERTY_VALUE_MAX]; if (property_get("media.mediadrmservice.enable", value, NULL) && (!strcmp("1", value) || !strcasecmp("true", value))) { CLOG_CONFIG(enableNativeBuffers, "system property override: using native-handles"); mSecureBufferType[portIndex] = kSecureBufferTypeNativeHandle; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } err = OMX_ErrorNone; } } return StatusFromOMXError(err); } Commit Message: OMXNodeInstance: sanity check portIndex. Bug: 31385713 Change-Id: Ib91d00eb5cc8c51c84d37f5d36d6b7ca594d201f (cherry picked from commit f80a1f5075a7c6e1982d37c68bfed7c9a611bb20) CWE ID: CWE-264
status_t OMXNodeInstance::enableNativeBuffers( OMX_U32 portIndex, OMX_BOOL graphic, OMX_BOOL enable) { if (portIndex >= NELEM(mSecureBufferType)) { ALOGE("b/31385713, portIndex(%u)", portIndex); android_errorWriteLog(0x534e4554, "31385713"); return BAD_VALUE; } Mutex::Autolock autoLock(mLock); CLOG_CONFIG(enableNativeBuffers, "%s:%u%s, %d", portString(portIndex), portIndex, graphic ? ", graphic" : "", enable); OMX_STRING name = const_cast<OMX_STRING>( graphic ? "OMX.google.android.index.enableAndroidNativeBuffers" : "OMX.google.android.index.allocateNativeHandle"); OMX_INDEXTYPE index; OMX_ERRORTYPE err = OMX_GetExtensionIndex(mHandle, name, &index); if (err == OMX_ErrorNone) { EnableAndroidNativeBuffersParams params; InitOMXParams(&params); params.nPortIndex = portIndex; params.enable = enable; err = OMX_SetParameter(mHandle, index, &params); CLOG_IF_ERROR(setParameter, err, "%s(%#x): %s:%u en=%d", name, index, portString(portIndex), portIndex, enable); if (!graphic) { if (err == OMX_ErrorNone) { mSecureBufferType[portIndex] = enable ? kSecureBufferTypeNativeHandle : kSecureBufferTypeOpaque; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } } } else { CLOG_ERROR_IF(enable, getExtensionIndex, err, "%s", name); if (!graphic) { char value[PROPERTY_VALUE_MAX]; if (property_get("media.mediadrmservice.enable", value, NULL) && (!strcmp("1", value) || !strcasecmp("true", value))) { CLOG_CONFIG(enableNativeBuffers, "system property override: using native-handles"); mSecureBufferType[portIndex] = kSecureBufferTypeNativeHandle; } else if (mSecureBufferType[portIndex] == kSecureBufferTypeUnknown) { mSecureBufferType[portIndex] = kSecureBufferTypeOpaque; } err = OMX_ErrorNone; } } return StatusFromOMXError(err); }
173,385
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context, const GURL& real_url) { if (real_url.SchemeIs(kGuestScheme)) return real_url; GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url); url::Origin origin = url::Origin::Create(url); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); url::Origin isolated_origin; if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin)) return isolated_origin.GetURL(); if (!origin.host().empty() && origin.scheme() != url::kFileScheme) { std::string domain = net::registry_controlled_domains::GetDomainAndRegistry( origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); std::string site = origin.scheme(); site += url::kStandardSchemeSeparator; site += domain.empty() ? origin.host() : domain; return GURL(site); } if (!origin.unique()) { DCHECK(!origin.scheme().empty()); return GURL(origin.scheme() + ":"); } else if (url.has_scheme()) { if (url.SchemeIsBlob()) { if (url.has_ref()) { GURL::Replacements replacements; replacements.ClearRef(); url = url.ReplaceComponents(replacements); } return url; } DCHECK(!url.scheme().empty()); return GURL(url.scheme() + ":"); } DCHECK(!url.is_valid()) << url; return GURL(); } Commit Message: Use unique processes for data URLs on restore. Data URLs are usually put into the process that created them, but this info is not tracked after a tab restore. Ensure that they do not end up in the parent frame's process (or each other's process), in case they are malicious. BUG=863069 Change-Id: Ib391f90c7bdf28a0a9c057c5cc7918c10aed968b Reviewed-on: https://chromium-review.googlesource.com/1150767 Reviewed-by: Alex Moshchuk <[email protected]> Reviewed-by: Lei Zhang <[email protected]> Commit-Queue: Charlie Reis <[email protected]> Cr-Commit-Position: refs/heads/master@{#581023} CWE ID: CWE-285
GURL SiteInstance::GetSiteForURL(BrowserContext* browser_context, const GURL& real_url) { if (real_url.SchemeIs(kGuestScheme)) return real_url; GURL url = SiteInstanceImpl::GetEffectiveURL(browser_context, real_url); url::Origin origin = url::Origin::Create(url); auto* policy = ChildProcessSecurityPolicyImpl::GetInstance(); url::Origin isolated_origin; if (policy->GetMatchingIsolatedOrigin(origin, &isolated_origin)) return isolated_origin.GetURL(); if (!origin.host().empty() && origin.scheme() != url::kFileScheme) { std::string domain = net::registry_controlled_domains::GetDomainAndRegistry( origin.host(), net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES); std::string site = origin.scheme(); site += url::kStandardSchemeSeparator; site += domain.empty() ? origin.host() : domain; return GURL(site); } if (!origin.unique()) { DCHECK(!origin.scheme().empty()); return GURL(origin.scheme() + ":"); } else if (url.has_scheme()) { // that might allow two URLs created by different sites to share a process. // See https://crbug.com/863623 and https://crbug.com/863069. // schemes, such as file:. // TODO(creis): This currently causes problems with tests on Android and // Android WebView. For now, skip it when Site Isolation is not enabled, // since there's no need to isolate data and blob URLs from each other in // that case. bool is_site_isolation_enabled = SiteIsolationPolicy::UseDedicatedProcessesForAllSites() || SiteIsolationPolicy::AreIsolatedOriginsEnabled(); if (is_site_isolation_enabled && (url.SchemeIsBlob() || url.scheme() == url::kDataScheme)) { // origins from each other. We also get here for browser-initiated // navigations to data URLs, which have a unique origin and should only // share a process when they are identical. Remove hash from the URL in // either case, since same-document navigations shouldn't use a different // site URL. if (url.has_ref()) { GURL::Replacements replacements; replacements.ClearRef(); url = url.ReplaceComponents(replacements); } return url; } DCHECK(!url.scheme().empty()); return GURL(url.scheme() + ":"); } DCHECK(!url.is_valid()) << url; return GURL(); }
173,183
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id, int do_interlace, int use_update_info) { standard_display d; context(psIn, fault); /* Set up the display (stack frame) variables from the arguments to the * function and initialize the locals that are filled in later. */ standard_display_init(&d, psIn, id, do_interlace, use_update_info); /* Everything is protected by a Try/Catch. The functions called also * typically have local Try/Catch blocks. */ Try { png_structp pp; png_infop pi; /* Get a png_struct for reading the image. This will throw an error if it * fails, so we don't need to check the result. */ pp = set_store_for_read(d.ps, &pi, d.id, d.do_interlace ? (d.ps->progressive ? "pngvalid progressive deinterlacer" : "pngvalid sequential deinterlacer") : (d.ps->progressive ? "progressive reader" : "sequential reader")); /* Initialize the palette correctly from the png_store_file. */ standard_palette_init(&d); /* Introduce the correct read function. */ if (d.ps->progressive) { png_set_progressive_read_fn(pp, &d, standard_info, progressive_row, standard_end); /* Now feed data into the reader until we reach the end: */ store_progressive_read(d.ps, pp, pi); } else { /* Note that this takes the store, not the display. */ png_set_read_fn(pp, d.ps, store_read); /* Check the header values: */ png_read_info(pp, pi); /* The code tests both versions of the images that the sequential * reader can produce. */ standard_info_imp(&d, pp, pi, 2 /*images*/); /* Need the total bytes in the image below; we can't get to this point * unless the PNG file values have been checked against the expected * values. */ { sequential_row(&d, pp, pi, 0, 1); /* After the last pass loop over the rows again to check that the * image is correct. */ if (!d.speed) { standard_text_validate(&d, pp, pi, 1/*check_end*/); standard_image_validate(&d, pp, 0, 1); } else d.ps->validated = 1; } } /* Check for validation. */ if (!d.ps->validated) png_error(pp, "image read failed silently"); /* Successful completion. */ } Catch(fault) d.ps = fault; /* make sure this hasn't been clobbered. */ /* In either case clean up the store. */ store_read_reset(d.ps); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id, standard_test(png_store* const psIn, png_uint_32 const id, int do_interlace, int use_update_info) { standard_display d; context(psIn, fault); /* Set up the display (stack frame) variables from the arguments to the * function and initialize the locals that are filled in later. */ standard_display_init(&d, psIn, id, do_interlace, use_update_info); /* Everything is protected by a Try/Catch. The functions called also * typically have local Try/Catch blocks. */ Try { png_structp pp; png_infop pi; /* Get a png_struct for reading the image. This will throw an error if it * fails, so we don't need to check the result. */ pp = set_store_for_read(d.ps, &pi, d.id, d.do_interlace ? (d.ps->progressive ? "pngvalid progressive deinterlacer" : "pngvalid sequential deinterlacer") : (d.ps->progressive ? "progressive reader" : "sequential reader")); /* Initialize the palette correctly from the png_store_file. */ standard_palette_init(&d); /* Introduce the correct read function. */ if (d.ps->progressive) { png_set_progressive_read_fn(pp, &d, standard_info, progressive_row, standard_end); /* Now feed data into the reader until we reach the end: */ store_progressive_read(d.ps, pp, pi); } else { /* Note that this takes the store, not the display. */ png_set_read_fn(pp, d.ps, store_read); /* Check the header values: */ png_read_info(pp, pi); /* The code tests both versions of the images that the sequential * reader can produce. */ standard_info_imp(&d, pp, pi, 2 /*images*/); /* Need the total bytes in the image below; we can't get to this point * unless the PNG file values have been checked against the expected * values. */ { sequential_row(&d, pp, pi, 0, 1); /* After the last pass loop over the rows again to check that the * image is correct. */ if (!d.speed) { standard_text_validate(&d, pp, pi, 1/*check_end*/); standard_image_validate(&d, pp, 0, 1); } else d.ps->validated = 1; } } /* Check for validation. */ if (!d.ps->validated) png_error(pp, "image read failed silently"); /* Successful completion. */ } Catch(fault) d.ps = fault; /* make sure this hasn't been clobbered. */ /* In either case clean up the store. */ store_read_reset(d.ps); }
173,702
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintViewManager::PrintPreviewDone() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_NE(NOT_PREVIEWING, print_preview_state_); if (print_preview_state_ == SCRIPTED_PREVIEW) { auto& map = g_scripted_print_preview_closure_map.Get(); auto it = map.find(scripted_print_preview_rph_); CHECK(it != map.end()); it->second.Run(); map.erase(it); scripted_print_preview_rph_ = nullptr; } print_preview_state_ = NOT_PREVIEWING; print_preview_rfh_ = nullptr; } Commit Message: Properly clean up in PrintViewManager::RenderFrameCreated(). BUG=694382,698622 Review-Url: https://codereview.chromium.org/2742853003 Cr-Commit-Position: refs/heads/master@{#457363} CWE ID: CWE-125
void PrintViewManager::PrintPreviewDone() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (print_preview_state_ == NOT_PREVIEWING) return; if (print_preview_state_ == SCRIPTED_PREVIEW) { auto& map = g_scripted_print_preview_closure_map.Get(); auto it = map.find(scripted_print_preview_rph_); CHECK(it != map.end()); it->second.Run(); map.erase(it); scripted_print_preview_rph_ = nullptr; } print_preview_state_ = NOT_PREVIEWING; print_preview_rfh_ = nullptr; }
172,404
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE3(osf_sysinfo, int, command, char __user *, buf, long, count) { const char *sysinfo_table[] = { utsname()->sysname, utsname()->nodename, utsname()->release, utsname()->version, utsname()->machine, "alpha", /* instruction set architecture */ "dummy", /* hardware serial number */ "dummy", /* hardware manufacturer */ "dummy", /* secure RPC domain */ }; unsigned long offset; const char *res; long len, err = -EINVAL; offset = command-1; if (offset >= ARRAY_SIZE(sysinfo_table)) { /* Digital UNIX has a few unpublished interfaces here */ printk("sysinfo(%d)", command); goto out; } down_read(&uts_sem); res = sysinfo_table[offset]; len = strlen(res)+1; if (len > count) len = count; if (copy_to_user(buf, res, len)) err = -EFAULT; else err = 0; up_read(&uts_sem); out: return err; } Commit Message: alpha: fix several security issues Fix several security issues in Alpha-specific syscalls. Untested, but mostly trivial. 1. Signedness issue in osf_getdomainname allows copying out-of-bounds kernel memory to userland. 2. Signedness issue in osf_sysinfo allows copying large amounts of kernel memory to userland. 3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy size, allowing copying large amounts of kernel memory to userland. 4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows privilege escalation via writing return value of sys_wait4 to kernel memory. Signed-off-by: Dan Rosenberg <[email protected]> Cc: Richard Henderson <[email protected]> Cc: Ivan Kokshaysky <[email protected]> Cc: Matt Turner <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-264
SYSCALL_DEFINE3(osf_sysinfo, int, command, char __user *, buf, long, count) { const char *sysinfo_table[] = { utsname()->sysname, utsname()->nodename, utsname()->release, utsname()->version, utsname()->machine, "alpha", /* instruction set architecture */ "dummy", /* hardware serial number */ "dummy", /* hardware manufacturer */ "dummy", /* secure RPC domain */ }; unsigned long offset; const char *res; long len, err = -EINVAL; offset = command-1; if (offset >= ARRAY_SIZE(sysinfo_table)) { /* Digital UNIX has a few unpublished interfaces here */ printk("sysinfo(%d)", command); goto out; } down_read(&uts_sem); res = sysinfo_table[offset]; len = strlen(res)+1; if ((unsigned long)len > (unsigned long)count) len = count; if (copy_to_user(buf, res, len)) err = -EFAULT; else err = 0; up_read(&uts_sem); out: return err; }
165,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Smb4KMountJob::fillArgs(Smb4KShare *share, QMap<QString, QVariant>& map) { QString mount; QStringList paths; paths << "/bin"; paths << "/sbin"; paths << "/usr/bin"; paths << "/usr/sbin"; paths << "/usr/local/bin"; paths << "/usr/local/sbin"; for (int i = 0; i < paths.size(); ++i) { mount = KGlobal::dirs()->findExe("mount.cifs", paths.at(i)); if (!mount.isEmpty()) { map.insert("mh_command", mount); break; } else { continue; } } if (mount.isEmpty()) { paths << "/sbin"; paths << "/usr/bin"; paths << "/usr/sbin"; paths << "/usr/local/bin"; paths << "/usr/local/sbin"; } QMap<QString, QString> global_options = globalSambaOptions(); Smb4KCustomOptions *options = Smb4KCustomOptionsManager::self()->findOptions(share); break; } Commit Message: CWE ID: CWE-20
bool Smb4KMountJob::fillArgs(Smb4KShare *share, QMap<QString, QVariant>& map) { const QString mount = findMountExecutable(); if (mount.isEmpty()) { paths << "/sbin"; paths << "/usr/bin"; paths << "/usr/sbin"; paths << "/usr/local/bin"; paths << "/usr/local/sbin"; } map.insert("mh_command", mount); QMap<QString, QString> global_options = globalSambaOptions(); Smb4KCustomOptions *options = Smb4KCustomOptionsManager::self()->findOptions(share); break; }
164,825
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc) { struct scsi_device *SDev; struct scsi_sense_hdr sshdr; int result, err = 0, retries = 0; SDev = cd->device; retry: if (!scsi_block_when_processing_errors(SDev)) { err = -ENODEV; goto out; } result = scsi_execute(SDev, cgc->cmd, cgc->data_direction, cgc->buffer, cgc->buflen, (unsigned char *)cgc->sense, &sshdr, cgc->timeout, IOCTL_RETRIES, 0, 0, NULL); /* Minimal error checking. Ignore cases we know about, and report the rest. */ if (driver_byte(result) != 0) { switch (sshdr.sense_key) { case UNIT_ATTENTION: SDev->changed = 1; if (!cgc->quiet) sr_printk(KERN_INFO, cd, "disc change detected.\n"); if (retries++ < 10) goto retry; err = -ENOMEDIUM; break; case NOT_READY: /* This happens if there is no disc in drive */ if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) { /* sense: Logical unit is in process of becoming ready */ if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready yet.\n"); if (retries++ < 10) { /* sleep 2 sec and try again */ ssleep(2); goto retry; } else { /* 20 secs are enough? */ err = -ENOMEDIUM; break; } } if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready. Make sure there " "is a disc in the drive.\n"); err = -ENOMEDIUM; break; case ILLEGAL_REQUEST: err = -EIO; if (sshdr.asc == 0x20 && sshdr.ascq == 0x00) /* sense: Invalid command operation code */ err = -EDRIVE_CANT_DO_THIS; break; default: err = -EIO; } } /* Wake up a process waiting for device */ out: cgc->stat = err; return err; } Commit Message: sr: pass down correctly sized SCSI sense buffer We're casting the CDROM layer request_sense to the SCSI sense buffer, but the former is 64 bytes and the latter is 96 bytes. As we generally allocate these on the stack, we end up blowing up the stack. Fix this by wrapping the scsi_execute() call with a properly sized sense buffer, and copying back the bits for the CDROM layer. Cc: [email protected] Reported-by: Piotr Gabriel Kosinski <[email protected]> Reported-by: Daniel Shapira <[email protected]> Tested-by: Kees Cook <[email protected]> Fixes: 82ed4db499b8 ("block: split scsi_request out of struct request") Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-119
int sr_do_ioctl(Scsi_CD *cd, struct packet_command *cgc) { struct scsi_device *SDev; struct scsi_sense_hdr sshdr; int result, err = 0, retries = 0; unsigned char sense_buffer[SCSI_SENSE_BUFFERSIZE], *senseptr = NULL; SDev = cd->device; if (cgc->sense) senseptr = sense_buffer; retry: if (!scsi_block_when_processing_errors(SDev)) { err = -ENODEV; goto out; } result = scsi_execute(SDev, cgc->cmd, cgc->data_direction, cgc->buffer, cgc->buflen, senseptr, &sshdr, cgc->timeout, IOCTL_RETRIES, 0, 0, NULL); if (cgc->sense) memcpy(cgc->sense, sense_buffer, sizeof(*cgc->sense)); /* Minimal error checking. Ignore cases we know about, and report the rest. */ if (driver_byte(result) != 0) { switch (sshdr.sense_key) { case UNIT_ATTENTION: SDev->changed = 1; if (!cgc->quiet) sr_printk(KERN_INFO, cd, "disc change detected.\n"); if (retries++ < 10) goto retry; err = -ENOMEDIUM; break; case NOT_READY: /* This happens if there is no disc in drive */ if (sshdr.asc == 0x04 && sshdr.ascq == 0x01) { /* sense: Logical unit is in process of becoming ready */ if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready yet.\n"); if (retries++ < 10) { /* sleep 2 sec and try again */ ssleep(2); goto retry; } else { /* 20 secs are enough? */ err = -ENOMEDIUM; break; } } if (!cgc->quiet) sr_printk(KERN_INFO, cd, "CDROM not ready. Make sure there " "is a disc in the drive.\n"); err = -ENOMEDIUM; break; case ILLEGAL_REQUEST: err = -EIO; if (sshdr.asc == 0x20 && sshdr.ascq == 0x00) /* sense: Invalid command operation code */ err = -EDRIVE_CANT_DO_THIS; break; default: err = -EIO; } } /* Wake up a process waiting for device */ out: cgc->stat = err; return err; }
169,220
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) { uint partOf = 0; const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString(); const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString(); const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool(); if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) { partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt(); } qDebug() << "Currrent active notifications:" << m_activeNotifications; qDebug() << "Guessing partOf as:" << partOf; qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf; QString _body; if (partOf > 0) { const QString source = QStringLiteral("notification %1").arg(partOf); Plasma::DataContainer *container = containerForSource(source); if (container) { _body = container->data()[QStringLiteral("body")].toString(); if (_body != body) { _body.append("\n").append(body); } else { _body = body; } replaces_id = partOf; CloseNotification(partOf); } } uint id = replaces_id ? replaces_id : m_nextId++; if (m_alwaysReplaceAppsList.contains(app_name)) { if (m_notificationsFromReplaceableApp.contains(app_name)) { id = m_notificationsFromReplaceableApp.value(app_name); } else { m_notificationsFromReplaceableApp.insert(app_name, id); } } QString appname_str = app_name; if (appname_str.isEmpty()) { appname_str = i18n("Unknown Application"); } bool isPersistent = timeout == 0; const int AVERAGE_WORD_LENGTH = 6; const int WORD_PER_MINUTE = 250; int count = summary.length() + body.length(); if (timeout <= 0) { timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE; timeout = 2000 + qMax(timeout, 3000); } const QString source = QStringLiteral("notification %1").arg(id); const QString source = QStringLiteral("notification %1").arg(id); QString bodyFinal = (partOf == 0 ? body : _body); bodyFinal = bodyFinal.trimmed(); bodyFinal = bodyFinal.replace(QLatin1String("\n"), QLatin1String("<br/>")); bodyFinal = bodyFinal.simplified(); bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>")); bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&amp;")); bodyFinal.replace(QLatin1String("&apos;"), QChar('\'')); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); bodyFinal = bodyFinal.simplified(); bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>")); bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&amp;")); bodyFinal.replace(QLatin1String("&apos;"), QChar('\'')); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); notificationData.insert(QStringLiteral("eventId"), eventId); notificationData.insert(QStringLiteral("appName"), appname_str); notificationData.insert(QStringLiteral("appIcon"), app_icon); notificationData.insert(QStringLiteral("summary"), summary); notificationData.insert(QStringLiteral("body"), bodyFinal); notificationData.insert(QStringLiteral("actions"), actions); notificationData.insert(QStringLiteral("isPersistent"), isPersistent); notificationData.insert(QStringLiteral("expireTimeout"), timeout); bool configurable = false; if (!appRealName.isEmpty()) { if (m_configurableApplications.contains(appRealName)) { configurable = m_configurableApplications.value(appRealName); } else { QScopedPointer<KConfig> config(new KConfig(appRealName + QStringLiteral(".notifyrc"), KConfig::NoGlobals)); config->addConfigSources(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications5/") + appRealName + QStringLiteral(".notifyrc"))); const QRegularExpression regexp(QStringLiteral("^Event/([^/]*)$")); configurable = !config->groupList().filter(regexp).isEmpty(); m_configurableApplications.insert(appRealName, configurable); } } notificationData.insert(QStringLiteral("appRealName"), appRealName); notificationData.insert(QStringLiteral("configurable"), configurable); QImage image; if (hints.contains(QStringLiteral("image-data"))) { QDBusArgument arg = hints[QStringLiteral("image-data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image_data"))) { QDBusArgument arg = hints[QStringLiteral("image_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image-path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image-path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("image_path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image_path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("icon_data"))) { QDBusArgument arg = hints[QStringLiteral("icon_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } notificationData.insert(QStringLiteral("image"), image.isNull() ? QVariant() : image); if (hints.contains(QStringLiteral("urgency"))) { notificationData.insert(QStringLiteral("urgency"), hints[QStringLiteral("urgency")].toInt()); } setData(source, notificationData); m_activeNotifications.insert(source, app_name + summary); return id; } Commit Message: CWE ID: CWE-200
uint NotificationsEngine::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantMap &hints, int timeout) { uint partOf = 0; const QString appRealName = hints[QStringLiteral("x-kde-appname")].toString(); const QString eventId = hints[QStringLiteral("x-kde-eventId")].toString(); const bool skipGrouping = hints[QStringLiteral("x-kde-skipGrouping")].toBool(); if (!replaces_id && m_activeNotifications.values().contains(app_name + summary) && !skipGrouping && !m_alwaysReplaceAppsList.contains(app_name)) { partOf = m_activeNotifications.key(app_name + summary).midRef(13).toUInt(); } qDebug() << "Currrent active notifications:" << m_activeNotifications; qDebug() << "Guessing partOf as:" << partOf; qDebug() << " New Notification: " << summary << body << timeout << "& Part of:" << partOf; QString _body; if (partOf > 0) { const QString source = QStringLiteral("notification %1").arg(partOf); Plasma::DataContainer *container = containerForSource(source); if (container) { _body = container->data()[QStringLiteral("body")].toString(); if (_body != body) { _body.append("\n").append(body); } else { _body = body; } replaces_id = partOf; CloseNotification(partOf); } } uint id = replaces_id ? replaces_id : m_nextId++; if (m_alwaysReplaceAppsList.contains(app_name)) { if (m_notificationsFromReplaceableApp.contains(app_name)) { id = m_notificationsFromReplaceableApp.value(app_name); } else { m_notificationsFromReplaceableApp.insert(app_name, id); } } QString appname_str = app_name; if (appname_str.isEmpty()) { appname_str = i18n("Unknown Application"); } bool isPersistent = timeout == 0; const int AVERAGE_WORD_LENGTH = 6; const int WORD_PER_MINUTE = 250; int count = summary.length() + body.length(); if (timeout <= 0) { timeout = 60000 * count / AVERAGE_WORD_LENGTH / WORD_PER_MINUTE; timeout = 2000 + qMax(timeout, 3000); } const QString source = QStringLiteral("notification %1").arg(id); const QString source = QStringLiteral("notification %1").arg(id); QString bodyFinal = (partOf == 0 ? body : _body); bodyFinal = NotificationSanitizer::parse(bodyFinal); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); bodyFinal = bodyFinal.simplified(); bodyFinal.replace(QRegularExpression(QStringLiteral("<br/>\\s*<br/>(\\s|<br/>)*")), QLatin1String("<br/>")); bodyFinal.replace(QRegularExpression(QStringLiteral("&(?!(?:apos|quot|[gl]t|amp);|#)")), QLatin1String("&amp;")); bodyFinal.replace(QLatin1String("&apos;"), QChar('\'')); Plasma::DataEngine::Data notificationData; notificationData.insert(QStringLiteral("id"), QString::number(id)); notificationData.insert(QStringLiteral("eventId"), eventId); notificationData.insert(QStringLiteral("appName"), appname_str); notificationData.insert(QStringLiteral("appIcon"), app_icon); notificationData.insert(QStringLiteral("summary"), summary); notificationData.insert(QStringLiteral("body"), bodyFinal); notificationData.insert(QStringLiteral("actions"), actions); notificationData.insert(QStringLiteral("isPersistent"), isPersistent); notificationData.insert(QStringLiteral("expireTimeout"), timeout); bool configurable = false; if (!appRealName.isEmpty()) { if (m_configurableApplications.contains(appRealName)) { configurable = m_configurableApplications.value(appRealName); } else { QScopedPointer<KConfig> config(new KConfig(appRealName + QStringLiteral(".notifyrc"), KConfig::NoGlobals)); config->addConfigSources(QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("knotifications5/") + appRealName + QStringLiteral(".notifyrc"))); const QRegularExpression regexp(QStringLiteral("^Event/([^/]*)$")); configurable = !config->groupList().filter(regexp).isEmpty(); m_configurableApplications.insert(appRealName, configurable); } } notificationData.insert(QStringLiteral("appRealName"), appRealName); notificationData.insert(QStringLiteral("configurable"), configurable); QImage image; if (hints.contains(QStringLiteral("image-data"))) { QDBusArgument arg = hints[QStringLiteral("image-data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image_data"))) { QDBusArgument arg = hints[QStringLiteral("image_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } else if (hints.contains(QStringLiteral("image-path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image-path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("image_path"))) { QString path = findImageForSpecImagePath(hints[QStringLiteral("image_path")].toString()); if (!path.isEmpty()) { image.load(path); } } else if (hints.contains(QStringLiteral("icon_data"))) { QDBusArgument arg = hints[QStringLiteral("icon_data")].value<QDBusArgument>(); image = decodeNotificationSpecImageHint(arg); } notificationData.insert(QStringLiteral("image"), image.isNull() ? QVariant() : image); if (hints.contains(QStringLiteral("urgency"))) { notificationData.insert(QStringLiteral("urgency"), hints[QStringLiteral("urgency")].toInt()); } setData(source, notificationData); m_activeNotifications.insert(source, app_name + summary); return id; }
165,026
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftVPX::onQueueFilled(OMX_U32 /* portIndex */) { if (mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); bool EOSseen = false; while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { EOSseen = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } } if (mImg == NULL) { if (vpx_codec_decode( (vpx_codec_ctx_t *)mCtx, inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen, NULL, 0)) { ALOGE("on2 decoder failed to decode frame."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } vpx_codec_iter_t iter = NULL; mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter); } if (mImg != NULL) { CHECK_EQ(mImg->fmt, IMG_FMT_I420); uint32_t width = mImg->d_w; uint32_t height = mImg->d_h; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { return; } outHeader->nOffset = 0; outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nFlags = EOSseen ? OMX_BUFFERFLAG_EOS : 0; outHeader->nTimeStamp = inHeader->nTimeStamp; uint8_t *dst = outHeader->pBuffer; const uint8_t *srcY = (const uint8_t *)mImg->planes[PLANE_Y]; const uint8_t *srcU = (const uint8_t *)mImg->planes[PLANE_U]; const uint8_t *srcV = (const uint8_t *)mImg->planes[PLANE_V]; size_t srcYStride = mImg->stride[PLANE_Y]; size_t srcUStride = mImg->stride[PLANE_U]; size_t srcVStride = mImg->stride[PLANE_V]; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mImg = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } } Commit Message: DO NOT MERGE - Remove deprecated image defines libvpx has always supported the VPX_ prefixed versions of these defines. The unprefixed versions have been removed in the most recent release. https://chromium.googlesource.com/webm/libvpx/+/9cdaa3d72eade9ad162ef8f78a93bd8f85c6de10 BUG=23452792 Change-Id: I8a656f2262f117d7a95271f45100b8c6fd0a470f CWE ID: CWE-119
void SoftVPX::onQueueFilled(OMX_U32 /* portIndex */) { if (mOutputPortSettingsChange != NONE) { return; } List<BufferInfo *> &inQueue = getPortQueue(0); List<BufferInfo *> &outQueue = getPortQueue(1); bool EOSseen = false; while (!inQueue.empty() && !outQueue.empty()) { BufferInfo *inInfo = *inQueue.begin(); OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { EOSseen = true; if (inHeader->nFilledLen == 0) { inQueue.erase(inQueue.begin()); inInfo->mOwnedByUs = false; notifyEmptyBufferDone(inHeader); outHeader->nFilledLen = 0; outHeader->nFlags = OMX_BUFFERFLAG_EOS; outQueue.erase(outQueue.begin()); outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return; } } if (mImg == NULL) { if (vpx_codec_decode( (vpx_codec_ctx_t *)mCtx, inHeader->pBuffer + inHeader->nOffset, inHeader->nFilledLen, NULL, 0)) { ALOGE("on2 decoder failed to decode frame."); notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); return; } vpx_codec_iter_t iter = NULL; mImg = vpx_codec_get_frame((vpx_codec_ctx_t *)mCtx, &iter); } if (mImg != NULL) { CHECK_EQ(mImg->fmt, VPX_IMG_FMT_I420); uint32_t width = mImg->d_w; uint32_t height = mImg->d_h; bool portWillReset = false; handlePortSettingsChange(&portWillReset, width, height); if (portWillReset) { return; } outHeader->nOffset = 0; outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2; outHeader->nFlags = EOSseen ? OMX_BUFFERFLAG_EOS : 0; outHeader->nTimeStamp = inHeader->nTimeStamp; uint8_t *dst = outHeader->pBuffer; const uint8_t *srcY = (const uint8_t *)mImg->planes[VPX_PLANE_Y]; const uint8_t *srcU = (const uint8_t *)mImg->planes[VPX_PLANE_U]; const uint8_t *srcV = (const uint8_t *)mImg->planes[VPX_PLANE_V]; size_t srcYStride = mImg->stride[VPX_PLANE_Y]; size_t srcUStride = mImg->stride[VPX_PLANE_U]; size_t srcVStride = mImg->stride[VPX_PLANE_V]; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mImg = NULL; outInfo->mOwnedByUs = false; outQueue.erase(outQueue.begin()); outInfo = NULL; notifyFillBufferDone(outHeader); outHeader = NULL; } inInfo->mOwnedByUs = false; inQueue.erase(inQueue.begin()); inInfo = NULL; notifyEmptyBufferDone(inHeader); inHeader = NULL; } }
173,899
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 do_write_pids(pid_t tpid, const char *contrl, const char *cg, const char *file, const char *buf) { int sock[2] = {-1, -1}; pid_t qpid, cpid = -1; FILE *pids_file = NULL; bool answer = false, fail = false; pids_file = open_pids_file(contrl, cg); if (!pids_file) return false; /* * write the pids to a socket, have helper in writer's pidns * call movepid for us */ if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) { perror("socketpair"); goto out; } cpid = fork(); if (cpid == -1) goto out; if (!cpid) { // child fclose(pids_file); pid_from_ns_wrapper(sock[1], tpid); } const char *ptr = buf; while (sscanf(ptr, "%d", &qpid) == 1) { struct ucred cred; char v; if (write(sock[0], &qpid, sizeof(qpid)) != sizeof(qpid)) { fprintf(stderr, "%s: error writing pid to child: %s\n", __func__, strerror(errno)); goto out; } if (recv_creds(sock[0], &cred, &v)) { if (v == '0') { if (fprintf(pids_file, "%d", (int) cred.pid) < 0) fail = true; } } ptr = strchr(ptr, '\n'); if (!ptr) break; ptr++; } /* All good, write the value */ qpid = -1; if (write(sock[0], &qpid ,sizeof(qpid)) != sizeof(qpid)) fprintf(stderr, "Warning: failed to ask child to exit\n"); if (!fail) answer = true; out: if (cpid != -1) wait_for_pid(cpid); if (sock[0] != -1) { close(sock[0]); close(sock[1]); } if (pids_file) { if (fclose(pids_file) != 0) answer = false; } return answer; } Commit Message: Implement privilege check when moving tasks When writing pids to a tasks file in lxcfs, lxcfs was checking for privilege over the tasks file but not over the pid being moved. Since the cgm_movepid request is done as root on the host, not with the requestor's credentials, we must copy the check which cgmanager was doing to ensure that the requesting task is allowed to change the victim task's cgroup membership. This is CVE-2015-1344 https://bugs.launchpad.net/ubuntu/+source/lxcfs/+bug/1512854 Signed-off-by: Serge Hallyn <[email protected]> CWE ID: CWE-264
static bool do_write_pids(pid_t tpid, const char *contrl, const char *cg, const char *file, const char *buf) /* * Given host @uid, return the uid to which it maps in * @pid's user namespace, or -1 if none. */ bool hostuid_to_ns(uid_t uid, pid_t pid, uid_t *answer) { FILE *f; char line[400]; sprintf(line, "/proc/%d/uid_map", pid); if ((f = fopen(line, "r")) == NULL) { return false; } *answer = convert_id_to_ns(f, uid); fclose(f); if (*answer == -1) return false; return true; } /* * get_pid_creds: get the real uid and gid of @pid from * /proc/$$/status * (XXX should we use euid here?) */ void get_pid_creds(pid_t pid, uid_t *uid, gid_t *gid) { char line[400]; uid_t u; gid_t g; FILE *f; *uid = -1; *gid = -1; sprintf(line, "/proc/%d/status", pid); if ((f = fopen(line, "r")) == NULL) { fprintf(stderr, "Error opening %s: %s\n", line, strerror(errno)); return; } while (fgets(line, 400, f)) { if (strncmp(line, "Uid:", 4) == 0) { if (sscanf(line+4, "%u", &u) != 1) { fprintf(stderr, "bad uid line for pid %u\n", pid); fclose(f); return; } *uid = u; } else if (strncmp(line, "Gid:", 4) == 0) { if (sscanf(line+4, "%u", &g) != 1) { fprintf(stderr, "bad gid line for pid %u\n", pid); fclose(f); return; } *gid = g; } } fclose(f); } /* * May the requestor @r move victim @v to a new cgroup? * This is allowed if * . they are the same task * . they are ownedy by the same uid * . @r is root on the host, or * . @v's uid is mapped into @r's where @r is root. */ bool may_move_pid(pid_t r, uid_t r_uid, pid_t v) { uid_t v_uid, tmpuid; gid_t v_gid; if (r == v) return true; if (r_uid == 0) return true; get_pid_creds(v, &v_uid, &v_gid); if (r_uid == v_uid) return true; if (hostuid_to_ns(r_uid, r, &tmpuid) && tmpuid == 0 && hostuid_to_ns(v_uid, r, &tmpuid)) return true; return false; } static bool do_write_pids(pid_t tpid, uid_t tuid, const char *contrl, const char *cg, const char *file, const char *buf) { int sock[2] = {-1, -1}; pid_t qpid, cpid = -1; FILE *pids_file = NULL; bool answer = false, fail = false; pids_file = open_pids_file(contrl, cg); if (!pids_file) return false; /* * write the pids to a socket, have helper in writer's pidns * call movepid for us */ if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) { perror("socketpair"); goto out; } cpid = fork(); if (cpid == -1) goto out; if (!cpid) { // child fclose(pids_file); pid_from_ns_wrapper(sock[1], tpid); } const char *ptr = buf; while (sscanf(ptr, "%d", &qpid) == 1) { struct ucred cred; char v; if (write(sock[0], &qpid, sizeof(qpid)) != sizeof(qpid)) { fprintf(stderr, "%s: error writing pid to child: %s\n", __func__, strerror(errno)); goto out; } if (recv_creds(sock[0], &cred, &v)) { if (v == '0') { if (!may_move_pid(tpid, tuid, cred.pid)) { fail = true; break; } if (fprintf(pids_file, "%d", (int) cred.pid) < 0) fail = true; } } ptr = strchr(ptr, '\n'); if (!ptr) break; ptr++; } /* All good, write the value */ qpid = -1; if (write(sock[0], &qpid ,sizeof(qpid)) != sizeof(qpid)) fprintf(stderr, "Warning: failed to ask child to exit\n"); if (!fail) answer = true; out: if (cpid != -1) wait_for_pid(cpid); if (sock[0] != -1) { close(sock[0]); close(sock[1]); } if (pids_file) { if (fclose(pids_file) != 0) answer = false; } return answer; }
166,702
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ContainerNode::notifyNodeInsertedInternal(Node& root, NodeVector& postInsertionNotificationTargets) { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) { if (!inDocument() && !node.isContainerNode()) continue; if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(this)) postInsertionNotificationTargets.append(&node); for (ShadowRoot* shadowRoot = node.youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) notifyNodeInsertedInternal(*shadowRoot, postInsertionNotificationTargets); } } Commit Message: Fix an optimisation in ContainerNode::notifyNodeInsertedInternal [email protected] BUG=544020 Review URL: https://codereview.chromium.org/1420653003 Cr-Commit-Position: refs/heads/master@{#355240} CWE ID:
void ContainerNode::notifyNodeInsertedInternal(Node& root, NodeVector& postInsertionNotificationTargets) { EventDispatchForbiddenScope assertNoEventDispatch; ScriptForbiddenScope forbidScript; for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) { // into detached subtrees that are not in a shadow tree. if (!inDocument() && !isInShadowTree() && !node.isContainerNode()) continue; if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(this)) postInsertionNotificationTargets.append(&node); for (ShadowRoot* shadowRoot = node.youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) notifyNodeInsertedInternal(*shadowRoot, postInsertionNotificationTargets); } }
171,772
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *load_device_tree(const char *filename_path, int *sizep) { int dt_size; int dt_file_load_size; int ret; void *fdt = NULL; *sizep = 0; dt_size = get_image_size(filename_path); if (dt_size < 0) { error_report("Unable to get size of device tree file '%s'", filename_path); goto fail; } /* Expand to 2x size to give enough room for manipulation. */ dt_size += 10000; dt_size *= 2; /* First allocate space in qemu for device tree */ fdt = g_malloc0(dt_size); dt_file_load_size = load_image(filename_path, fdt); if (dt_file_load_size < 0) { error_report("Unable to open device tree file '%s'", filename_path); goto fail; } ret = fdt_open_into(fdt, fdt, dt_size); if (ret) { error_report("Unable to copy device tree in memory"); goto fail; } /* Check sanity of device tree */ if (fdt_check_header(fdt)) { error_report("Device tree file loaded into memory is invalid: %s", filename_path); goto fail; } *sizep = dt_size; return fdt; fail: g_free(fdt); return NULL; } Commit Message: CWE ID: CWE-119
void *load_device_tree(const char *filename_path, int *sizep) { int dt_size; int dt_file_load_size; int ret; void *fdt = NULL; *sizep = 0; dt_size = get_image_size(filename_path); if (dt_size < 0) { error_report("Unable to get size of device tree file '%s'", filename_path); goto fail; } /* Expand to 2x size to give enough room for manipulation. */ dt_size += 10000; dt_size *= 2; /* First allocate space in qemu for device tree */ fdt = g_malloc0(dt_size); dt_file_load_size = load_image_size(filename_path, fdt, dt_size); if (dt_file_load_size < 0) { error_report("Unable to open device tree file '%s'", filename_path); goto fail; } ret = fdt_open_into(fdt, fdt, dt_size); if (ret) { error_report("Unable to copy device tree in memory"); goto fail; } /* Check sanity of device tree */ if (fdt_check_header(fdt)) { error_report("Device tree file loaded into memory is invalid: %s", filename_path); goto fail; } *sizep = dt_size; return fdt; fail: g_free(fdt); return NULL; }
165,222
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cifs_lookup(struct inode *parent_dir_inode, struct dentry *direntry, struct nameidata *nd) { int xid; int rc = 0; /* to get around spurious gcc warning, set to zero here */ __u32 oplock = enable_oplocks ? REQ_OPLOCK : 0; __u16 fileHandle = 0; bool posix_open = false; struct cifs_sb_info *cifs_sb; struct tcon_link *tlink; struct cifs_tcon *pTcon; struct cifsFileInfo *cfile; struct inode *newInode = NULL; char *full_path = NULL; struct file *filp; xid = GetXid(); cFYI(1, "parent inode = 0x%p name is: %s and dentry = 0x%p", parent_dir_inode, direntry->d_name.name, direntry); /* check whether path exists */ cifs_sb = CIFS_SB(parent_dir_inode->i_sb); tlink = cifs_sb_tlink(cifs_sb); if (IS_ERR(tlink)) { FreeXid(xid); return (struct dentry *)tlink; } pTcon = tlink_tcon(tlink); /* * Don't allow the separator character in a path component. * The VFS will not allow "/", but "\" is allowed by posix. */ if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)) { int i; for (i = 0; i < direntry->d_name.len; i++) if (direntry->d_name.name[i] == '\\') { cFYI(1, "Invalid file name"); rc = -EINVAL; goto lookup_out; } } /* * O_EXCL: optimize away the lookup, but don't hash the dentry. Let * the VFS handle the create. */ if (nd && (nd->flags & LOOKUP_EXCL)) { d_instantiate(direntry, NULL); rc = 0; goto lookup_out; } /* can not grab the rename sem here since it would deadlock in the cases (beginning of sys_rename itself) in which we already have the sb rename sem */ full_path = build_path_from_dentry(direntry); if (full_path == NULL) { rc = -ENOMEM; goto lookup_out; } if (direntry->d_inode != NULL) { cFYI(1, "non-NULL inode in lookup"); } else { cFYI(1, "NULL inode in lookup"); } cFYI(1, "Full path: %s inode = 0x%p", full_path, direntry->d_inode); /* Posix open is only called (at lookup time) for file create now. * For opens (rather than creates), because we do not know if it * is a file or directory yet, and current Samba no longer allows * us to do posix open on dirs, we could end up wasting an open call * on what turns out to be a dir. For file opens, we wait to call posix * open till cifs_open. It could be added here (lookup) in the future * but the performance tradeoff of the extra network request when EISDIR * or EACCES is returned would have to be weighed against the 50% * reduction in network traffic in the other paths. */ if (pTcon->unix_ext) { if (nd && !(nd->flags & LOOKUP_DIRECTORY) && (nd->flags & LOOKUP_OPEN) && !pTcon->broken_posix_open && (nd->intent.open.file->f_flags & O_CREAT)) { rc = cifs_posix_open(full_path, &newInode, parent_dir_inode->i_sb, nd->intent.open.create_mode, nd->intent.open.file->f_flags, &oplock, &fileHandle, xid); /* * The check below works around a bug in POSIX * open in samba versions 3.3.1 and earlier where * open could incorrectly fail with invalid parameter. * If either that or op not supported returned, follow * the normal lookup. */ if ((rc == 0) || (rc == -ENOENT)) posix_open = true; else if ((rc == -EINVAL) || (rc != -EOPNOTSUPP)) pTcon->broken_posix_open = true; } if (!posix_open) rc = cifs_get_inode_info_unix(&newInode, full_path, parent_dir_inode->i_sb, xid); } else rc = cifs_get_inode_info(&newInode, full_path, NULL, parent_dir_inode->i_sb, xid, NULL); if ((rc == 0) && (newInode != NULL)) { d_add(direntry, newInode); if (posix_open) { filp = lookup_instantiate_filp(nd, direntry, generic_file_open); if (IS_ERR(filp)) { rc = PTR_ERR(filp); CIFSSMBClose(xid, pTcon, fileHandle); goto lookup_out; } cfile = cifs_new_fileinfo(fileHandle, filp, tlink, oplock); if (cfile == NULL) { fput(filp); CIFSSMBClose(xid, pTcon, fileHandle); rc = -ENOMEM; goto lookup_out; } } /* since paths are not looked up by component - the parent directories are presumed to be good here */ renew_parental_timestamps(direntry); } else if (rc == -ENOENT) { rc = 0; direntry->d_time = jiffies; d_add(direntry, NULL); /* if it was once a directory (but how can we tell?) we could do shrink_dcache_parent(direntry); */ } else if (rc != -EACCES) { cERROR(1, "Unexpected lookup error %d", rc); /* We special case check for Access Denied - since that is a common return code */ } lookup_out: kfree(full_path); cifs_put_tlink(tlink); FreeXid(xid); return ERR_PTR(rc); } Commit Message: cifs: fix dentry refcount leak when opening a FIFO on lookup commit 5bccda0ebc7c0331b81ac47d39e4b920b198b2cd upstream. The cifs code will attempt to open files on lookup under certain circumstances. What happens though if we find that the file we opened was actually a FIFO or other special file? Currently, the open filehandle just ends up being leaked leading to a dentry refcount mismatch and oops on umount. Fix this by having the code close the filehandle on the server if it turns out not to be a regular file. While we're at it, change this spaghetti if statement into a switch too. Reported-by: CAI Qian <[email protected]> Tested-by: CAI Qian <[email protected]> Reviewed-by: Shirish Pargaonkar <[email protected]> Signed-off-by: Jeff Layton <[email protected]> Signed-off-by: Steve French <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-264
cifs_lookup(struct inode *parent_dir_inode, struct dentry *direntry, struct nameidata *nd) { int xid; int rc = 0; /* to get around spurious gcc warning, set to zero here */ __u32 oplock = enable_oplocks ? REQ_OPLOCK : 0; __u16 fileHandle = 0; bool posix_open = false; struct cifs_sb_info *cifs_sb; struct tcon_link *tlink; struct cifs_tcon *pTcon; struct cifsFileInfo *cfile; struct inode *newInode = NULL; char *full_path = NULL; struct file *filp; xid = GetXid(); cFYI(1, "parent inode = 0x%p name is: %s and dentry = 0x%p", parent_dir_inode, direntry->d_name.name, direntry); /* check whether path exists */ cifs_sb = CIFS_SB(parent_dir_inode->i_sb); tlink = cifs_sb_tlink(cifs_sb); if (IS_ERR(tlink)) { FreeXid(xid); return (struct dentry *)tlink; } pTcon = tlink_tcon(tlink); /* * Don't allow the separator character in a path component. * The VFS will not allow "/", but "\" is allowed by posix. */ if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)) { int i; for (i = 0; i < direntry->d_name.len; i++) if (direntry->d_name.name[i] == '\\') { cFYI(1, "Invalid file name"); rc = -EINVAL; goto lookup_out; } } /* * O_EXCL: optimize away the lookup, but don't hash the dentry. Let * the VFS handle the create. */ if (nd && (nd->flags & LOOKUP_EXCL)) { d_instantiate(direntry, NULL); rc = 0; goto lookup_out; } /* can not grab the rename sem here since it would deadlock in the cases (beginning of sys_rename itself) in which we already have the sb rename sem */ full_path = build_path_from_dentry(direntry); if (full_path == NULL) { rc = -ENOMEM; goto lookup_out; } if (direntry->d_inode != NULL) { cFYI(1, "non-NULL inode in lookup"); } else { cFYI(1, "NULL inode in lookup"); } cFYI(1, "Full path: %s inode = 0x%p", full_path, direntry->d_inode); /* Posix open is only called (at lookup time) for file create now. * For opens (rather than creates), because we do not know if it * is a file or directory yet, and current Samba no longer allows * us to do posix open on dirs, we could end up wasting an open call * on what turns out to be a dir. For file opens, we wait to call posix * open till cifs_open. It could be added here (lookup) in the future * but the performance tradeoff of the extra network request when EISDIR * or EACCES is returned would have to be weighed against the 50% * reduction in network traffic in the other paths. */ if (pTcon->unix_ext) { if (nd && !(nd->flags & LOOKUP_DIRECTORY) && (nd->flags & LOOKUP_OPEN) && !pTcon->broken_posix_open && (nd->intent.open.file->f_flags & O_CREAT)) { rc = cifs_posix_open(full_path, &newInode, parent_dir_inode->i_sb, nd->intent.open.create_mode, nd->intent.open.file->f_flags, &oplock, &fileHandle, xid); /* * The check below works around a bug in POSIX * open in samba versions 3.3.1 and earlier where * open could incorrectly fail with invalid parameter. * If either that or op not supported returned, follow * the normal lookup. */ switch (rc) { case 0: /* * The server may allow us to open things like * FIFOs, but the client isn't set up to deal * with that. If it's not a regular file, just * close it and proceed as if it were a normal * lookup. */ if (newInode && !S_ISREG(newInode->i_mode)) { CIFSSMBClose(xid, pTcon, fileHandle); break; } case -ENOENT: posix_open = true; case -EOPNOTSUPP: break; default: pTcon->broken_posix_open = true; } } if (!posix_open) rc = cifs_get_inode_info_unix(&newInode, full_path, parent_dir_inode->i_sb, xid); } else rc = cifs_get_inode_info(&newInode, full_path, NULL, parent_dir_inode->i_sb, xid, NULL); if ((rc == 0) && (newInode != NULL)) { d_add(direntry, newInode); if (posix_open) { filp = lookup_instantiate_filp(nd, direntry, generic_file_open); if (IS_ERR(filp)) { rc = PTR_ERR(filp); CIFSSMBClose(xid, pTcon, fileHandle); goto lookup_out; } cfile = cifs_new_fileinfo(fileHandle, filp, tlink, oplock); if (cfile == NULL) { fput(filp); CIFSSMBClose(xid, pTcon, fileHandle); rc = -ENOMEM; goto lookup_out; } } /* since paths are not looked up by component - the parent directories are presumed to be good here */ renew_parental_timestamps(direntry); } else if (rc == -ENOENT) { rc = 0; direntry->d_time = jiffies; d_add(direntry, NULL); /* if it was once a directory (but how can we tell?) we could do shrink_dcache_parent(direntry); */ } else if (rc != -EACCES) { cERROR(1, "Unexpected lookup error %d", rc); /* We special case check for Access Denied - since that is a common return code */ } lookup_out: kfree(full_path); cifs_put_tlink(tlink); FreeXid(xid); return ERR_PTR(rc); }
165,645
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderProcessImpl::RenderProcessImpl() : ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_( FROM_HERE, base::TimeDelta::FromSeconds(5), this, &RenderProcessImpl::ClearTransportDIBCache)), transport_dib_next_sequence_number_(0) { in_process_plugins_ = InProcessPlugins(); for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) shared_mem_cache_[i] = NULL; #if defined(OS_WIN) if (GetModuleHandle(L"LPK.DLL") == NULL) { typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs); GdiInitializeLanguagePack gdi_init_lpk = reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress( GetModuleHandle(L"GDI32.DLL"), "GdiInitializeLanguagePack")); DCHECK(gdi_init_lpk); if (gdi_init_lpk) { gdi_init_lpk(0); } } #endif webkit_glue::SetJavaScriptFlags( "--debugger-auto-break" " --prof --prof-lazy"); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kJavaScriptFlags)) { webkit_glue::SetJavaScriptFlags( command_line.GetSwitchValueASCII(switches::kJavaScriptFlags)); } } Commit Message: Allow browser to handle all WebUI navigations. BUG=113496 TEST="Google Dashboard" link in Sync settings loads in new process. Review URL: http://codereview.chromium.org/9663045 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
RenderProcessImpl::RenderProcessImpl() : ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_( FROM_HERE, base::TimeDelta::FromSeconds(5), this, &RenderProcessImpl::ClearTransportDIBCache)), transport_dib_next_sequence_number_(0), enabled_bindings_(0) { in_process_plugins_ = InProcessPlugins(); for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i) shared_mem_cache_[i] = NULL; #if defined(OS_WIN) if (GetModuleHandle(L"LPK.DLL") == NULL) { typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs); GdiInitializeLanguagePack gdi_init_lpk = reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress( GetModuleHandle(L"GDI32.DLL"), "GdiInitializeLanguagePack")); DCHECK(gdi_init_lpk); if (gdi_init_lpk) { gdi_init_lpk(0); } } #endif webkit_glue::SetJavaScriptFlags( "--debugger-auto-break" " --prof --prof-lazy"); const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kJavaScriptFlags)) { webkit_glue::SetJavaScriptFlags( command_line.GetSwitchValueASCII(switches::kJavaScriptFlags)); } }
171,017
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tls1_setup_key_block(SSL *s) { unsigned char *p; const EVP_CIPHER *c; const EVP_MD *hash; int num; SSL_COMP *comp; int mac_type = NID_undef, mac_secret_size = 0; int ret = 0; if (s->s3->tmp.key_block_length != 0) return (1); if (!ssl_cipher_get_evp (s->session, &c, &hash, &mac_type, &mac_secret_size, &comp, SSL_USE_ETM(s))) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE); return (0); } s->s3->tmp.new_sym_enc = c; s->s3->tmp.new_hash = hash; s->s3->tmp.new_mac_pkey_type = mac_type; s->s3->tmp.new_mac_secret_size = mac_secret_size; num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c); num *= 2; ssl3_cleanup_key_block(s); if ((p = OPENSSL_malloc(num)) == NULL) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE); goto err; } s->s3->tmp.key_block_length = num; s->s3->tmp.key_block = p; #ifdef SSL_DEBUG printf("client random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->client_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("server random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->server_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("master key\n"); { int z; for (z = 0; z < s->session->master_key_length; z++) printf("%02X%c", s->session->master_key[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!tls1_generate_key_block(s, p, num)) goto err; #ifdef SSL_DEBUG printf("\nkey block\n"); { int z; for (z = 0; z < num; z++) printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) && s->method->version <= TLS1_VERSION) { /* * enable vulnerability countermeasure for CBC ciphers with known-IV * problem (http://www.openssl.org/~bodo/tls-cbc.txt) */ s->s3->need_empty_fragments = 1; if (s->session->cipher != NULL) { if (s->session->cipher->algorithm_enc == SSL_eNULL) s->s3->need_empty_fragments = 0; #ifndef OPENSSL_NO_RC4 if (s->session->cipher->algorithm_enc == SSL_RC4) s->s3->need_empty_fragments = 0; #endif } } ret = 1; err: return (ret); } Commit Message: Don't change the state of the ETM flags until CCS processing Changing the ciphersuite during a renegotiation can result in a crash leading to a DoS attack. ETM has not been implemented in 1.1.0 for DTLS so this is TLS only. The problem is caused by changing the flag indicating whether to use ETM or not immediately on negotiation of ETM, rather than at CCS. Therefore, during a renegotiation, if the ETM state is changing (usually due to a change of ciphersuite), then an error/crash will occur. Due to the fact that there are separate CCS messages for read and write we actually now need two flags to determine whether to use ETM or not. CVE-2017-3733 Reviewed-by: Richard Levitte <[email protected]> CWE ID: CWE-20
int tls1_setup_key_block(SSL *s) { unsigned char *p; const EVP_CIPHER *c; const EVP_MD *hash; int num; SSL_COMP *comp; int mac_type = NID_undef, mac_secret_size = 0; int ret = 0; if (s->s3->tmp.key_block_length != 0) return (1); if (!ssl_cipher_get_evp(s->session, &c, &hash, &mac_type, &mac_secret_size, &comp, s->tlsext_use_etm)) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE); return (0); } s->s3->tmp.new_sym_enc = c; s->s3->tmp.new_hash = hash; s->s3->tmp.new_mac_pkey_type = mac_type; s->s3->tmp.new_mac_secret_size = mac_secret_size; num = EVP_CIPHER_key_length(c) + mac_secret_size + EVP_CIPHER_iv_length(c); num *= 2; ssl3_cleanup_key_block(s); if ((p = OPENSSL_malloc(num)) == NULL) { SSLerr(SSL_F_TLS1_SETUP_KEY_BLOCK, ERR_R_MALLOC_FAILURE); goto err; } s->s3->tmp.key_block_length = num; s->s3->tmp.key_block = p; #ifdef SSL_DEBUG printf("client random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->client_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("server random\n"); { int z; for (z = 0; z < SSL3_RANDOM_SIZE; z++) printf("%02X%c", s->s3->server_random[z], ((z + 1) % 16) ? ' ' : '\n'); } printf("master key\n"); { int z; for (z = 0; z < s->session->master_key_length; z++) printf("%02X%c", s->session->master_key[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!tls1_generate_key_block(s, p, num)) goto err; #ifdef SSL_DEBUG printf("\nkey block\n"); { int z; for (z = 0; z < num; z++) printf("%02X%c", p[z], ((z + 1) % 16) ? ' ' : '\n'); } #endif if (!(s->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) && s->method->version <= TLS1_VERSION) { /* * enable vulnerability countermeasure for CBC ciphers with known-IV * problem (http://www.openssl.org/~bodo/tls-cbc.txt) */ s->s3->need_empty_fragments = 1; if (s->session->cipher != NULL) { if (s->session->cipher->algorithm_enc == SSL_eNULL) s->s3->need_empty_fragments = 0; #ifndef OPENSSL_NO_RC4 if (s->session->cipher->algorithm_enc == SSL_RC4) s->s3->need_empty_fragments = 0; #endif } } ret = 1; err: return (ret); }
168,426
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range) { __u64 start = F2FS_BYTES_TO_BLK(range->start); __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1; unsigned int start_segno, end_segno; struct cp_control cpc; int err = 0; if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize) return -EINVAL; cpc.trimmed = 0; if (end <= MAIN_BLKADDR(sbi)) goto out; if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) { f2fs_msg(sbi->sb, KERN_WARNING, "Found FS corruption, run fsck to fix."); goto out; } /* start/end segment number in main_area */ start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start); end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 : GET_SEGNO(sbi, end); cpc.reason = CP_DISCARD; cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen)); /* do checkpoint to issue discard commands safely */ for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) { cpc.trim_start = start_segno; if (sbi->discard_blks == 0) break; else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi)) cpc.trim_end = end_segno; else cpc.trim_end = min_t(unsigned int, rounddown(start_segno + BATCHED_TRIM_SEGMENTS(sbi), sbi->segs_per_sec) - 1, end_segno); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); if (err) break; schedule(); } /* It's time to issue all the filed discards */ mark_discard_range_all(sbi); f2fs_wait_discard_bios(sbi); out: range->len = F2FS_BLK_TO_BYTES(cpc.trimmed); return err; } Commit Message: f2fs: fix potential panic during fstrim As Ju Hyung Park reported: "When 'fstrim' is called for manual trim, a BUG() can be triggered randomly with this patch. I'm seeing this issue on both x86 Desktop and arm64 Android phone. On x86 Desktop, this was caused during Ubuntu boot-up. I have a cronjob installed which calls 'fstrim -v /' during boot. On arm64 Android, this was caused during GC looping with 1ms gc_min_sleep_time & gc_max_sleep_time." Root cause of this issue is that f2fs_wait_discard_bios can only be used by f2fs_put_super, because during put_super there must be no other referrers, so it can ignore discard entry's reference count when removing the entry, otherwise in other caller we will hit bug_on in __remove_discard_cmd as there may be other issuer added reference count in discard entry. Thread A Thread B - issue_discard_thread - f2fs_ioc_fitrim - f2fs_trim_fs - f2fs_wait_discard_bios - __issue_discard_cmd - __submit_discard_cmd - __wait_discard_cmd - dc->ref++ - __wait_one_discard_bio - __wait_discard_cmd - __remove_discard_cmd - f2fs_bug_on(sbi, dc->ref) Fixes: 969d1b180d987c2be02de890d0fff0f66a0e80de Reported-by: Ju Hyung Park <[email protected]> Signed-off-by: Chao Yu <[email protected]> Signed-off-by: Jaegeuk Kim <[email protected]> CWE ID: CWE-20
int f2fs_trim_fs(struct f2fs_sb_info *sbi, struct fstrim_range *range) { __u64 start = F2FS_BYTES_TO_BLK(range->start); __u64 end = start + F2FS_BYTES_TO_BLK(range->len) - 1; unsigned int start_segno, end_segno; struct cp_control cpc; int err = 0; if (start >= MAX_BLKADDR(sbi) || range->len < sbi->blocksize) return -EINVAL; cpc.trimmed = 0; if (end <= MAIN_BLKADDR(sbi)) goto out; if (is_sbi_flag_set(sbi, SBI_NEED_FSCK)) { f2fs_msg(sbi->sb, KERN_WARNING, "Found FS corruption, run fsck to fix."); goto out; } /* start/end segment number in main_area */ start_segno = (start <= MAIN_BLKADDR(sbi)) ? 0 : GET_SEGNO(sbi, start); end_segno = (end >= MAX_BLKADDR(sbi)) ? MAIN_SEGS(sbi) - 1 : GET_SEGNO(sbi, end); cpc.reason = CP_DISCARD; cpc.trim_minlen = max_t(__u64, 1, F2FS_BYTES_TO_BLK(range->minlen)); /* do checkpoint to issue discard commands safely */ for (; start_segno <= end_segno; start_segno = cpc.trim_end + 1) { cpc.trim_start = start_segno; if (sbi->discard_blks == 0) break; else if (sbi->discard_blks < BATCHED_TRIM_BLOCKS(sbi)) cpc.trim_end = end_segno; else cpc.trim_end = min_t(unsigned int, rounddown(start_segno + BATCHED_TRIM_SEGMENTS(sbi), sbi->segs_per_sec) - 1, end_segno); mutex_lock(&sbi->gc_mutex); err = write_checkpoint(sbi, &cpc); mutex_unlock(&sbi->gc_mutex); if (err) break; schedule(); } /* It's time to issue all the filed discards */ mark_discard_range_all(sbi); f2fs_wait_discard_bios(sbi, false); out: range->len = F2FS_BLK_TO_BYTES(cpc.trimmed); return err; }
169,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: static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } Commit Message: bluetooth: Validate socket address length in sco_sock_bind(). Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; if (addr_len < sizeof(struct sockaddr_sco)) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; }
167,532
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: l2tp_framing_type_print(netdissect_options *ndo, const u_char *dat) { const uint32_t *ptr = (const uint32_t *)dat; if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_ASYNC_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_SYNC_MASK) { ND_PRINT((ndo, "S")); } } Commit Message: CVE-2017-13006/L2TP: Check whether an AVP's content exceeds the AVP length. It's not good enough to check whether all the data specified by the AVP length was captured - you also have to check whether that length is large enough for all the required data in the AVP. This fixes a buffer over-read discovered by Yannick Formaggio. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
l2tp_framing_type_print(netdissect_options *ndo, const u_char *dat) l2tp_framing_type_print(netdissect_options *ndo, const u_char *dat, u_int length) { const uint32_t *ptr = (const uint32_t *)dat; if (length < 4) { ND_PRINT((ndo, "AVP too short")); return; } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_ASYNC_MASK) { ND_PRINT((ndo, "A")); } if (EXTRACT_32BITS(ptr) & L2TP_FRAMING_TYPE_SYNC_MASK) { ND_PRINT((ndo, "S")); } }
167,895
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_InitHooks(cJSON_Hooks* hooks) { if ( ! hooks ) { /* Reset hooks. */ cJSON_malloc = malloc; cJSON_free = free; return; } cJSON_malloc = (hooks->malloc_fn) ? hooks->malloc_fn : malloc; cJSON_free = (hooks->free_fn) ? hooks->free_fn : free; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
void cJSON_InitHooks(cJSON_Hooks* hooks) static char* cJSON_strdup(const char* str) {
167,290
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ ) { int rc = 0; gnutls_session *session = gnutls_malloc(sizeof(gnutls_session)); gnutls_init(session, type); # ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT /* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */ gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL); /* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */ # else gnutls_set_default_priority(*session); gnutls_kx_set_priority(*session, tls_kx_order); # endif gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock)); switch (type) { case GNUTLS_SERVER: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_s); break; case GNUTLS_CLIENT: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, anon_cred_c); break; } do { rc = gnutls_handshake(*session); } while (rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN); if (rc < 0) { crm_err("Handshake failed: %s", gnutls_strerror(rc)); gnutls_deinit(*session); gnutls_free(session); return NULL; } return session; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
create_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */ ) void * crm_create_anon_tls_session(int csock, int type /* GNUTLS_SERVER, GNUTLS_CLIENT */, void *credentials) { gnutls_session *session = gnutls_malloc(sizeof(gnutls_session)); gnutls_init(session, type); # ifdef HAVE_GNUTLS_PRIORITY_SET_DIRECT /* http://www.manpagez.com/info/gnutls/gnutls-2.10.4/gnutls_81.php#Echo-Server-with-anonymous-authentication */ gnutls_priority_set_direct(*session, "NORMAL:+ANON-DH", NULL); /* gnutls_priority_set_direct (*session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL); */ # else gnutls_set_default_priority(*session); gnutls_kx_set_priority(*session, anon_tls_kx_order); # endif gnutls_transport_set_ptr(*session, (gnutls_transport_ptr) GINT_TO_POINTER(csock)); switch (type) { case GNUTLS_SERVER: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_server_credentials_t) credentials); break; case GNUTLS_CLIENT: gnutls_credentials_set(*session, GNUTLS_CRD_ANON, (gnutls_anon_client_credentials_t) credentials); break; } return session; }
166,162
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); } Commit Message: Fix bug #72455: Heap Overflow due to integer overflows CWE ID: CWE-190
PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; if (data_size <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Integer overflow in data size"); RETURN_FALSE; } data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); }
167,091
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *b, *c = NULL, *u = NULL, *v = NULL, *tmp; int ret = 0; bn_check_top(a); bn_check_top(p); BN_CTX_start(ctx); if ((b = BN_CTX_get(ctx)) == NULL) goto err; if ((c = BN_CTX_get(ctx)) == NULL) goto err; if ((u = BN_CTX_get(ctx)) == NULL) goto err; if ((v = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_mod(u, a, p)) goto err; if (BN_is_zero(u)) goto err; if (!BN_copy(v, p)) goto err; # if 0 if (!BN_one(b)) goto err; while (1) { while (!BN_is_odd(u)) { if (BN_is_zero(u)) goto err; if (!BN_rshift1(u, u)) goto err; if (BN_is_odd(b)) { if (!BN_GF2m_add(b, b, p)) goto err; } if (!BN_rshift1(b, b)) goto err; } if (BN_abs_is_word(u, 1)) break; if (BN_num_bits(u) < BN_num_bits(v)) { tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; } if (!BN_GF2m_add(u, u, v)) goto err; if (!BN_GF2m_add(b, b, c)) goto err; } # else { int i, ubits = BN_num_bits(u), vbits = BN_num_bits(v), /* v is copy * of p */ top = p->top; BN_ULONG *udp, *bdp, *vdp, *cdp; bn_wexpand(u, top); udp = u->d; for (i = u->top; i < top; i++) udp[i] = 0; u->top = top; bn_wexpand(b, top); bdp = b->d; bdp[0] = 1; for (i = 1; i < top; i++) bdp[i] = 0; b->top = top; bn_wexpand(c, top); cdp = c->d; for (i = 0; i < top; i++) cdp[i] = 0; c->top = top; vdp = v->d; /* It pays off to "cache" *->d pointers, * because it allows optimizer to be more * aggressive. But we don't have to "cache" * p->d, because *p is declared 'const'... */ while (1) { while (ubits && !(udp[0] & 1)) { BN_ULONG u0, u1, b0, b1, mask; u0 = udp[0]; b0 = bdp[0]; mask = (BN_ULONG)0 - (b0 & 1); b0 ^= p->d[0] & mask; for (i = 0; i < top - 1; i++) { u1 = udp[i + 1]; udp[i] = ((u0 >> 1) | (u1 << (BN_BITS2 - 1))) & BN_MASK2; u0 = u1; b1 = bdp[i + 1] ^ (p->d[i + 1] & mask); bdp[i] = ((b0 >> 1) | (b1 << (BN_BITS2 - 1))) & BN_MASK2; b0 = b1; } udp[i] = u0 >> 1; bdp[i] = b0 >> 1; ubits--; } if (ubits <= BN_BITS2 && udp[0] == 1) break; if (ubits < vbits) { i = ubits; ubits = vbits; vbits = i; tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; udp = vdp; vdp = v->d; bdp = cdp; cdp = c->d; } for (i = 0; i < top; i++) { udp[i] ^= vdp[i]; bdp[i] ^= cdp[i]; } if (ubits == vbits) { BN_ULONG ul; int utop = (ubits - 1) / BN_BITS2; while ((ul = udp[utop]) == 0 && utop) utop--; ubits = utop * BN_BITS2 + BN_num_bits_word(ul); } } bn_correct_top(b); } # endif if (!BN_copy(r, b)) goto err; bn_check_top(r); ret = 1; err: # ifdef BN_DEBUG /* BN_CTX_end would complain about the * expanded form */ bn_correct_top(c); bn_correct_top(u); bn_correct_top(v); # endif BN_CTX_end(ctx); return ret; } Commit Message: bn/bn_gf2m.c: avoid infinite loop wich malformed ECParamters. CVE-2015-1788 Reviewed-by: Matt Caswell <[email protected]> CWE ID: CWE-399
int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *b, *c = NULL, *u = NULL, *v = NULL, *tmp; int ret = 0; bn_check_top(a); bn_check_top(p); BN_CTX_start(ctx); if ((b = BN_CTX_get(ctx)) == NULL) goto err; if ((c = BN_CTX_get(ctx)) == NULL) goto err; if ((u = BN_CTX_get(ctx)) == NULL) goto err; if ((v = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_mod(u, a, p)) goto err; if (BN_is_zero(u)) goto err; if (!BN_copy(v, p)) goto err; # if 0 if (!BN_one(b)) goto err; while (1) { while (!BN_is_odd(u)) { if (BN_is_zero(u)) goto err; if (!BN_rshift1(u, u)) goto err; if (BN_is_odd(b)) { if (!BN_GF2m_add(b, b, p)) goto err; } if (!BN_rshift1(b, b)) goto err; } if (BN_abs_is_word(u, 1)) break; if (BN_num_bits(u) < BN_num_bits(v)) { tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; } if (!BN_GF2m_add(u, u, v)) goto err; if (!BN_GF2m_add(b, b, c)) goto err; } # else { int i; int ubits = BN_num_bits(u); int vbits = BN_num_bits(v); /* v is copy of p */ int top = p->top; BN_ULONG *udp, *bdp, *vdp, *cdp; bn_wexpand(u, top); udp = u->d; for (i = u->top; i < top; i++) udp[i] = 0; u->top = top; bn_wexpand(b, top); bdp = b->d; bdp[0] = 1; for (i = 1; i < top; i++) bdp[i] = 0; b->top = top; bn_wexpand(c, top); cdp = c->d; for (i = 0; i < top; i++) cdp[i] = 0; c->top = top; vdp = v->d; /* It pays off to "cache" *->d pointers, * because it allows optimizer to be more * aggressive. But we don't have to "cache" * p->d, because *p is declared 'const'... */ while (1) { while (ubits && !(udp[0] & 1)) { BN_ULONG u0, u1, b0, b1, mask; u0 = udp[0]; b0 = bdp[0]; mask = (BN_ULONG)0 - (b0 & 1); b0 ^= p->d[0] & mask; for (i = 0; i < top - 1; i++) { u1 = udp[i + 1]; udp[i] = ((u0 >> 1) | (u1 << (BN_BITS2 - 1))) & BN_MASK2; u0 = u1; b1 = bdp[i + 1] ^ (p->d[i + 1] & mask); bdp[i] = ((b0 >> 1) | (b1 << (BN_BITS2 - 1))) & BN_MASK2; b0 = b1; } udp[i] = u0 >> 1; bdp[i] = b0 >> 1; ubits--; } if (ubits <= BN_BITS2) { if (udp[0] == 0) /* poly was reducible */ goto err; if (udp[0] == 1) break; } if (ubits < vbits) { i = ubits; ubits = vbits; vbits = i; tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; udp = vdp; vdp = v->d; bdp = cdp; cdp = c->d; } for (i = 0; i < top; i++) { udp[i] ^= vdp[i]; bdp[i] ^= cdp[i]; } if (ubits == vbits) { BN_ULONG ul; int utop = (ubits - 1) / BN_BITS2; while ((ul = udp[utop]) == 0 && utop) utop--; ubits = utop * BN_BITS2 + BN_num_bits_word(ul); } } bn_correct_top(b); } # endif if (!BN_copy(r, b)) goto err; bn_check_top(r); ret = 1; err: # ifdef BN_DEBUG /* BN_CTX_end would complain about the * expanded form */ bn_correct_top(c); bn_correct_top(u); bn_correct_top(v); # endif BN_CTX_end(ctx); return ret; }
166,694
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int em_fxrstor(struct x86_emulate_ctxt *ctxt) { struct fxregs_state fx_state; int rc; rc = check_fxsr(ctxt); if (rc != X86EMUL_CONTINUE) return rc; rc = segmented_read(ctxt, ctxt->memop.addr.mem, &fx_state, 512); if (rc != X86EMUL_CONTINUE) return rc; if (fx_state.mxcsr >> 16) return emulate_gp(ctxt, 0); ctxt->ops->get_fpu(ctxt); if (ctxt->mode < X86EMUL_MODE_PROT64) rc = fxrstor_fixup(ctxt, &fx_state); if (rc == X86EMUL_CONTINUE) rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state)); ctxt->ops->put_fpu(ctxt); return rc; } Commit Message: KVM: x86: Introduce segmented_write_std Introduces segemented_write_std. Switches from emulated reads/writes to standard read/writes in fxsave, fxrstor, sgdt, and sidt. This fixes CVE-2017-2584, a longstanding kernel memory leak. Since commit 283c95d0e389 ("KVM: x86: emulate FXSAVE and FXRSTOR", 2016-11-09), which is luckily not yet in any final release, this would also be an exploitable kernel memory *write*! Reported-by: Dmitry Vyukov <[email protected]> Cc: [email protected] Fixes: 96051572c819194c37a8367624b285be10297eca Fixes: 283c95d0e3891b64087706b344a4b545d04a6e62 Suggested-by: Paolo Bonzini <[email protected]> Signed-off-by: Steve Rutherford <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-416
static int em_fxrstor(struct x86_emulate_ctxt *ctxt) { struct fxregs_state fx_state; int rc; rc = check_fxsr(ctxt); if (rc != X86EMUL_CONTINUE) return rc; rc = segmented_read_std(ctxt, ctxt->memop.addr.mem, &fx_state, 512); if (rc != X86EMUL_CONTINUE) return rc; if (fx_state.mxcsr >> 16) return emulate_gp(ctxt, 0); ctxt->ops->get_fpu(ctxt); if (ctxt->mode < X86EMUL_MODE_PROT64) rc = fxrstor_fixup(ctxt, &fx_state); if (rc == X86EMUL_CONTINUE) rc = asm_safe("fxrstor %[fx]", : [fx] "m"(fx_state)); ctxt->ops->put_fpu(ctxt); return rc; }
168,444
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BluetoothDeviceChromeOS::ExpectingPasskey() const { return !passkey_callback_.is_null(); } Commit Message: Refactor to support default Bluetooth pairing delegate In order to support a default pairing delegate we need to move the agent service provider delegate implementation from BluetoothDevice to BluetoothAdapter while retaining the existing API. BUG=338492 TEST=device_unittests, unit_tests, browser_tests Review URL: https://codereview.chromium.org/148293003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
bool BluetoothDeviceChromeOS::ExpectingPasskey() const { return pairing_context_.get() && pairing_context_->ExpectingPasskey(); }
171,225
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = 0; memset(&sllc, 0, sizeof(sllc)); lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); memset(uaddr, 0, *uaddrlen); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; } Commit Message: llc: fix info leak via getsockname() The LLC code wrongly returns 0, i.e. "success", when the socket is zapped. Together with the uninitialized uaddrlen pointer argument from sys_getsockname this leads to an arbitrary memory leak of up to 128 bytes kernel stack via the getsockname() syscall. Return an error instead when the socket is zapped to prevent the info leak. Also remove the unnecessary memset(0). We don't directly write to the memory pointed by uaddr but memcpy() a local structure at the end of the function that is properly initialized. Signed-off-by: Mathias Krause <[email protected]> Cc: Arnaldo Carvalho de Melo <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = -EBADF; memset(&sllc, 0, sizeof(sllc)); lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; }
166,184
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: vips_foreign_load_start( VipsImage *out, void *a, void *b ) { VipsForeignLoad *load = VIPS_FOREIGN_LOAD( b ); VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load ); if( !load->real ) { if( !(load->real = vips_foreign_load_temp( load )) ) return( NULL ); #ifdef DEBUG printf( "vips_foreign_load_start: triggering ->load()\n" ); #endif /*DEBUG*/ /* Read the image in. This may involve a long computation and * will finish with load->real holding the decompressed image. * * We want our caller to be able to see this computation on * @out, so eval signals on ->real need to appear on ->out. */ load->real->progress_signal = load->out; /* Note the load object on the image. Loaders can use * this to signal invalidate if they hit a load error. See * vips_foreign_load_invalidate() below. */ g_object_set_qdata( G_OBJECT( load->real ), vips__foreign_load_operation, load ); if( class->load( load ) || vips_image_pio_input( load->real ) ) return( NULL ); /* ->header() read the header into @out, load has read the * image into @real. They must match exactly in size, bands, * format and coding for the copy to work. * * Some versions of ImageMagick give different results between * Ping and Load for some formats, for example. */ if( !vips_foreign_load_iscompat( load->real, out ) ) return( NULL ); /* We have to tell vips that out depends on real. We've set * the demand hint below, but not given an input there. */ vips_image_pipelinev( load->out, load->out->dhint, load->real, NULL ); } return( vips_region_new( load->real ) ); } Commit Message: fix a crash with delayed load If a delayed load failed, it could leave the pipeline only half-set up. Sebsequent threads could then segv. Set a load-has-failed flag and test before generate. See https://github.com/jcupitt/libvips/issues/893 CWE ID: CWE-362
vips_foreign_load_start( VipsImage *out, void *a, void *b ) { VipsForeignLoad *load = VIPS_FOREIGN_LOAD( b ); VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load ); /* If this start has failed before in another thread, we can fail now. */ if( load->error ) return( NULL ); if( !load->real ) { if( !(load->real = vips_foreign_load_temp( load )) ) return( NULL ); #ifdef DEBUG printf( "vips_foreign_load_start: triggering ->load()\n" ); #endif /*DEBUG*/ /* Read the image in. This may involve a long computation and * will finish with load->real holding the decompressed image. * * We want our caller to be able to see this computation on * @out, so eval signals on ->real need to appear on ->out. */ load->real->progress_signal = load->out; /* Note the load object on the image. Loaders can use * this to signal invalidate if they hit a load error. See * vips_foreign_load_invalidate() below. */ g_object_set_qdata( G_OBJECT( load->real ), vips__foreign_load_operation, load ); /* Load the image and check the result. * * ->header() read the header into @out, load has read the * image into @real. They must match exactly in size, bands, * format and coding for the copy to work. * * Some versions of ImageMagick give different results between * Ping and Load for some formats, for example. * * If the load fails, we need to stop */ if( class->load( load ) || vips_image_pio_input( load->real ) || vips_foreign_load_iscompat( load->real, out ) ) { vips_operation_invalidate( VIPS_OPERATION( load ) ); load->error = TRUE; return( NULL ); } /* We have to tell vips that out depends on real. We've set * the demand hint below, but not given an input there. */ vips_image_pipelinev( load->out, load->out->dhint, load->real, NULL ); } return( vips_region_new( load->real ) ); }
169,304
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool semaphore_try_wait(semaphore_t *semaphore) { assert(semaphore != NULL); assert(semaphore->fd != INVALID_FD); int flags = fcntl(semaphore->fd, F_GETFL); if (flags == -1) { LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno)); return false; } if (fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK) == -1) { LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno)); return false; } eventfd_t value; if (eventfd_read(semaphore->fd, &value) == -1) return false; if (fcntl(semaphore->fd, F_SETFL, flags) == -1) LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno)); return true; } 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
bool semaphore_try_wait(semaphore_t *semaphore) { assert(semaphore != NULL); assert(semaphore->fd != INVALID_FD); int flags = TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_GETFL)); if (flags == -1) { LOG_ERROR("%s unable to get flags for semaphore fd: %s", __func__, strerror(errno)); return false; } if (TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_SETFL, flags | O_NONBLOCK)) == -1) { LOG_ERROR("%s unable to set O_NONBLOCK for semaphore fd: %s", __func__, strerror(errno)); return false; } eventfd_t value; if (eventfd_read(semaphore->fd, &value) == -1) return false; if (TEMP_FAILURE_RETRY(fcntl(semaphore->fd, F_SETFL, flags)) == -1) LOG_ERROR("%s unable to resetore flags for semaphore fd: %s", __func__, strerror(errno)); return true; }
173,483
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cJSON *cJSON_CreateNull( void ) { cJSON *item = cJSON_New_Item(); if ( item ) item->type = cJSON_NULL; return item; } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
cJSON *cJSON_CreateNull( void )
167,276
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: bool DataReductionProxySettings::IsDataSaverEnabledByUser() const { //// static if (params::ShouldForceEnableDataReductionProxy()) return true; if (spdy_proxy_auth_enabled_.GetPrefName().empty()) return false; return spdy_proxy_auth_enabled_.GetValue(); } Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it This method now officially becomes the source of truth that everything in the code base eventually calls into to determine whether or not DataSaver is enabled. Bug: 934399 Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242 Reviewed-by: Joshua Pawlicki <[email protected]> Reviewed-by: Tarun Bansal <[email protected]> Commit-Queue: Robert Ogden <[email protected]> Cr-Commit-Position: refs/heads/master@{#643948} CWE ID: CWE-119
bool DataReductionProxySettings::IsDataSaverEnabledByUser() const { //// static bool DataReductionProxySettings::IsDataSaverEnabledByUser(PrefService* prefs) { if (params::ShouldForceEnableDataReductionProxy()) return true; return prefs && prefs->GetBoolean(prefs::kDataSaverEnabled); }
172,556
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); } Commit Message: issue #54: fix potential out-of-bounds heap read CWE ID: CWE-125
int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum) { WavpackHeader *wphdr = (WavpackHeader *) buffer; uint32_t checksum_passed = 0, bcount, meta_bc; unsigned char *dp, meta_id, c1, c2; if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader)) return FALSE; bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8; dp = (unsigned char *)(wphdr + 1); while (bcount >= 2) { meta_id = *dp++; c1 = *dp++; meta_bc = c1 << 1; bcount -= 2; if (meta_id & ID_LARGE) { if (bcount < 2) return FALSE; c1 = *dp++; c2 = *dp++; meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17); bcount -= 2; } if (bcount < meta_bc) return FALSE; if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) { #ifdef BITSTREAM_SHORTS uint16_t *csptr = (uint16_t*) buffer; #else unsigned char *csptr = buffer; #endif int wcount = (int)(dp - 2 - buffer) >> 1; uint32_t csum = (uint32_t) -1; if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4) return FALSE; #ifdef BITSTREAM_SHORTS while (wcount--) csum = (csum * 3) + *csptr++; #else WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat); while (wcount--) { csum = (csum * 3) + csptr [0] + (csptr [1] << 8); csptr += 2; } WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat); #endif if (meta_bc == 4) { if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff) || dp[2] != ((csum >> 16) & 0xff) || dp[3] != ((csum >> 24) & 0xff)) return FALSE; } else { csum ^= csum >> 16; if (*dp != (csum & 0xff) || dp[1] != ((csum >> 8) & 0xff)) return FALSE; } checksum_passed++; } bcount -= meta_bc; dp += meta_bc; } return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed); }
168,971
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void LauncherView::Init() { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); model_->AddObserver(this); const LauncherItems& items(model_->items()); for (LauncherItems::const_iterator i = items.begin(); i != items.end(); ++i) { views::View* child = CreateViewForItem(*i); child->SetPaintToLayer(true); view_model_->Add(child, static_cast<int>(i - items.begin())); AddChildView(child); } UpdateFirstButtonPadding(); overflow_button_ = new views::ImageButton(this); overflow_button_->set_accessibility_focusable(true); overflow_button_->SetImage( views::CustomButton::BS_NORMAL, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW).ToImageSkia()); overflow_button_->SetImage( views::CustomButton::BS_HOT, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_HOT).ToImageSkia()); overflow_button_->SetImage( views::CustomButton::BS_PUSHED, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_PUSHED).ToImageSkia()); overflow_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_AURA_LAUNCHER_OVERFLOW_NAME)); overflow_button_->set_context_menu_controller(this); ConfigureChildView(overflow_button_); AddChildView(overflow_button_); } Commit Message: ash: Add launcher overflow bubble. - Host a LauncherView in bubble to display overflown items; - Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown; - Fit bubble when items are added/removed; - Keep launcher bar on screen when the bubble is shown; BUG=128054 TEST=Verify launcher overflown items are in a bubble instead of menu. Review URL: https://chromiumcodereview.appspot.com/10659003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
void LauncherView::Init() { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); model_->AddObserver(this); const LauncherItems& items(model_->items()); for (LauncherItems::const_iterator i = items.begin(); i != items.end(); ++i) { views::View* child = CreateViewForItem(*i); child->SetPaintToLayer(true); view_model_->Add(child, static_cast<int>(i - items.begin())); AddChildView(child); } UpdateFirstButtonPadding(); overflow_button_ = new views::ImageButton(this); overflow_button_->set_accessibility_focusable(true); overflow_button_->SetImageAlignment(views::ImageButton::ALIGN_CENTER, views::ImageButton::ALIGN_MIDDLE); overflow_button_->SetImage( views::CustomButton::BS_NORMAL, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW).ToImageSkia()); overflow_button_->SetImage( views::CustomButton::BS_HOT, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_HOT).ToImageSkia()); overflow_button_->SetImage( views::CustomButton::BS_PUSHED, rb.GetImageNamed(IDR_AURA_LAUNCHER_OVERFLOW_PUSHED).ToImageSkia()); overflow_button_->SetAccessibleName( l10n_util::GetStringUTF16(IDS_AURA_LAUNCHER_OVERFLOW_NAME)); overflow_button_->set_context_menu_controller(this); ConfigureChildView(overflow_button_); AddChildView(overflow_button_); }
170,890
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; } 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 char* Track::GetCodecNameAsUTF8() const
174,294
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int ext4_split_unwritten_extents(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags) { ext4_lblk_t eof_block; ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len; int split_flag = 0, depth; ext_debug("ext4_split_unwritten_extents: inode %lu, logical" "block %llu, max_blocks %u\n", inode->i_ino, (unsigned long long)map->m_lblk, map->m_len); eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits; if (eof_block < map->m_lblk + map->m_len) eof_block = map->m_lblk + map->m_len; /* * It is safe to convert extent to initialized via explicit * zeroout only if extent is fully insde i_size or new_size. */ depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0; split_flag |= EXT4_EXT_MARK_UNINIT2; flags |= EXT4_GET_BLOCKS_PRE_IO; return ext4_split_extent(handle, inode, path, map, split_flag, flags); } Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio We assumed that at the time we call ext4_convert_unwritten_extents_endio() extent in question is fully inside [map.m_lblk, map->m_len] because it was already split during submission. But this may not be true due to a race between writeback vs fallocate. If extent in question is larger than requested we will split it again. Special precautions should being done if zeroout required because [map.m_lblk, map->m_len] already contains valid data. Signed-off-by: Dmitry Monakhov <[email protected]> Signed-off-by: "Theodore Ts'o" <[email protected]> Cc: [email protected] CWE ID: CWE-362
static int ext4_split_unwritten_extents(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, struct ext4_ext_path *path, int flags) { ext4_lblk_t eof_block; ext4_lblk_t ee_block; struct ext4_extent *ex; unsigned int ee_len; int split_flag = 0, depth; ext_debug("ext4_split_unwritten_extents: inode %lu, logical" "block %llu, max_blocks %u\n", inode->i_ino, (unsigned long long)map->m_lblk, map->m_len); eof_block = (inode->i_size + inode->i_sb->s_blocksize - 1) >> inode->i_sb->s_blocksize_bits; if (eof_block < map->m_lblk + map->m_len) eof_block = map->m_lblk + map->m_len; /* * It is safe to convert extent to initialized via explicit * zeroout only if extent is fully insde i_size or new_size. */ depth = ext_depth(inode); ex = path[depth].p_ext; ee_block = le32_to_cpu(ex->ee_block); ee_len = ext4_ext_get_actual_len(ex); split_flag |= ee_block + ee_len <= eof_block ? EXT4_EXT_MAY_ZEROOUT : 0; split_flag |= EXT4_EXT_MARK_UNINIT2; if (flags & EXT4_GET_BLOCKS_CONVERT) split_flag |= EXT4_EXT_DATA_VALID2; flags |= EXT4_GET_BLOCKS_PRE_IO; return ext4_split_extent(handle, inode, path, map, split_flag, flags); }
165,535
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void cJSON_AddItemToArray( cJSON *array, cJSON *item ) { cJSON *c = array->child; if ( ! item ) return; if ( ! c ) { array->child = item; } else { while ( c && c->next ) c = c->next; suffix_object( c, item ); } } Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a malformed JSON string was passed on the control channel. This issue, present in the cJSON library, was already fixed upstream, so was addressed here in iperf3 by importing a newer version of cJSON (plus local ESnet modifications). Discovered and reported by Dave McDaniel, Cisco Talos. Based on a patch by @dopheide-esnet, with input from @DaveGamble. Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001, CVE-2016-4303 (cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40) Signed-off-by: Bruce A. Mah <[email protected]> CWE ID: CWE-119
void cJSON_AddItemToArray( cJSON *array, cJSON *item )
167,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: chpass_principal_2_svc(chpass_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name, service_name; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ, FALSE, 0, NULL, arg->pass); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_chpass_principal((void *)handle, arg->princ, arg->pass); } else { log_unauth("kadm5_chpass_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if (ret.code != KADM5_AUTH_CHANGEPW) { if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_chpass_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); exit_func: free_server_handle(handle); return &ret; } Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631] In each kadmind server stub, initialize the client_name and server_name variables, and release them in the cleanup handler. Many of the stubs will otherwise leak the client and server name if krb5_unparse_name() fails. Also make sure to free the prime_arg variables in rename_principal_2_svc(), or we can leak the first one if unparsing the second one fails. Discovered by Simo Sorce. CVE-2015-8631: In all versions of MIT krb5, an authenticated attacker can cause kadmind to leak memory by supplying a null principal name in a request which uses one. Repeating these requests will eventually cause kadmind to exhaust all available memory. CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C ticket: 8343 (new) target_version: 1.14-next target_version: 1.13-next tags: pullup CWE ID: CWE-119
chpass_principal_2_svc(chpass_arg *arg, struct svc_req *rqstp) { static generic_ret ret; char *prime_arg; gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER; gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER; OM_uint32 minor_stat; kadm5_server_handle_t handle; const char *errmsg = NULL; xdr_free(xdr_generic_ret, &ret); if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle))) goto exit_func; if ((ret.code = check_handle((void *)handle))) goto exit_func; ret.api_version = handle->api_version; if (setup_gss_names(rqstp, &client_name, &service_name) < 0) { ret.code = KADM5_FAILURE; goto exit_func; } if (krb5_unparse_name(handle->context, arg->princ, &prime_arg)) { ret.code = KADM5_BAD_PRINCIPAL; goto exit_func; } if (cmp_gss_krb5_name(handle, rqst2name(rqstp), arg->princ)) { ret.code = chpass_principal_wrapper_3((void *)handle, arg->princ, FALSE, 0, NULL, arg->pass); } else if (!(CHANGEPW_SERVICE(rqstp)) && kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_CHANGEPW, arg->princ, NULL)) { ret.code = kadm5_chpass_principal((void *)handle, arg->princ, arg->pass); } else { log_unauth("kadm5_chpass_principal", prime_arg, &client_name, &service_name, rqstp); ret.code = KADM5_AUTH_CHANGEPW; } if (ret.code != KADM5_AUTH_CHANGEPW) { if (ret.code != 0) errmsg = krb5_get_error_message(handle->context, ret.code); log_done("kadm5_chpass_principal", prime_arg, errmsg, &client_name, &service_name, rqstp); if (errmsg != NULL) krb5_free_error_message(handle->context, errmsg); } free(prime_arg); exit_func: gss_release_buffer(&minor_stat, &client_name); gss_release_buffer(&minor_stat, &service_name); free_server_handle(handle); return &ret; }
167,505
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Chapters::Display::~Display() { } 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
Chapters::Display::~Display()
174,464
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { int end = readU16(data, kEndCountOffset + 2 * i); int start = readU16(data, kHeaderSize + 2 * (segCount + i)); int rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { int delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (int j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (int j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { return false; } int glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; } Commit Message: Reject fonts with invalid ranges in cmap A corrupt or malicious font may have a negative size in its cmap range, which in turn could lead to memory corruption. This patch detects the case and rejects the font, and also includes an assertion in the sparse bit set implementation if we missed any such case. External issue: https://code.google.com/p/android/issues/detail?id=192618 Bug: 26413177 Change-Id: Icc0c80e4ef389abba0964495b89aa0fae3e9f4b2 CWE ID: CWE-20
static bool getCoverageFormat4(vector<uint32_t>& coverage, const uint8_t* data, size_t size) { const size_t kSegCountOffset = 6; const size_t kEndCountOffset = 14; const size_t kHeaderSize = 16; const size_t kSegmentSize = 8; // total size of array elements for one segment if (kEndCountOffset > size) { return false; } size_t segCount = readU16(data, kSegCountOffset) >> 1; if (kHeaderSize + segCount * kSegmentSize > size) { return false; } for (size_t i = 0; i < segCount; i++) { uint32_t end = readU16(data, kEndCountOffset + 2 * i); uint32_t start = readU16(data, kHeaderSize + 2 * (segCount + i)); if (end < start) { // invalid segment range: size must be positive return false; } uint32_t rangeOffset = readU16(data, kHeaderSize + 2 * (3 * segCount + i)); if (rangeOffset == 0) { uint32_t delta = readU16(data, kHeaderSize + 2 * (2 * segCount + i)); if (((end + delta) & 0xffff) > end - start) { addRange(coverage, start, end + 1); } else { for (uint32_t j = start; j < end + 1; j++) { if (((j + delta) & 0xffff) != 0) { addRange(coverage, j, j + 1); } } } } else { for (uint32_t j = start; j < end + 1; j++) { uint32_t actualRangeOffset = kHeaderSize + 6 * segCount + rangeOffset + (i + j - start) * 2; if (actualRangeOffset + 2 > size) { return false; } uint32_t glyphId = readU16(data, actualRangeOffset); if (glyphId != 0) { addRange(coverage, j, j + 1); } } } } return true; }
174,235
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci) { struct sock *sk; struct sock *make; struct rose_sock *make_rose; struct rose_facilities_struct facilities; int n, len; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the rose frame start */ memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); len = (((skb->data[3] >> 4) & 0x0F) + 1) >> 1; len += (((skb->data[3] >> 0) & 0x0F) + 1) >> 1; if (!rose_parse_facilities(skb->data + len + 4, &facilities)) { rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76); return 0; } sk = rose_find_listener(&facilities.source_addr, &facilities.source_call); /* * We can't accept the Call Request. */ if (sk == NULL || sk_acceptq_is_full(sk) || (make = rose_make_new(sk)) == NULL) { rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120); return 0; } skb->sk = make; make->sk_state = TCP_ESTABLISHED; make_rose = rose_sk(make); make_rose->lci = lci; make_rose->dest_addr = facilities.dest_addr; make_rose->dest_call = facilities.dest_call; make_rose->dest_ndigis = facilities.dest_ndigis; for (n = 0 ; n < facilities.dest_ndigis ; n++) make_rose->dest_digis[n] = facilities.dest_digis[n]; make_rose->source_addr = facilities.source_addr; make_rose->source_call = facilities.source_call; make_rose->source_ndigis = facilities.source_ndigis; for (n = 0 ; n < facilities.source_ndigis ; n++) make_rose->source_digis[n]= facilities.source_digis[n]; make_rose->neighbour = neigh; make_rose->device = dev; make_rose->facilities = facilities; make_rose->neighbour->use++; if (rose_sk(sk)->defer) { make_rose->state = ROSE_STATE_5; } else { rose_write_internal(make, ROSE_CALL_ACCEPTED); make_rose->state = ROSE_STATE_3; rose_start_idletimer(make); } make_rose->condition = 0x00; make_rose->vs = 0; make_rose->va = 0; make_rose->vr = 0; make_rose->vl = 0; sk->sk_ack_backlog++; rose_insert_socket(make); skb_queue_head(&sk->sk_receive_queue, skb); rose_start_heartbeat(make); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 1; } Commit Message: rose: Add length checks to CALL_REQUEST parsing Define some constant offsets for CALL_REQUEST based on the description at <http://www.techfest.com/networking/wan/x25plp.htm> and the definition of ROSE as using 10-digit (5-byte) addresses. Use them consistently. Validate all implicit and explicit facilities lengths. Validate the address length byte rather than either trusting or assuming its value. Signed-off-by: Ben Hutchings <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
int rose_rx_call_request(struct sk_buff *skb, struct net_device *dev, struct rose_neigh *neigh, unsigned int lci) { struct sock *sk; struct sock *make; struct rose_sock *make_rose; struct rose_facilities_struct facilities; int n; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the rose frame start */ memset(&facilities, 0x00, sizeof(struct rose_facilities_struct)); if (!rose_parse_facilities(skb->data + ROSE_CALL_REQ_FACILITIES_OFF, skb->len - ROSE_CALL_REQ_FACILITIES_OFF, &facilities)) { rose_transmit_clear_request(neigh, lci, ROSE_INVALID_FACILITY, 76); return 0; } sk = rose_find_listener(&facilities.source_addr, &facilities.source_call); /* * We can't accept the Call Request. */ if (sk == NULL || sk_acceptq_is_full(sk) || (make = rose_make_new(sk)) == NULL) { rose_transmit_clear_request(neigh, lci, ROSE_NETWORK_CONGESTION, 120); return 0; } skb->sk = make; make->sk_state = TCP_ESTABLISHED; make_rose = rose_sk(make); make_rose->lci = lci; make_rose->dest_addr = facilities.dest_addr; make_rose->dest_call = facilities.dest_call; make_rose->dest_ndigis = facilities.dest_ndigis; for (n = 0 ; n < facilities.dest_ndigis ; n++) make_rose->dest_digis[n] = facilities.dest_digis[n]; make_rose->source_addr = facilities.source_addr; make_rose->source_call = facilities.source_call; make_rose->source_ndigis = facilities.source_ndigis; for (n = 0 ; n < facilities.source_ndigis ; n++) make_rose->source_digis[n]= facilities.source_digis[n]; make_rose->neighbour = neigh; make_rose->device = dev; make_rose->facilities = facilities; make_rose->neighbour->use++; if (rose_sk(sk)->defer) { make_rose->state = ROSE_STATE_5; } else { rose_write_internal(make, ROSE_CALL_ACCEPTED); make_rose->state = ROSE_STATE_3; rose_start_idletimer(make); } make_rose->condition = 0x00; make_rose->vs = 0; make_rose->va = 0; make_rose->vr = 0; make_rose->vl = 0; sk->sk_ack_backlog++; rose_insert_socket(make); skb_queue_head(&sk->sk_receive_queue, skb); rose_start_heartbeat(make); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); return 1; }
165,669
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FUNC_DECODER(dissector_postgresql) { DECLARE_DISP_PTR(ptr); struct ec_session *s = NULL; void *ident = NULL; char tmp[MAX_ASCII_ADDR_LEN]; struct postgresql_status *conn_status; /* don't complain about unused var */ (void) DECODE_DATA; (void) DECODE_DATALEN; (void) DECODED_LEN; if (FROM_CLIENT("postgresql", PACKET)) { if (PACKET->DATA.len < 4) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); /* if the session does not exist... */ if (session_get(&s, ident, DISSECT_IDENT_LEN) == -ENOTFOUND) { /* search for user and database strings, look for StartupMessage */ unsigned char *u = memmem(ptr, PACKET->DATA.len, "user", 4); unsigned char *d = memmem(ptr, PACKET->DATA.len, "database", 8); if (!memcmp(ptr + 4, "\x00\x03\x00\x00", 4) && u && d) { /* create the new session */ dissect_create_session(&s, PACKET, DISSECT_CODE(dissector_postgresql)); /* remember the state (used later) */ SAFE_CALLOC(s->data, 1, sizeof(struct postgresql_status)); conn_status = (struct postgresql_status *) s->data; conn_status->status = WAIT_AUTH; /* user is always null-terminated */ strncpy((char*)conn_status->user, (char*)(u + 5), 65); conn_status->user[64] = 0; /* database is always null-terminated */ strncpy((char*)conn_status->database, (char*)(d + 9), 65); conn_status->database[64] = 0; /* save the session */ session_put(s); } } else { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_RESPONSE) { /* check for PasswordMessage packet */ if (ptr[0] == 'p' && conn_status->type == MD5) { DEBUG_MSG("\tDissector_postgresql RESPONSE type is MD5"); if(memcmp(ptr + 1, "\x00\x00\x00\x28", 4)) { DEBUG_MSG("\tDissector_postgresql BUG, expected length is 40"); return NULL; } if (PACKET->DATA.len < 40) { DEBUG_MSG("\tDissector_postgresql BUG, expected length is 40"); return NULL; } memcpy(conn_status->hash, ptr + 5 + 3, 32); conn_status->hash[32] = 0; DISSECT_MSG("%s:$postgres$%s*%s*%s:%s:%d\n", conn_status->user, conn_status->user, conn_status->salt, conn_status->hash, ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst)); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } else if (ptr[0] == 'p' && conn_status->type == CT) { int length; DEBUG_MSG("\tDissector_postgresql RESPONSE type is clear-text!"); GET_ULONG_BE(length, ptr, 1); strncpy((char*)conn_status->password, (char*)(ptr + 5), length - 4); conn_status->password[length - 4] = 0; DISSECT_MSG("PostgreSQL credentials:%s-%d:%s:%s\n", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), conn_status->user, conn_status->password); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } } } } else { /* Packets coming from the server */ if (PACKET->DATA.len < 9) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); if (session_get(&s, ident, DISSECT_IDENT_LEN) == ESUCCESS) { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, "\x00\x00\x00\x0c", 4) && !memcmp(ptr + 5, "\x00\x00\x00\x05", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = MD5; DEBUG_MSG("\tDissector_postgresql AUTH type is MD5"); hex_encode(ptr + 9, 4, conn_status->salt); /* save salt */ } else if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, "\x00\x00\x00\x08", 4) && !memcmp(ptr + 5, "\x00\x00\x00\x03", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = CT; DEBUG_MSG("\tDissector_postgresql AUTH type is clear-text!"); } } } SAFE_FREE(ident); return NULL; } Commit Message: Fixed heap overflow caused by length CWE ID: CWE-119
FUNC_DECODER(dissector_postgresql) { DECLARE_DISP_PTR(ptr); struct ec_session *s = NULL; void *ident = NULL; char tmp[MAX_ASCII_ADDR_LEN]; struct postgresql_status *conn_status; /* don't complain about unused var */ (void) DECODE_DATA; (void) DECODE_DATALEN; (void) DECODED_LEN; if (FROM_CLIENT("postgresql", PACKET)) { if (PACKET->DATA.len < 4) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); /* if the session does not exist... */ if (session_get(&s, ident, DISSECT_IDENT_LEN) == -ENOTFOUND) { /* search for user and database strings, look for StartupMessage */ unsigned char *u = memmem(ptr, PACKET->DATA.len, "user", 4); unsigned char *d = memmem(ptr, PACKET->DATA.len, "database", 8); if (!memcmp(ptr + 4, "\x00\x03\x00\x00", 4) && u && d) { /* create the new session */ dissect_create_session(&s, PACKET, DISSECT_CODE(dissector_postgresql)); /* remember the state (used later) */ SAFE_CALLOC(s->data, 1, sizeof(struct postgresql_status)); conn_status = (struct postgresql_status *) s->data; conn_status->status = WAIT_AUTH; /* user is always null-terminated */ strncpy((char*)conn_status->user, (char*)(u + 5), 65); conn_status->user[64] = 0; /* database is always null-terminated */ strncpy((char*)conn_status->database, (char*)(d + 9), 65); conn_status->database[64] = 0; /* save the session */ session_put(s); } } else { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_RESPONSE) { /* check for PasswordMessage packet */ if (ptr[0] == 'p' && conn_status->type == MD5) { DEBUG_MSG("\tDissector_postgresql RESPONSE type is MD5"); if(memcmp(ptr + 1, "\x00\x00\x00\x28", 4)) { DEBUG_MSG("\tDissector_postgresql BUG, expected length is 40"); return NULL; } if (PACKET->DATA.len < 40) { DEBUG_MSG("\tDissector_postgresql BUG, expected length is 40"); return NULL; } memcpy(conn_status->hash, ptr + 5 + 3, 32); conn_status->hash[32] = 0; DISSECT_MSG("%s:$postgres$%s*%s*%s:%s:%d\n", conn_status->user, conn_status->user, conn_status->salt, conn_status->hash, ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst)); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } else if (ptr[0] == 'p' && conn_status->type == CT) { int length; DEBUG_MSG("\tDissector_postgresql RESPONSE type is clear-text!"); GET_ULONG_BE(length, ptr, 1); length -= 4; if (length < 0 || length > 65 || PACKET->DATA.len < length+5) { dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); return NULL; } snprintf((char*)conn_status->password, length+1, "%s", (char*)(ptr + 5)); DISSECT_MSG("PostgreSQL credentials:%s-%d:%s:%s\n", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), conn_status->user, conn_status->password); dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql)); } } } } else { /* Packets coming from the server */ if (PACKET->DATA.len < 9) return NULL; dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql)); if (session_get(&s, ident, DISSECT_IDENT_LEN) == ESUCCESS) { conn_status = (struct postgresql_status *) s->data; if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, "\x00\x00\x00\x0c", 4) && !memcmp(ptr + 5, "\x00\x00\x00\x05", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = MD5; DEBUG_MSG("\tDissector_postgresql AUTH type is MD5"); hex_encode(ptr + 9, 4, conn_status->salt); /* save salt */ } else if (conn_status->status == WAIT_AUTH && ptr[0] == 'R' && !memcmp(ptr + 1, "\x00\x00\x00\x08", 4) && !memcmp(ptr + 5, "\x00\x00\x00\x03", 4)) { conn_status->status = WAIT_RESPONSE; conn_status->type = CT; DEBUG_MSG("\tDissector_postgresql AUTH type is clear-text!"); } } } SAFE_FREE(ident); return NULL; }
166,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; } Commit Message: avcodec/jpeg2000dec: prevent out of array accesses in pixel addressing Fixes Ticket2921 Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-119
static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, AVFrame *picture) { int compno, reslevelno, bandno; int x, y; uint8_t *line; Jpeg2000T1Context t1; /* Loop on tile components */ for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; /* Loop on resolution levels */ for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) { Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno; /* Loop on bands */ for (bandno = 0; bandno < rlevel->nbands; bandno++) { int nb_precincts, precno; Jpeg2000Band *band = rlevel->band + bandno; int cblkno = 0, bandpos; bandpos = bandno + (reslevelno > 0); if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1]) continue; nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y; /* Loop on precincts */ for (precno = 0; precno < nb_precincts; precno++) { Jpeg2000Prec *prec = band->prec + precno; /* Loop on codeblocks */ for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) { int x, y; Jpeg2000Cblk *cblk = prec->cblk + cblkno; decode_cblk(s, codsty, &t1, cblk, cblk->coord[0][1] - cblk->coord[0][0], cblk->coord[1][1] - cblk->coord[1][0], bandpos); x = cblk->coord[0][0]; y = cblk->coord[1][0]; if (codsty->transform == FF_DWT97) dequantization_float(x, y, cblk, comp, &t1, band); else dequantization_int(x, y, cblk, comp, &t1, band); } /* end cblk */ } /*end prec */ } /* end band */ } /* end reslevel */ /* inverse DWT */ ff_dwt_decode(&comp->dwt, codsty->transform == FF_DWT97 ? (void*)comp->f_data : (void*)comp->i_data); } /*end comp */ /* inverse MCT transformation */ if (tile->codsty[0].mct) mct_decode(s, tile); if (s->cdef[0] < 0) { for (x = 0; x < s->ncomponents; x++) s->cdef[x] = x + 1; if ((s->ncomponents & 1) == 0) s->cdef[s->ncomponents-1] = 0; } if (s->precision <= 8) { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; line = picture->data[plane] + y / s->cdy[compno] * picture->linesize[plane]; for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint8_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = line + x / s->cdx[compno] * pixelsize + compno*!planar; if (codsty->transform == FF_DWT97) { for (; x < w; x += s->cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s->cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); *dst = val << (8 - cbps); i_datap++; dst += pixelsize; } } line += picture->linesize[plane]; } } } else { for (compno = 0; compno < s->ncomponents; compno++) { Jpeg2000Component *comp = tile->comp + compno; Jpeg2000CodingStyle *codsty = tile->codsty + compno; float *datap = comp->f_data; int32_t *i_datap = comp->i_data; uint16_t *linel; int cbps = s->cbps[compno]; int w = tile->comp[compno].coord[0][1] - s->image_offset_x; int planar = !!picture->data[2]; int pixelsize = planar ? 1 : s->ncomponents; int plane = 0; if (planar) plane = s->cdef[compno] ? s->cdef[compno]-1 : (s->ncomponents-1); y = tile->comp[compno].coord[1][0] - s->image_offset_y; linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (picture->linesize[plane] >> 1); for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) { uint16_t *dst; x = tile->comp[compno].coord[0][0] - s->image_offset_x; dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar); if (codsty->transform == FF_DWT97) { for (; x < w; x += s-> cdx[compno]) { int val = lrintf(*datap) + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); datap++; dst += pixelsize; } } else { for (; x < w; x += s-> cdx[compno]) { int val = *i_datap + (1 << (cbps - 1)); /* DC level shift and clip see ISO 15444-1:2002 G.1.2 */ val = av_clip(val, 0, (1 << cbps) - 1); /* align 12 bit values in little-endian mode */ *dst = val << (16 - cbps); i_datap++; dst += pixelsize; } } linel += picture->linesize[plane] >> 1; } } } return 0; }
165,913
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunLoop::BeforeRun() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); #if DCHECK_IS_ON() DCHECK(!run_called_); run_called_ = true; #endif // DCHECK_IS_ON() if (quit_called_) return false; auto& active_run_loops_ = delegate_->active_run_loops_; active_run_loops_.push(this); const bool is_nested = active_run_loops_.size() > 1; if (is_nested) { CHECK(delegate_->allow_nesting_); for (auto& observer : delegate_->nesting_observers_) observer.OnBeginNestedRunLoop(); } running_ = true; return true; } Commit Message: Introduce RunLoop::Type::NESTABLE_TASKS_ALLOWED to replace MessageLoop::ScopedNestableTaskAllower. (as well as MessageLoop::SetNestableTasksAllowed()) Surveying usage: the scoped object is always instantiated right before RunLoop().Run(). The intent is really to allow nestable tasks in that RunLoop so it's better to explicitly label that RunLoop as such and it allows us to break the last dependency that forced some RunLoop users to use MessageLoop APIs. There's also the odd case of allowing nestable tasks for loops that are reentrant from a native task (without going through RunLoop), these are the minority but will have to be handled (after cleaning up the majority of cases that are RunLoop induced). As highlighted by robliao@ in https://chromium-review.googlesource.com/c/600517 (which was merged in this CL). [email protected] Bug: 750779 Change-Id: I43d122c93ec903cff3a6fe7b77ec461ea0656448 Reviewed-on: https://chromium-review.googlesource.com/594713 Commit-Queue: Gabriel Charette <[email protected]> Reviewed-by: Robert Liao <[email protected]> Reviewed-by: danakj <[email protected]> Cr-Commit-Position: refs/heads/master@{#492263} CWE ID:
bool RunLoop::BeforeRun() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); #if DCHECK_IS_ON() DCHECK(!run_called_); run_called_ = true; #endif // DCHECK_IS_ON() if (quit_called_) return false; auto& active_run_loops_ = delegate_->active_run_loops_; active_run_loops_.push(this); const bool is_nested = active_run_loops_.size() > 1; if (is_nested) { CHECK(delegate_->allow_nesting_); for (auto& observer : delegate_->nesting_observers_) observer.OnBeginNestedRunLoop(); if (type_ == Type::kNestableTasksAllowed) delegate_->EnsureWorkScheduled(); } running_ = true; return true; }
171,868
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel, int gpu_host_id) { surface_route_id_ = params_in_pixel.route_id; if (params_in_pixel.protection_state_id && params_in_pixel.protection_state_id != protection_state_id_) { DCHECK(!current_surface_); InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } if (ShouldFastACK(params_in_pixel.surface_handle)) { InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, false, NULL); return; } current_surface_ = params_in_pixel.surface_handle; released_front_lock_ = NULL; DCHECK(current_surface_); UpdateExternalTexture(); ui::Compositor* compositor = GetCompositor(); if (!compositor) { InsertSyncPointAndACK(params_in_pixel.route_id, gpu_host_id, true, NULL); } else { DCHECK(image_transport_clients_.find(params_in_pixel.surface_handle) != image_transport_clients_.end()); gfx::Size surface_size_in_pixel = image_transport_clients_[params_in_pixel.surface_handle]->size(); gfx::Rect rect_to_paint = ConvertRectToDIP(this, gfx::Rect( params_in_pixel.x, surface_size_in_pixel.height() - params_in_pixel.y - params_in_pixel.height, params_in_pixel.width, params_in_pixel.height)); rect_to_paint.Inset(-1, -1); rect_to_paint.Intersect(window_->bounds()); window_->SchedulePaintInRect(rect_to_paint); can_lock_compositor_ = NO_PENDING_COMMIT; on_compositing_did_commit_callbacks_.push_back( base::Bind(&RenderWidgetHostViewAura::InsertSyncPointAndACK, params_in_pixel.route_id, gpu_host_id, true)); if (!compositor->HasObserver(this)) compositor->AddObserver(this); } } Commit Message: Implement TextureImageTransportSurface using texture mailbox This has a couple of advantages: - allow tearing down and recreating the UI parent context without losing the renderer contexts - do not require a context to be able to generate textures when creating the GLSurfaceHandle - clearer ownership semantics that potentially allows for more robust and easier lost context handling/thumbnailing/etc., since a texture is at any given time owned by either: UI parent, mailbox, or TextureImageTransportSurface - simplify frontbuffer protection logic; the frontbuffer textures are now owned by RWHV where they are refcounted The TextureImageTransportSurface informs RenderWidgetHostView of the mailbox names for the front- and backbuffer textures by associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message. During SwapBuffers() or PostSubBuffer() cycles, it then uses produceTextureCHROMIUM() and consumeTextureCHROMIUM() to transfer ownership between renderer and browser compositor. RWHV sends back the surface_handle of the buffer being returned with the Swap ACK (or 0 if no buffer is being returned in which case TextureImageTransportSurface will allocate a new texture - note that this could be used to simply keep textures for thumbnailing). BUG=154815,139616 [email protected] Review URL: https://chromiumcodereview.appspot.com/11194042 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID:
void RenderWidgetHostViewAura::AcceleratedSurfacePostSubBuffer( const GpuHostMsg_AcceleratedSurfacePostSubBuffer_Params& params_in_pixel, int gpu_host_id) { const gfx::Rect surface_rect = gfx::Rect(gfx::Point(), params_in_pixel.surface_size); gfx::Rect damage_rect(params_in_pixel.x, params_in_pixel.y, params_in_pixel.width, params_in_pixel.height); BufferPresentedParams ack_params( params_in_pixel.route_id, gpu_host_id, params_in_pixel.surface_handle); if (!SwapBuffersPrepare(surface_rect, damage_rect, &ack_params)) return; SkRegion damage(RectToSkIRect(damage_rect)); if (!skipped_damage_.isEmpty()) { damage.op(skipped_damage_, SkRegion::kUnion_Op); skipped_damage_.setEmpty(); } DCHECK(surface_rect.Contains(SkIRectToRect(damage.getBounds()))); ui::Texture* current_texture = image_transport_clients_[current_surface_]; const gfx::Size surface_size_in_pixel = params_in_pixel.surface_size; DLOG_IF(ERROR, ack_params.texture_to_produce && ack_params.texture_to_produce->size() != current_texture->size() && SkIRectToRect(damage.getBounds()) != surface_rect) << "Expected full damage rect after size change"; if (ack_params.texture_to_produce && !previous_damage_.isEmpty() && ack_params.texture_to_produce->size() == current_texture->size()) { ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); GLHelper* gl_helper = factory->GetGLHelper(); gl_helper->CopySubBufferDamage( current_texture->PrepareTexture(), ack_params.texture_to_produce->PrepareTexture(), damage, previous_damage_); } previous_damage_ = damage; ui::Compositor* compositor = GetCompositor(); if (compositor) { gfx::Rect rect_to_paint = ConvertRectToDIP(this, gfx::Rect( params_in_pixel.x, surface_size_in_pixel.height() - params_in_pixel.y - params_in_pixel.height, params_in_pixel.width, params_in_pixel.height)); rect_to_paint.Inset(-1, -1); rect_to_paint.Intersect(window_->bounds()); window_->SchedulePaintInRect(rect_to_paint); } SwapBuffersCompleted(ack_params); }
171,374
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 jas_matrix_divpow2(jas_matrix_t *matrix, int n) { int i; int j; jas_seqent_t *rowstart; int rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { *data = (*data >= 0) ? ((*data) >> n) : (-((-(*data)) >> n)); } } } } Commit Message: The generation of the configuration file jas_config.h has been completely reworked in order to avoid pollution of the global namespace. Some problematic types like uchar, ulong, and friends have been replaced with names with a jas_ prefix. An option max_samples has been added to the BMP and JPEG decoders to restrict the maximum size of image that they can decode. This change was made as a (possibly temporary) fix to address security concerns. A max_samples command-line option has also been added to imginfo. Whether an image component (for jas_image_t) is stored in memory or on disk is now based on the component size (rather than the image size). Some debug log message were added. Some new integer overflow checks were added. Some new safe integer add/multiply functions were added. More pre-C99 cruft was removed. JasPer has numerous "hacks" to handle pre-C99 compilers. JasPer now assumes C99 support. So, this pre-C99 cruft is unnecessary and can be removed. The regression jasper-doublefree-mem_close.jpg has been re-enabled. Theoretically, it should work more predictably now. CWE ID: CWE-190
void jas_matrix_divpow2(jas_matrix_t *matrix, int n) { jas_matind_t i; jas_matind_t j; jas_seqent_t *rowstart; jas_matind_t rowstep; jas_seqent_t *data; if (jas_matrix_numrows(matrix) > 0 && jas_matrix_numcols(matrix) > 0) { assert(matrix->rows_); rowstep = jas_matrix_rowstep(matrix); for (i = matrix->numrows_, rowstart = matrix->rows_[0]; i > 0; --i, rowstart += rowstep) { for (j = matrix->numcols_, data = rowstart; j > 0; --j, ++data) { *data = (*data >= 0) ? ((*data) >> n) : (-((-(*data)) >> n)); } } } }
168,704
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (is_guest_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_nested; else if (vcpu->arch.apic_base & X2APIC_ENABLE) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); } Commit Message: kvm:vmx: more complete state update on APICv on/off The function to update APICv on/off state (in particular, to deactivate it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust APICv-related fields among secondary processor-based VM-execution controls. As a result, Windows 2012 guests get stuck when SynIC-based auto-EOI interrupt intersected with e.g. an IPI in the guest. In addition, the MSR intercept bitmap isn't updated every time "virtualize x2APIC mode" is toggled. This path can only be triggered by a malicious guest, because Windows didn't use x2APIC but rather their own synthetic APIC access MSRs; however a guest running in a SynIC-enabled VM could switch to x2APIC and thus obtain direct access to host APIC MSRs (CVE-2016-4440). The patch fixes those omissions. Signed-off-by: Roman Kagan <[email protected]> Reported-by: Steve Rutherford <[email protected]> Reported-by: Yang Zhang <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-264
static void vmx_set_msr_bitmap(struct kvm_vcpu *vcpu) { unsigned long *msr_bitmap; if (is_guest_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_nested; else if (cpu_has_secondary_exec_ctrls() && (vmcs_read32(SECONDARY_VM_EXEC_CONTROL) & SECONDARY_EXEC_VIRTUALIZE_X2APIC_MODE)) { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode_x2apic; else msr_bitmap = vmx_msr_bitmap_legacy_x2apic; } else { if (is_long_mode(vcpu)) msr_bitmap = vmx_msr_bitmap_longmode; else msr_bitmap = vmx_msr_bitmap_legacy; } vmcs_write64(MSR_BITMAP, __pa(msr_bitmap)); }
167,264
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ImageInputType::ensurePrimaryContent() { if (!m_useFallbackContent) return; m_useFallbackContent = false; reattachFallbackContent(); } Commit Message: ImageInputType::ensurePrimaryContent should recreate UA shadow tree. Once the fallback shadow tree was created, it was never recreated even if ensurePrimaryContent was called. Such situation happens by updating |src| attribute. BUG=589838 Review URL: https://codereview.chromium.org/1732753004 Cr-Commit-Position: refs/heads/master@{#377804} CWE ID: CWE-361
void ImageInputType::ensurePrimaryContent() { if (!m_useFallbackContent) return; m_useFallbackContent = false; if (ShadowRoot* root = element().userAgentShadowRoot()) root->removeChildren(); createShadowSubtree(); reattachFallbackContent(); }
172,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: DOMFileSystemSync* WorkerGlobalScopeFileSystem::webkitRequestFileSystemSync(WorkerGlobalScope& worker, int type, long long size, ExceptionState& exceptionState) { ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem()) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } FileSystemType fileSystemType = static_cast<FileSystemType>(type); if (!DOMFileSystemBase::isValidType(fileSystemType)) { exceptionState.throwDOMException(InvalidModificationError, "the type must be TEMPORARY or PERSISTENT."); return 0; } RefPtr<FileSystemSyncCallbackHelper> helper = FileSystemSyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = FileSystemCallbacks::create(helper->successCallback(), helper->errorCallback(), &worker, fileSystemType); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->requestFileSystem(&worker, fileSystemType, size, callbacks.release()); return helper->getResult(exceptionState); } Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/ These are leftovers when we shipped Oilpan for filesystem/ once. BUG=340522 Review URL: https://codereview.chromium.org/501263003 git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-119
DOMFileSystemSync* WorkerGlobalScopeFileSystem::webkitRequestFileSystemSync(WorkerGlobalScope& worker, int type, long long size, ExceptionState& exceptionState) { ExecutionContext* secureContext = worker.executionContext(); if (!secureContext->securityOrigin()->canAccessFileSystem()) { exceptionState.throwSecurityError(FileError::securityErrorMessage); return 0; } FileSystemType fileSystemType = static_cast<FileSystemType>(type); if (!DOMFileSystemBase::isValidType(fileSystemType)) { exceptionState.throwDOMException(InvalidModificationError, "the type must be TEMPORARY or PERSISTENT."); return 0; } FileSystemSyncCallbackHelper* helper = FileSystemSyncCallbackHelper::create(); OwnPtr<AsyncFileSystemCallbacks> callbacks = FileSystemCallbacks::create(helper->successCallback(), helper->errorCallback(), &worker, fileSystemType); callbacks->setShouldBlockUntilCompletion(true); LocalFileSystem::from(worker)->requestFileSystem(&worker, fileSystemType, size, callbacks.release()); return helper->getResult(exceptionState); }
171,432
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: cib_notify_client(gpointer key, gpointer value, gpointer user_data) { const char *type = NULL; gboolean do_send = FALSE; cib_client_t *client = value; xmlNode *update_msg = user_data; CRM_CHECK(client != NULL, return TRUE); CRM_CHECK(update_msg != NULL, return TRUE); if (client->ipc == NULL) { crm_warn("Skipping client with NULL channel"); return FALSE; } type = crm_element_value(update_msg, F_SUBTYPE); CRM_LOG_ASSERT(type != NULL); if (client->diffs && safe_str_eq(type, T_CIB_DIFF_NOTIFY)) { do_send = TRUE; } else if (client->replace && safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) { do_send = TRUE; } else if (client->confirmations && safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) { do_send = TRUE; } else if (client->pre_notify && safe_str_eq(type, T_CIB_PRE_NOTIFY)) { do_send = TRUE; } else if (client->post_notify && safe_str_eq(type, T_CIB_POST_NOTIFY)) { do_send = TRUE; } if (do_send) { if (client->ipc) { if(crm_ipcs_send(client->ipc, 0, update_msg, TRUE) == FALSE) { crm_warn("Notification of client %s/%s failed", client->name, client->id); } #ifdef HAVE_GNUTLS_GNUTLS_H } else if (client->session) { crm_debug("Sent %s notification to client %s/%s", type, client->name, client->id); crm_send_remote_msg(client->session, update_msg, client->encrypted); #endif } else { crm_err("Unknown transport for %s", client->name); } } return FALSE; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_notify_client(gpointer key, gpointer value, gpointer user_data) { const char *type = NULL; gboolean do_send = FALSE; cib_client_t *client = value; xmlNode *update_msg = user_data; CRM_CHECK(client != NULL, return TRUE); CRM_CHECK(update_msg != NULL, return TRUE); if (client->ipc == NULL && client->session == NULL) { crm_warn("Skipping client with NULL channel"); return FALSE; } type = crm_element_value(update_msg, F_SUBTYPE); CRM_LOG_ASSERT(type != NULL); if (client->diffs && safe_str_eq(type, T_CIB_DIFF_NOTIFY)) { do_send = TRUE; } else if (client->replace && safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) { do_send = TRUE; } else if (client->confirmations && safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) { do_send = TRUE; } else if (client->pre_notify && safe_str_eq(type, T_CIB_PRE_NOTIFY)) { do_send = TRUE; } else if (client->post_notify && safe_str_eq(type, T_CIB_POST_NOTIFY)) { do_send = TRUE; } if (do_send) { if (client->ipc) { if(crm_ipcs_send(client->ipc, 0, update_msg, TRUE) == FALSE) { crm_warn("Notification of client %s/%s failed", client->name, client->id); } #ifdef HAVE_GNUTLS_GNUTLS_H } else if (client->session) { crm_debug("Sent %s notification to client %s/%s", type, client->name, client->id); crm_send_remote_msg(client->session, update_msg, client->encrypted); #endif } else { crm_err("Unknown transport for %s", client->name); } } return FALSE; }
166,146
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion web_gl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), web_gl_version_(web_gl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); } Commit Message: Reset ES3 pixel pack parameters and PIXEL_PACK_BUFFER binding in DrawingBuffer before ReadPixels() and recover them later. BUG=740603 TEST=new conformance test [email protected],[email protected] Change-Id: I3ea54c6cc34f34e249f7c8b9f792d93c5e1958f4 Reviewed-on: https://chromium-review.googlesource.com/570840 Reviewed-by: Antoine Labour <[email protected]> Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#486518} CWE ID: CWE-119
DrawingBuffer::DrawingBuffer( std::unique_ptr<WebGraphicsContext3DProvider> context_provider, std::unique_ptr<Extensions3DUtil> extensions_util, Client* client, bool discard_framebuffer_supported, bool want_alpha_channel, bool premultiplied_alpha, PreserveDrawingBuffer preserve, WebGLVersion webgl_version, bool want_depth, bool want_stencil, ChromiumImageUsage chromium_image_usage, const CanvasColorParams& color_params) : client_(client), preserve_drawing_buffer_(preserve), webgl_version_(webgl_version), context_provider_(WTF::WrapUnique(new WebGraphicsContext3DProviderWrapper( std::move(context_provider)))), gl_(this->ContextProvider()->ContextGL()), extensions_util_(std::move(extensions_util)), discard_framebuffer_supported_(discard_framebuffer_supported), want_alpha_channel_(want_alpha_channel), premultiplied_alpha_(premultiplied_alpha), software_rendering_(this->ContextProvider()->IsSoftwareRendering()), want_depth_(want_depth), want_stencil_(want_stencil), color_space_(color_params.GetGfxColorSpace()), chromium_image_usage_(chromium_image_usage) { TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation", TRACE_EVENT_SCOPE_GLOBAL); }
172,291
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: archive_read_format_zip_cleanup(struct archive_read *a) { struct zip *zip; struct zip_entry *zip_entry, *next_zip_entry; zip = (struct zip *)(a->format->data); #ifdef HAVE_ZLIB_H if (zip->stream_valid) inflateEnd(&zip->stream); #endif #if HAVA_LZMA_H && HAVE_LIBLZMA if (zip->zipx_lzma_valid) { lzma_end(&zip->zipx_lzma_stream); } #endif #ifdef HAVE_BZLIB_H if (zip->bzstream_valid) { BZ2_bzDecompressEnd(&zip->bzstream); } #endif free(zip->uncompressed_buffer); if (zip->ppmd8_valid) __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8); if (zip->zip_entries) { zip_entry = zip->zip_entries; while (zip_entry != NULL) { next_zip_entry = zip_entry->next; archive_string_free(&zip_entry->rsrcname); free(zip_entry); zip_entry = next_zip_entry; } } free(zip->decrypted_buffer); if (zip->cctx_valid) archive_decrypto_aes_ctr_release(&zip->cctx); if (zip->hctx_valid) archive_hmac_sha1_cleanup(&zip->hctx); free(zip->iv); free(zip->erd); free(zip->v_data); archive_string_free(&zip->format_name); free(zip); (a->format->data) = NULL; return (ARCHIVE_OK); } Commit Message: Fix typo in preprocessor macro in archive_read_format_zip_cleanup() Frees lzma_stream on cleanup() Fixes #1165 CWE ID: CWE-399
archive_read_format_zip_cleanup(struct archive_read *a) { struct zip *zip; struct zip_entry *zip_entry, *next_zip_entry; zip = (struct zip *)(a->format->data); #ifdef HAVE_ZLIB_H if (zip->stream_valid) inflateEnd(&zip->stream); #endif #if HAVE_LZMA_H && HAVE_LIBLZMA if (zip->zipx_lzma_valid) { lzma_end(&zip->zipx_lzma_stream); } #endif #ifdef HAVE_BZLIB_H if (zip->bzstream_valid) { BZ2_bzDecompressEnd(&zip->bzstream); } #endif free(zip->uncompressed_buffer); if (zip->ppmd8_valid) __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8); if (zip->zip_entries) { zip_entry = zip->zip_entries; while (zip_entry != NULL) { next_zip_entry = zip_entry->next; archive_string_free(&zip_entry->rsrcname); free(zip_entry); zip_entry = next_zip_entry; } } free(zip->decrypted_buffer); if (zip->cctx_valid) archive_decrypto_aes_ctr_release(&zip->cctx); if (zip->hctx_valid) archive_hmac_sha1_cleanup(&zip->hctx); free(zip->iv); free(zip->erd); free(zip->v_data); archive_string_free(&zip->format_name); free(zip); (a->format->data) = NULL; return (ARCHIVE_OK); }
169,695
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf, UINT16 len, BOOLEAN ext, BOOLEAN forward) { UNUSED(ext); UNUSED(forward); if (tap_fd != INVALID_FD) { tETH_HDR eth_hdr; memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN); memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN); eth_hdr.h_proto = htons(proto); char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)]; memcpy(packet, &eth_hdr, sizeof(tETH_HDR)); if (len > TAP_MAX_PKT_WRITE_LEN) { LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len); return -1; } memcpy(packet + sizeof(tETH_HDR), buf, len); /* Send data to network interface */ int ret = write(tap_fd, packet, len + sizeof(tETH_HDR)); BTIF_TRACE_DEBUG("ret:%d", ret); return ret; } return -1; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
int btpan_tap_send(int tap_fd, const BD_ADDR src, const BD_ADDR dst, UINT16 proto, const char* buf, UINT16 len, BOOLEAN ext, BOOLEAN forward) { UNUSED(ext); UNUSED(forward); if (tap_fd != INVALID_FD) { tETH_HDR eth_hdr; memcpy(&eth_hdr.h_dest, dst, ETH_ADDR_LEN); memcpy(&eth_hdr.h_src, src, ETH_ADDR_LEN); eth_hdr.h_proto = htons(proto); char packet[TAP_MAX_PKT_WRITE_LEN + sizeof(tETH_HDR)]; memcpy(packet, &eth_hdr, sizeof(tETH_HDR)); if (len > TAP_MAX_PKT_WRITE_LEN) { LOG_ERROR("btpan_tap_send eth packet size:%d is exceeded limit!", len); return -1; } memcpy(packet + sizeof(tETH_HDR), buf, len); /* Send data to network interface */ int ret = TEMP_FAILURE_RETRY(write(tap_fd, packet, len + sizeof(tETH_HDR))); BTIF_TRACE_DEBUG("ret:%d", ret); return ret; } return -1; }
173,446
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long Chapters::Atom::Parse( IMkvReader* pReader, long long pos, long long size) { const long long stop = pos + size; while (pos < stop) { long long id, size; long status = ParseElementHeader( pReader, pos, stop, id, size); if (status < 0) // error return status; if (size == 0) // weird continue; if (id == 0x00) // Display ID { status = ParseDisplay(pReader, pos, size); if (status < 0) // error return status; } else if (id == 0x1654) // StringUID ID { status = UnserializeString(pReader, pos, size, m_string_uid); if (status < 0) // error return status; } else if (id == 0x33C4) // UID ID { long long val; status = UnserializeInt(pReader, pos, size, val); if (status < 0) // error return status; m_uid = val; } else if (id == 0x11) // TimeStart ID { const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_start_timecode = val; } else if (id == 0x12) // TimeEnd ID { const long long val = UnserializeUInt(pReader, pos, size); if (val < 0) // error return static_cast<long>(val); m_stop_timecode = val; } pos += size; assert(pos <= stop); } assert(pos == stop); return 0; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
long Chapters::Atom::Parse(
174,402
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: spnego_gss_accept_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret, tmpmin, negState; send_token_flag return_token; gss_buffer_t mechtok_in, mic_in, mic_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_ctx_id_t sc = NULL; spnego_gss_cred_id_t spcred = NULL; int sendTokenInit = 0, tmpret; mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated mech's gss_accept_sec_context function * and examine the results. * 3. Process or generate MICs if necessary. * * Step one determines whether the negotiation requires a MIC exchange, * while steps two and three share responsibility for determining when * the exchange is complete. If the selected mech completes in this * call and no MIC exchange is expected, then step 2 will decide. If a * MIC exchange is expected, then step 3 will decide. If an error * occurs in any step, the exchange will be aborted, possibly with an * error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * return_token is used to indicate what type of token, if any, should * be generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (input_token == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ; /* Step 1: Perform mechanism negotiation. */ sc = (spnego_gss_ctx_id_t)*context_handle; spcred = (spnego_gss_cred_id_t)verifier_cred_handle; if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) { /* Process an initial token or request for NegHints. */ if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (time_rec != NULL) *time_rec = 0; if (ret_flags != NULL) *ret_flags = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (input_token->length == 0) { ret = acc_ctx_hints(minor_status, context_handle, spcred, &mic_out, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; sendTokenInit = 1; ret = GSS_S_CONTINUE_NEEDED; } else { /* Can set negState to REQUEST_MIC */ ret = acc_ctx_new(minor_status, input_token, context_handle, spcred, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } } else { /* Process a response token. Can set negState to * ACCEPT_INCOMPLETE. */ ret = acc_ctx_cont(minor_status, input_token, context_handle, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } /* Step 2: invoke the negotiated mechanism's gss_accept_sec_context * function. */ sc = (spnego_gss_ctx_id_t)*context_handle; /* * Handle mechtok_in and mic_in only if they are * present in input_token. If neither is present, whether * this is an error depends on whether this is the first * round-trip. RET is set to a default value according to * whether it is the first round-trip. */ if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) { ret = acc_ctx_call_acc(minor_status, sc, spcred, mechtok_in, mech_type, &mechtok_out, ret_flags, time_rec, delegated_cred_handle, &negState, &return_token); } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && sc->mech_complete && (sc->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mic_in, (mechtok_out.length != 0), sc, &mic_out, &negState, &return_token); } cleanup: if (return_token == INIT_TOKEN_SEND && sendTokenInit) { assert(sc != NULL); tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0, GSS_C_NO_BUFFER, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } else if (return_token != NO_TOKEN_SEND && return_token != CHECK_MIC) { tmpret = make_spnego_tokenTarg_msg(negState, sc ? sc->internal_mech : GSS_C_NO_OID, &mechtok_out, mic_out, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } if (ret == GSS_S_COMPLETE) { *context_handle = (gss_ctx_id_t)sc->ctx_handle; if (sc->internal_name != GSS_C_NO_NAME && src_name != NULL) { *src_name = sc->internal_name; sc->internal_name = GSS_C_NO_NAME; } release_spnego_ctx(&sc); } else if (ret != GSS_S_CONTINUE_NEEDED) { if (sc != NULL) { gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&sc); } *context_handle = GSS_C_NO_CONTEXT; } gss_release_buffer(&tmpmin, &mechtok_out); if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mic_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_in); free(mic_in); } if (mic_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_out); free(mic_out); } 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_accept_sec_context( OM_uint32 *minor_status, gss_ctx_id_t *context_handle, gss_cred_id_t verifier_cred_handle, gss_buffer_t input_token, gss_channel_bindings_t input_chan_bindings, gss_name_t *src_name, gss_OID *mech_type, gss_buffer_t output_token, OM_uint32 *ret_flags, OM_uint32 *time_rec, gss_cred_id_t *delegated_cred_handle) { OM_uint32 ret, tmpmin, negState; send_token_flag return_token; gss_buffer_t mechtok_in, mic_in, mic_out; gss_buffer_desc mechtok_out = GSS_C_EMPTY_BUFFER; spnego_gss_ctx_id_t sc = NULL; spnego_gss_cred_id_t spcred = NULL; int sendTokenInit = 0, tmpret; mechtok_in = mic_in = mic_out = GSS_C_NO_BUFFER; /* * This function works in three steps: * * 1. Perform mechanism negotiation. * 2. Invoke the negotiated mech's gss_accept_sec_context function * and examine the results. * 3. Process or generate MICs if necessary. * * Step one determines whether the negotiation requires a MIC exchange, * while steps two and three share responsibility for determining when * the exchange is complete. If the selected mech completes in this * call and no MIC exchange is expected, then step 2 will decide. If a * MIC exchange is expected, then step 3 will decide. If an error * occurs in any step, the exchange will be aborted, possibly with an * error token. * * negState determines the state of the negotiation, and is * communicated to the acceptor if a continuing token is sent. * return_token is used to indicate what type of token, if any, should * be generated. */ /* Validate arguments. */ if (minor_status != NULL) *minor_status = 0; if (output_token != GSS_C_NO_BUFFER) { output_token->length = 0; output_token->value = NULL; } if (minor_status == NULL || output_token == GSS_C_NO_BUFFER || context_handle == NULL) return GSS_S_CALL_INACCESSIBLE_WRITE; if (input_token == GSS_C_NO_BUFFER) return GSS_S_CALL_INACCESSIBLE_READ; /* Step 1: Perform mechanism negotiation. */ sc = (spnego_gss_ctx_id_t)*context_handle; spcred = (spnego_gss_cred_id_t)verifier_cred_handle; if (sc == NULL || sc->internal_mech == GSS_C_NO_OID) { /* Process an initial token or request for NegHints. */ if (src_name != NULL) *src_name = GSS_C_NO_NAME; if (mech_type != NULL) *mech_type = GSS_C_NO_OID; if (time_rec != NULL) *time_rec = 0; if (ret_flags != NULL) *ret_flags = 0; if (delegated_cred_handle != NULL) *delegated_cred_handle = GSS_C_NO_CREDENTIAL; if (input_token->length == 0) { ret = acc_ctx_hints(minor_status, context_handle, spcred, &mic_out, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; sendTokenInit = 1; ret = GSS_S_CONTINUE_NEEDED; } else { /* Can set negState to REQUEST_MIC */ ret = acc_ctx_new(minor_status, input_token, context_handle, spcred, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } } else { /* Process a response token. Can set negState to * ACCEPT_INCOMPLETE. */ ret = acc_ctx_cont(minor_status, input_token, context_handle, &mechtok_in, &mic_in, &negState, &return_token); if (ret != GSS_S_COMPLETE) goto cleanup; ret = GSS_S_CONTINUE_NEEDED; } /* Step 2: invoke the negotiated mechanism's gss_accept_sec_context * function. */ sc = (spnego_gss_ctx_id_t)*context_handle; /* * Handle mechtok_in and mic_in only if they are * present in input_token. If neither is present, whether * this is an error depends on whether this is the first * round-trip. RET is set to a default value according to * whether it is the first round-trip. */ if (negState != REQUEST_MIC && mechtok_in != GSS_C_NO_BUFFER) { ret = acc_ctx_call_acc(minor_status, sc, spcred, mechtok_in, mech_type, &mechtok_out, ret_flags, time_rec, delegated_cred_handle, &negState, &return_token); } /* Step 3: process or generate the MIC, if the negotiated mech is * complete and supports MICs. */ if (!HARD_ERROR(ret) && sc->mech_complete && (sc->ctx_flags & GSS_C_INTEG_FLAG)) { ret = handle_mic(minor_status, mic_in, (mechtok_out.length != 0), sc, &mic_out, &negState, &return_token); } cleanup: if (return_token == INIT_TOKEN_SEND && sendTokenInit) { assert(sc != NULL); tmpret = make_spnego_tokenInit_msg(sc, 1, mic_out, 0, GSS_C_NO_BUFFER, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } else if (return_token != NO_TOKEN_SEND && return_token != CHECK_MIC) { tmpret = make_spnego_tokenTarg_msg(negState, sc ? sc->internal_mech : GSS_C_NO_OID, &mechtok_out, mic_out, return_token, output_token); if (tmpret < 0) ret = GSS_S_FAILURE; } if (ret == GSS_S_COMPLETE) { sc->opened = 1; if (sc->internal_name != GSS_C_NO_NAME && src_name != NULL) { *src_name = sc->internal_name; sc->internal_name = GSS_C_NO_NAME; } } else if (ret != GSS_S_CONTINUE_NEEDED) { if (sc != NULL) { gss_delete_sec_context(&tmpmin, &sc->ctx_handle, GSS_C_NO_BUFFER); release_spnego_ctx(&sc); } *context_handle = GSS_C_NO_CONTEXT; } gss_release_buffer(&tmpmin, &mechtok_out); if (mechtok_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mechtok_in); free(mechtok_in); } if (mic_in != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_in); free(mic_in); } if (mic_out != GSS_C_NO_BUFFER) { gss_release_buffer(&tmpmin, mic_out); free(mic_out); } return ret; }
166,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection) { Position start = startOfSelection.deepEquivalent().downstream(); if (isAtUnsplittableElement(start)) { RefPtr<Element> blockquote = createBlockElement(); insertNodeAt(blockquote, start); RefPtr<Element> placeholder = createBreakElement(document()); appendNode(placeholder, blockquote); setEndingSelection(VisibleSelection(positionBeforeNode(placeholder.get()), DOWNSTREAM, endingSelection().isDirectional())); return; } RefPtr<Element> blockquoteForNextIndent; VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection); VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next()); m_endOfLastParagraph = endOfParagraph(endOfSelection).deepEquivalent(); bool atEnd = false; Position end; while (endOfCurrentParagraph != endAfterSelection && !atEnd) { if (endOfCurrentParagraph.deepEquivalent() == m_endOfLastParagraph) atEnd = true; rangeForParagraphSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); endOfCurrentParagraph = end; Position afterEnd = end.next(); Node* enclosingCell = enclosingNodeOfType(start, &isTableCell); VisiblePosition endOfNextParagraph = endOfNextParagrahSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); formatRange(start, end, m_endOfLastParagraph, blockquoteForNextIndent); if (enclosingCell && enclosingCell != enclosingNodeOfType(endOfNextParagraph.deepEquivalent(), &isTableCell)) blockquoteForNextIndent = 0; if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument()) break; if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) { ASSERT_NOT_REACHED(); return; } endOfCurrentParagraph = endOfNextParagraph; } } Commit Message: Remove false assertion in ApplyBlockElementCommand::formatSelection() Note: This patch is preparation of fixing issue 294456. This patch removes false assertion in ApplyBlockElementCommand::formatSelection(), when contents of being indent is modified, e.g. mutation event, |endOfNextParagraph| can hold removed contents. BUG=294456 TEST=n/a [email protected] Review URL: https://codereview.chromium.org/25657004 git-svn-id: svn://svn.chromium.org/blink/trunk@158701 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection) { Position start = startOfSelection.deepEquivalent().downstream(); if (isAtUnsplittableElement(start)) { RefPtr<Element> blockquote = createBlockElement(); insertNodeAt(blockquote, start); RefPtr<Element> placeholder = createBreakElement(document()); appendNode(placeholder, blockquote); setEndingSelection(VisibleSelection(positionBeforeNode(placeholder.get()), DOWNSTREAM, endingSelection().isDirectional())); return; } RefPtr<Element> blockquoteForNextIndent; VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection); VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next()); m_endOfLastParagraph = endOfParagraph(endOfSelection).deepEquivalent(); bool atEnd = false; Position end; while (endOfCurrentParagraph != endAfterSelection && !atEnd) { if (endOfCurrentParagraph.deepEquivalent() == m_endOfLastParagraph) atEnd = true; rangeForParagraphSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); endOfCurrentParagraph = end; Position afterEnd = end.next(); Node* enclosingCell = enclosingNodeOfType(start, &isTableCell); VisiblePosition endOfNextParagraph = endOfNextParagrahSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end); formatRange(start, end, m_endOfLastParagraph, blockquoteForNextIndent); if (enclosingCell && enclosingCell != enclosingNodeOfType(endOfNextParagraph.deepEquivalent(), &isTableCell)) blockquoteForNextIndent = 0; if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument()) break; // If somehow, e.g. mutation event handler, we did, return to prevent crashes. if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) return; endOfCurrentParagraph = endOfNextParagraph; } }
171,170
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 kvm_set_guest_paused(struct kvm_vcpu *vcpu) { if (!vcpu->arch.time_page) return -EINVAL; vcpu->arch.pvclock_set_guest_stopped_request = true; kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); return 0; } Commit Message: KVM: x86: Convert MSR_KVM_SYSTEM_TIME to use gfn_to_hva_cache functions (CVE-2013-1797) There is a potential use after free issue with the handling of MSR_KVM_SYSTEM_TIME. If the guest specifies a GPA in a movable or removable memory such as frame buffers then KVM might continue to write to that address even after it's removed via KVM_SET_USER_MEMORY_REGION. KVM pins the page in memory so it's unlikely to cause an issue, but if the user space component re-purposes the memory previously used for the guest, then the guest will be able to corrupt that memory. Tested: Tested against kvmclock unit test Signed-off-by: Andrew Honig <[email protected]> Signed-off-by: Marcelo Tosatti <[email protected]> CWE ID: CWE-399
static int kvm_set_guest_paused(struct kvm_vcpu *vcpu) { if (!vcpu->arch.pv_time_enabled) return -EINVAL; vcpu->arch.pvclock_set_guest_stopped_request = true; kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); return 0; }
166,117
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: jiffies_to_timespec(const unsigned long jiffies, struct timespec *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u64 nsec = (u64)jiffies * TICK_NSEC; value->tv_sec = div_long_long_rem(nsec, NSEC_PER_SEC, &value->tv_nsec); } Commit Message: remove div_long_long_rem x86 is the only arch right now, which provides an optimized for div_long_long_rem and it has the downside that one has to be very careful that the divide doesn't overflow. The API is a little akward, as the arguments for the unsigned divide are signed. The signed version also doesn't handle a negative divisor and produces worse code on 64bit archs. There is little incentive to keep this API alive, so this converts the few users to the new API. Signed-off-by: Roman Zippel <[email protected]> Cc: Ralf Baechle <[email protected]> Cc: Ingo Molnar <[email protected]> Cc: Thomas Gleixner <[email protected]> Cc: john stultz <[email protected]> Cc: Christoph Lameter <[email protected]> Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-189
jiffies_to_timespec(const unsigned long jiffies, struct timespec *value) { /* * Convert jiffies to nanoseconds and separate with * one divide. */ u32 rem; value->tv_sec = div_u64_rem((u64)jiffies * TICK_NSEC, NSEC_PER_SEC, &rem); value->tv_nsec = rem; }
165,754
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: RenderThread::~RenderThread() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); if (web_database_observer_impl_.get()) web_database_observer_impl_->WaitForAllDatabasesToClose(); RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; RemoveFilter(vc_manager_->video_capture_message_filter()); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_.get()) file_thread_->Stop(); if (webkit_client_.get()) WebKit::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) PluginChannelBase::CleanupChannels(); if (RenderProcessImpl::InProcessPlugins()) CoUninitialize(); #endif } Commit Message: DevTools: move DevToolsAgent/Client into content. BUG=84078 TEST= Review URL: http://codereview.chromium.org/7461019 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@93596 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-20
RenderThread::~RenderThread() { FOR_EACH_OBSERVER( RenderProcessObserver, observers_, OnRenderProcessShutdown()); if (web_database_observer_impl_.get()) web_database_observer_impl_->WaitForAllDatabasesToClose(); RemoveFilter(devtools_agent_message_filter_.get()); devtools_agent_message_filter_ = NULL; RemoveFilter(audio_input_message_filter_.get()); audio_input_message_filter_ = NULL; RemoveFilter(audio_message_filter_.get()); audio_message_filter_ = NULL; RemoveFilter(vc_manager_->video_capture_message_filter()); RemoveFilter(db_message_filter_.get()); db_message_filter_ = NULL; if (file_thread_.get()) file_thread_->Stop(); if (webkit_client_.get()) WebKit::shutdown(); lazy_tls.Pointer()->Set(NULL); #if defined(OS_WIN) PluginChannelBase::CleanupChannels(); if (RenderProcessImpl::InProcessPlugins()) CoUninitialize(); #endif }
170,327
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } quantum=MagickMin(quantum/number_coordinates,BezierQuantum); primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); } Commit Message: ... CWE ID:
static MagickBooleanType TraceBezier(MVGInfo *mvg_info, const size_t number_coordinates) { double alpha, *coefficients, weight; PointInfo end, point, *points; PrimitiveInfo *primitive_info; register PrimitiveInfo *p; register ssize_t i, j; size_t control_points, quantum; /* Allocate coefficients. */ primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=number_coordinates; for (i=0; i < (ssize_t) number_coordinates; i++) { for (j=i+1; j < (ssize_t) number_coordinates; j++) { alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y); if (alpha > (double) SSIZE_MAX) { (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } if (alpha > (double) quantum) quantum=(size_t) alpha; } } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; quantum=MagickMin(quantum/number_coordinates,BezierQuantum); coefficients=(double *) AcquireQuantumMemory(number_coordinates, sizeof(*coefficients)); points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates* sizeof(*points)); if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL)) { if (points != (PointInfo *) NULL) points=(PointInfo *) RelinquishMagickMemory(points); if (coefficients != (double *) NULL) coefficients=(double *) RelinquishMagickMemory(coefficients); (void) ThrowMagickException(mvg_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",""); return(MagickFalse); } control_points=quantum*number_coordinates; if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } primitive_info=(*mvg_info->primitive_info)+mvg_info->offset; /* Compute bezier points. */ end=primitive_info[number_coordinates-1].point; for (i=0; i < (ssize_t) number_coordinates; i++) coefficients[i]=Permutate((ssize_t) number_coordinates-1,i); weight=0.0; for (i=0; i < (ssize_t) control_points; i++) { p=primitive_info; point.x=0.0; point.y=0.0; alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0); for (j=0; j < (ssize_t) number_coordinates; j++) { point.x+=alpha*coefficients[j]*p->point.x; point.y+=alpha*coefficients[j]*p->point.y; alpha*=weight/(1.0-weight); p++; } points[i]=point; weight+=1.0/control_points; } /* Bezier curves are just short segmented polys. */ p=primitive_info; for (i=0; i < (ssize_t) control_points; i++) { if (TracePoint(p,points[i]) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; } if (TracePoint(p,end) == MagickFalse) { points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickFalse); } p+=p->coordinates; primitive_info->coordinates=(size_t) (p-primitive_info); primitive_info->closed_subpath=MagickFalse; for (i=0; i < (ssize_t) primitive_info->coordinates; i++) { p->primitive=primitive_info->primitive; p--; } points=(PointInfo *) RelinquishMagickMemory(points); coefficients=(double *) RelinquishMagickMemory(coefficients); return(MagickTrue); }
169,485
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: alloc_limit_assert (char *fn_name, size_t size) { if (alloc_limit && size > alloc_limit) { alloc_limit_failure (fn_name, size); exit (-1); } } Commit Message: Fix integer overflows and harden memory allocator. CWE ID: CWE-190
alloc_limit_assert (char *fn_name, size_t size) { if (alloc_limit && size > alloc_limit) { alloc_limit_failure (fn_name, size); exit (-1); } }
168,354
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void RemoteFrame::ScheduleNavigation(Document& origin_document, const KURL& url, WebFrameLoadType frame_load_type, UserGestureStatus user_gesture_status) { FrameLoadRequest frame_request(&origin_document, ResourceRequest(url)); frame_request.GetResourceRequest().SetHasUserGesture( user_gesture_status == UserGestureStatus::kActive); frame_request.GetResourceRequest().SetFrameType( IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel : network::mojom::RequestContextFrameType::kNested); Navigate(frame_request, frame_load_type); } Commit Message: Add a check for disallowing remote frame navigations to local resources. Previously, RemoteFrame navigations did not perform any renderer-side checks and relied solely on the browser-side logic to block disallowed navigations via mechanisms like FilterURL. This means that blocked remote frame navigations were silently navigated to about:blank without any console error message. This CL adds a CanDisplay check to the remote navigation path to match an equivalent check done for local frame navigations. This way, the renderer can consistently block disallowed navigations in both cases and output an error message. Bug: 894399 Change-Id: I172f68f77c1676f6ca0172d2a6c78f7edc0e3b7a Reviewed-on: https://chromium-review.googlesource.com/c/1282390 Reviewed-by: Charlie Reis <[email protected]> Reviewed-by: Nate Chapin <[email protected]> Commit-Queue: Alex Moshchuk <[email protected]> Cr-Commit-Position: refs/heads/master@{#601022} CWE ID: CWE-732
void RemoteFrame::ScheduleNavigation(Document& origin_document, const KURL& url, WebFrameLoadType frame_load_type, UserGestureStatus user_gesture_status) { if (!origin_document.GetSecurityOrigin()->CanDisplay(url)) { origin_document.AddConsoleMessage(ConsoleMessage::Create( kSecurityMessageSource, kErrorMessageLevel, "Not allowed to load local resource: " + url.ElidedString())); return; } FrameLoadRequest frame_request(&origin_document, ResourceRequest(url)); frame_request.GetResourceRequest().SetHasUserGesture( user_gesture_status == UserGestureStatus::kActive); frame_request.GetResourceRequest().SetFrameType( IsMainFrame() ? network::mojom::RequestContextFrameType::kTopLevel : network::mojom::RequestContextFrameType::kNested); Navigate(frame_request, frame_load_type); }
172,614
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlDetectSAX2(ctxt); GROW; if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && (ctxt->input->end - ctxt->input->cur >= 4)) { xmlChar start[4]; xmlCharEncoding enc; start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) xmlSwitchEncoding(ctxt, enc); } if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ ctxt->instate = XML_PARSER_EOF; return; } } if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0"); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL)) xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID); ctxt->instate = XML_PARSER_DTD; ctxt->external = 1; while (((RAW == '<') && (NXT(1) == '?')) || ((RAW == '<') && (NXT(1) == '!')) || (RAW == '%') || IS_BLANK_CH(CUR)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; GROW; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); } } Commit Message: libxml: XML_PARSER_EOF checks from upstream BUG=229019 TBR=cpu Review URL: https://chromiumcodereview.appspot.com/14053009 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-119
xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, const xmlChar *SystemID) { xmlDetectSAX2(ctxt); GROW; if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && (ctxt->input->end - ctxt->input->cur >= 4)) { xmlChar start[4]; xmlCharEncoding enc; start[0] = RAW; start[1] = NXT(1); start[2] = NXT(2); start[3] = NXT(3); enc = xmlDetectCharEncoding(start, 4); if (enc != XML_CHAR_ENCODING_NONE) xmlSwitchEncoding(ctxt, enc); } if (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) { xmlParseTextDecl(ctxt); if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { /* * The XML REC instructs us to stop parsing right here */ ctxt->instate = XML_PARSER_EOF; return; } } if (ctxt->myDoc == NULL) { ctxt->myDoc = xmlNewDoc(BAD_CAST "1.0"); if (ctxt->myDoc == NULL) { xmlErrMemory(ctxt, "New Doc failed"); return; } ctxt->myDoc->properties = XML_DOC_INTERNAL; } if ((ctxt->myDoc != NULL) && (ctxt->myDoc->intSubset == NULL)) xmlCreateIntSubset(ctxt->myDoc, NULL, ExternalID, SystemID); ctxt->instate = XML_PARSER_DTD; ctxt->external = 1; while (((RAW == '<') && (NXT(1) == '?')) || ((RAW == '<') && (NXT(1) == '!')) || (RAW == '%') || IS_BLANK_CH(CUR)) { const xmlChar *check = CUR_PTR; unsigned int cons = ctxt->input->consumed; GROW; if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { xmlParseConditionalSections(ctxt); } else if (IS_BLANK_CH(CUR)) { NEXT; } else if (RAW == '%') { xmlParsePEReference(ctxt); } else xmlParseMarkupDecl(ctxt); /* * Pop-up of finished entities. */ while ((RAW == 0) && (ctxt->inputNr > 1)) xmlPopInput(ctxt); if ((CUR_PTR == check) && (cons == ctxt->input->consumed)) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); break; } } if (RAW != 0) { xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); } }
171,292
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: BufCompressedFill (BufFilePtr f) { CompressedFile *file; register char_type *stackp, *de_stack; register char_type finchar; register code_int code, oldcode, incode; BufChar *buf, *bufend; file = (CompressedFile *) f->private; buf = f->buffer; bufend = buf + BUFFILESIZE; stackp = file->stackp; de_stack = file->de_stack; finchar = file->finchar; oldcode = file->oldcode; while (buf < bufend) { while (stackp > de_stack && buf < bufend) *buf++ = *--stackp; if (buf == bufend) break; if (oldcode == -1) break; code = getcode (file); if (code == -1) break; if ( (code == CLEAR) && file->block_compress ) { for ( code = 255; code >= 0; code-- ) file->tab_prefix[code] = 0; file->clear_flg = 1; file->free_ent = FIRST - 1; if ( (code = getcode (file)) == -1 ) /* O, untimely death! */ break; } incode = code; /* * Special case for KwKwK string. */ if ( code >= file->free_ent ) { *stackp++ = finchar; code = oldcode; } /* * Generate output characters in reverse order */ while ( code >= 256 ) { *stackp++ = file->tab_suffix[code]; code = file->tab_prefix[code]; } /* * Generate the new entry. */ if ( (code=file->free_ent) < file->maxmaxcode ) { file->tab_prefix[code] = (unsigned short)oldcode; file->tab_suffix[code] = finchar; file->free_ent = code+1; } /* * Remember previous code. */ oldcode = incode; } file->oldcode = oldcode; file->stackp = stackp; file->finchar = finchar; if (buf == f->buffer) { f->left = 0; return BUFFILEEOF; } f->bufp = f->buffer + 1; f->left = (buf - f->buffer) - 1; return f->buffer[0]; } Commit Message: CWE ID: CWE-119
BufCompressedFill (BufFilePtr f) { CompressedFile *file; register char_type *stackp, *de_stack; register char_type finchar; register code_int code, oldcode, incode; BufChar *buf, *bufend; file = (CompressedFile *) f->private; buf = f->buffer; bufend = buf + BUFFILESIZE; stackp = file->stackp; de_stack = file->de_stack; finchar = file->finchar; oldcode = file->oldcode; while (buf < bufend) { while (stackp > de_stack && buf < bufend) *buf++ = *--stackp; if (buf == bufend) break; if (oldcode == -1) break; code = getcode (file); if (code == -1) break; if ( (code == CLEAR) && file->block_compress ) { for ( code = 255; code >= 0; code-- ) file->tab_prefix[code] = 0; file->clear_flg = 1; file->free_ent = FIRST - 1; if ( (code = getcode (file)) == -1 ) /* O, untimely death! */ break; } incode = code; /* * Special case for KwKwK string. */ if ( code >= file->free_ent ) { *stackp++ = finchar; code = oldcode; } /* * Generate output characters in reverse order */ while ( code >= 256 ) { if (stackp - de_stack >= STACK_SIZE - 1) return BUFFILEEOF; *stackp++ = file->tab_suffix[code]; code = file->tab_prefix[code]; } /* * Generate the new entry. */ if ( (code=file->free_ent) < file->maxmaxcode ) { file->tab_prefix[code] = (unsigned short)oldcode; file->tab_suffix[code] = finchar; file->free_ent = code+1; } /* * Remember previous code. */ oldcode = incode; } file->oldcode = oldcode; file->stackp = stackp; file->finchar = finchar; if (buf == f->buffer) { f->left = 0; return BUFFILEEOF; } f->bufp = f->buffer + 1; f->left = (buf - f->buffer) - 1; return f->buffer[0]; }
164,651
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ipt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((e->target_offset == sizeof(struct ipt_entry) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0 && unconditional(&e->ip)) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ipt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ipt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ipt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ipt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; } Commit Message: netfilter: x_tables: fix unconditional helper Ben Hawkes says: In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it is possible for a user-supplied ipt_entry structure to have a large next_offset field. This field is not bounds checked prior to writing a counter value at the supplied offset. Problem is that mark_source_chains should not have been called -- the rule doesn't have a next entry, so its supposed to return an absolute verdict of either ACCEPT or DROP. However, the function conditional() doesn't work as the name implies. It only checks that the rule is using wildcard address matching. However, an unconditional rule must also not be using any matches (no -m args). The underflow validator only checked the addresses, therefore passing the 'unconditional absolute verdict' test, while mark_source_chains also tested for presence of matches, and thus proceeeded to the next (not-existent) rule. Unify this so that all the callers have same idea of 'unconditional rule'. Reported-by: Ben Hawkes <[email protected]> Signed-off-by: Florian Westphal <[email protected]> Signed-off-by: Pablo Neira Ayuso <[email protected]> CWE ID: CWE-119
mark_source_chains(const struct xt_table_info *newinfo, unsigned int valid_hooks, void *entry0) { unsigned int hook; /* No recursion; use packet counter to save back ptrs (reset to 0 as we leave), and comefrom to save source hook bitmask */ for (hook = 0; hook < NF_INET_NUMHOOKS; hook++) { unsigned int pos = newinfo->hook_entry[hook]; struct ipt_entry *e = (struct ipt_entry *)(entry0 + pos); if (!(valid_hooks & (1 << hook))) continue; /* Set initial back pointer. */ e->counters.pcnt = pos; for (;;) { const struct xt_standard_target *t = (void *)ipt_get_target_c(e); int visited = e->comefrom & (1 << hook); if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { pr_err("iptables: loop hook %u pos %u %08X.\n", hook, pos, e->comefrom); return 0; } e->comefrom |= ((1 << hook) | (1 << NF_INET_NUMHOOKS)); /* Unconditional return/END. */ if ((unconditional(e) && (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < 0) || visited) { unsigned int oldpos, size; if ((strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0) && t->verdict < -NF_MAX_VERDICT - 1) { duprintf("mark_source_chains: bad " "negative verdict (%i)\n", t->verdict); return 0; } /* Return: backtrack through the last big jump. */ do { e->comefrom ^= (1<<NF_INET_NUMHOOKS); #ifdef DEBUG_IP_FIREWALL_USER if (e->comefrom & (1 << NF_INET_NUMHOOKS)) { duprintf("Back unset " "on hook %u " "rule %u\n", hook, pos); } #endif oldpos = pos; pos = e->counters.pcnt; e->counters.pcnt = 0; /* We're at the start. */ if (pos == oldpos) goto next; e = (struct ipt_entry *) (entry0 + pos); } while (oldpos == pos + e->next_offset); /* Move along one */ size = e->next_offset; e = (struct ipt_entry *) (entry0 + pos + size); e->counters.pcnt = pos; pos += size; } else { int newpos = t->verdict; if (strcmp(t->target.u.user.name, XT_STANDARD_TARGET) == 0 && newpos >= 0) { if (newpos > newinfo->size - sizeof(struct ipt_entry)) { duprintf("mark_source_chains: " "bad verdict (%i)\n", newpos); return 0; } /* This a jump; chase it. */ duprintf("Jump rule %u -> %u\n", pos, newpos); } else { /* ... this is a fallthru */ newpos = pos + e->next_offset; } e = (struct ipt_entry *) (entry0 + newpos); e->counters.pcnt = pos; pos = newpos; } } next: duprintf("Finished chain %u\n", hook); } return 1; }
167,370
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Blob::~Blob() { ThreadableBlobRegistry::unregisterBlobURL(m_internalURL); } Commit Message: Remove BlobRegistry indirection since there is only one implementation. BUG= Review URL: https://chromiumcodereview.appspot.com/15851008 git-svn-id: svn://svn.chromium.org/blink/trunk@152746 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID:
Blob::~Blob() { BlobRegistry::unregisterBlobURL(m_internalURL); }
170,679
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (put_user(len, optlen)) return -EFAULT; SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n", len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; } Commit Message: net/sctp: Validate parameter size for SCTP_GET_ASSOC_STATS Building sctp may fail with: In function ‘copy_from_user’, inlined from ‘sctp_getsockopt_assoc_stats’ at net/sctp/socket.c:5656:20: arch/x86/include/asm/uaccess_32.h:211:26: error: call to ‘copy_from_user_overflow’ declared with attribute error: copy_from_user() buffer size is not provably correct if built with W=1 due to a missing parameter size validation before the call to copy_from_user. Signed-off-by: Guenter Roeck <[email protected]> Acked-by: Vlad Yasevich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-20
static int sctp_getsockopt_assoc_stats(struct sock *sk, int len, char __user *optval, int __user *optlen) { struct sctp_assoc_stats sas; struct sctp_association *asoc = NULL; /* User must provide at least the assoc id */ if (len < sizeof(sctp_assoc_t)) return -EINVAL; /* Allow the struct to grow and fill in as much as possible */ len = min_t(size_t, len, sizeof(sas)); if (copy_from_user(&sas, optval, len)) return -EFAULT; asoc = sctp_id2assoc(sk, sas.sas_assoc_id); if (!asoc) return -EINVAL; sas.sas_rtxchunks = asoc->stats.rtxchunks; sas.sas_gapcnt = asoc->stats.gapcnt; sas.sas_outofseqtsns = asoc->stats.outofseqtsns; sas.sas_osacks = asoc->stats.osacks; sas.sas_isacks = asoc->stats.isacks; sas.sas_octrlchunks = asoc->stats.octrlchunks; sas.sas_ictrlchunks = asoc->stats.ictrlchunks; sas.sas_oodchunks = asoc->stats.oodchunks; sas.sas_iodchunks = asoc->stats.iodchunks; sas.sas_ouodchunks = asoc->stats.ouodchunks; sas.sas_iuodchunks = asoc->stats.iuodchunks; sas.sas_idupchunks = asoc->stats.idupchunks; sas.sas_opackets = asoc->stats.opackets; sas.sas_ipackets = asoc->stats.ipackets; /* New high max rto observed, will return 0 if not a single * RTO update took place. obs_rto_ipaddr will be bogus * in such a case */ sas.sas_maxrto = asoc->stats.max_obs_rto; memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr, sizeof(struct sockaddr_storage)); /* Mark beginning of a new observation period */ asoc->stats.max_obs_rto = asoc->rto_min; if (put_user(len, optlen)) return -EFAULT; SCTP_DEBUG_PRINTK("sctp_getsockopt_assoc_stat(%d): %d\n", len, sas.sas_assoc_id); if (copy_to_user(optval, &sas, len)) return -EFAULT; return 0; }
166,111
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static char *__filterShell(const char *arg) { r_return_val_if_fail (arg, NULL); char *a = malloc (strlen (arg) + 1); if (!a) { return NULL; } char *b = a; while (*arg) { switch (*arg) { case '@': case '`': case '|': case ';': case '\n': break; default: *b++ = *arg; break; } arg++; } *b = 0; return a; } Commit Message: More fixes for the CVE-2019-14745 CWE ID: CWE-78
static char *__filterShell(const char *arg) { r_return_val_if_fail (arg, NULL); char *a = malloc (strlen (arg) + 1); if (!a) { return NULL; } char *b = a; while (*arg) { char ch = *arg; switch (ch) { case '@': case '`': case '|': case ';': case '=': case '\n': break; default: *b++ = ch; break; } arg++; } *b = 0; return a; }
170,185
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BnHDCP::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case HDCP_SET_OBSERVER: { CHECK_INTERFACE(IHDCP, data, reply); sp<IHDCPObserver> observer = interface_cast<IHDCPObserver>(data.readStrongBinder()); reply->writeInt32(setObserver(observer)); return OK; } case HDCP_INIT_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); const char *host = data.readCString(); unsigned port = data.readInt32(); reply->writeInt32(initAsync(host, port)); return OK; } case HDCP_SHUTDOWN_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(shutdownAsync()); return OK; } case HDCP_GET_CAPS: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(getCaps()); return OK; } case HDCP_ENCRYPT: { size_t size = data.readInt32(); void *inData = malloc(2 * size); void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR; status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } case HDCP_ENCRYPT_NATIVE: { CHECK_INTERFACE(IHDCP, data, reply); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); size_t offset = data.readInt32(); size_t size = data.readInt32(); uint32_t streamCTR = data.readInt32(); void *outData = malloc(size); uint64_t inputCTR; status_t err = encryptNative(graphicBuffer, offset, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(outData); outData = NULL; return OK; } case HDCP_DECRYPT: { size_t size = data.readInt32(); void *inData = malloc(2 * size); void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR = data.readInt64(); status_t err = decrypt(inData, size, streamCTR, inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } default: return BBinder::onTransact(code, data, reply, flags); } } Commit Message: HDCP: buffer over flow check -- DO NOT MERGE bug: 20222489 Change-Id: I3a64a5999d68ea243d187f12ec7717b7f26d93a3 (cherry picked from commit 532cd7b86a5fdc7b9a30a45d8ae2d16ef7660a72) CWE ID: CWE-189
status_t BnHDCP::onTransact( uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { switch (code) { case HDCP_SET_OBSERVER: { CHECK_INTERFACE(IHDCP, data, reply); sp<IHDCPObserver> observer = interface_cast<IHDCPObserver>(data.readStrongBinder()); reply->writeInt32(setObserver(observer)); return OK; } case HDCP_INIT_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); const char *host = data.readCString(); unsigned port = data.readInt32(); reply->writeInt32(initAsync(host, port)); return OK; } case HDCP_SHUTDOWN_ASYNC: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(shutdownAsync()); return OK; } case HDCP_GET_CAPS: { CHECK_INTERFACE(IHDCP, data, reply); reply->writeInt32(getCaps()); return OK; } case HDCP_ENCRYPT: { size_t size = data.readInt32(); size_t bufSize = 2 * size; // watch out for overflow void *inData = NULL; if (bufSize > size) { inData = malloc(bufSize); } if (inData == NULL) { reply->writeInt32(ERROR_OUT_OF_RANGE); return OK; } void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR; status_t err = encrypt(inData, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } case HDCP_ENCRYPT_NATIVE: { CHECK_INTERFACE(IHDCP, data, reply); sp<GraphicBuffer> graphicBuffer = new GraphicBuffer(); data.read(*graphicBuffer); size_t offset = data.readInt32(); size_t size = data.readInt32(); uint32_t streamCTR = data.readInt32(); void *outData = malloc(size); uint64_t inputCTR; status_t err = encryptNative(graphicBuffer, offset, size, streamCTR, &inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->writeInt64(inputCTR); reply->write(outData, size); } free(outData); outData = NULL; return OK; } case HDCP_DECRYPT: { size_t size = data.readInt32(); size_t bufSize = 2 * size; // watch out for overflow void *inData = NULL; if (bufSize > size) { inData = malloc(bufSize); } if (inData == NULL) { reply->writeInt32(ERROR_OUT_OF_RANGE); return OK; } void *outData = (uint8_t *)inData + size; data.read(inData, size); uint32_t streamCTR = data.readInt32(); uint64_t inputCTR = data.readInt64(); status_t err = decrypt(inData, size, streamCTR, inputCTR, outData); reply->writeInt32(err); if (err == OK) { reply->write(outData, size); } free(inData); inData = outData = NULL; return OK; } default: return BBinder::onTransact(code, data, reply, flags); } }
173,361
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: exsltCryptoRc4EncryptFunction (xmlXPathParserContextPtr ctxt, int nargs) { int key_len = 0, key_size = 0; int str_len = 0, bin_len = 0, hex_len = 0; xmlChar *key = NULL, *str = NULL, *padkey = NULL; xmlChar *bin = NULL, *hex = NULL; xsltTransformContextPtr tctxt = NULL; if (nargs != 2) { xmlXPathSetArityError (ctxt); return; } tctxt = xsltXPathGetTransformContext(ctxt); str = xmlXPathPopString (ctxt); str_len = xmlUTF8Strlen (str); if (str_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (str); return; } key = xmlXPathPopString (ctxt); key_len = xmlUTF8Strlen (key); if (key_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (key); xmlFree (str); return; } padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1); if (padkey == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memset(padkey, 0, RC4_KEY_LENGTH + 1); key_size = xmlUTF8Strsize (key, key_len); if ((key_size > RC4_KEY_LENGTH) || (key_size < 0)) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: key size too long or key broken\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memcpy (padkey, key, key_size); /* encrypt it */ bin_len = str_len; bin = xmlStrdup (str); if (bin == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate string\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } PLATFORM_RC4_ENCRYPT (ctxt, padkey, str, str_len, bin, bin_len); /* encode it */ hex_len = str_len * 2 + 1; hex = xmlMallocAtomic (hex_len); if (hex == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate result\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } exsltCryptoBin2Hex (bin, str_len, hex, hex_len); xmlXPathReturnString (ctxt, hex); done: if (key != NULL) xmlFree (key); if (str != NULL) xmlFree (str); if (padkey != NULL) xmlFree (padkey); if (bin != NULL) xmlFree (bin); } 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
exsltCryptoRc4EncryptFunction (xmlXPathParserContextPtr ctxt, int nargs) { int key_len = 0; int str_len = 0, bin_len = 0, hex_len = 0; xmlChar *key = NULL, *str = NULL, *padkey = NULL; xmlChar *bin = NULL, *hex = NULL; xsltTransformContextPtr tctxt = NULL; if (nargs != 2) { xmlXPathSetArityError (ctxt); return; } tctxt = xsltXPathGetTransformContext(ctxt); str = xmlXPathPopString (ctxt); str_len = xmlStrlen (str); if (str_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (str); return; } key = xmlXPathPopString (ctxt); key_len = xmlStrlen (key); if (key_len == 0) { xmlXPathReturnEmptyString (ctxt); xmlFree (key); xmlFree (str); return; } padkey = xmlMallocAtomic (RC4_KEY_LENGTH + 1); if (padkey == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate padkey\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memset(padkey, 0, RC4_KEY_LENGTH + 1); if ((key_len > RC4_KEY_LENGTH) || (key_len < 0)) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: key size too long or key broken\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } memcpy (padkey, key, key_len); /* encrypt it */ bin_len = str_len; bin = xmlStrdup (str); if (bin == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate string\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } PLATFORM_RC4_ENCRYPT (ctxt, padkey, str, str_len, bin, bin_len); /* encode it */ hex_len = str_len * 2 + 1; hex = xmlMallocAtomic (hex_len); if (hex == NULL) { xsltTransformError(tctxt, NULL, tctxt->inst, "exsltCryptoRc4EncryptFunction: Failed to allocate result\n"); tctxt->state = XSLT_STATE_STOPPED; xmlXPathReturnEmptyString (ctxt); goto done; } exsltCryptoBin2Hex (bin, str_len, hex, hex_len); xmlXPathReturnString (ctxt, hex); done: if (key != NULL) xmlFree (key); if (str != NULL) xmlFree (str); if (padkey != NULL) xmlFree (padkey); if (bin != NULL) xmlFree (bin); }
173,288
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams( int version, const std::string& selection, const std::string& base_page_url, int now_on_tap_version) : version(version), start(base::string16::npos), end(base::string16::npos), selection(selection), base_page_url(base_page_url), now_on_tap_version(now_on_tap_version) {} Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards" BUG=644934 Review-Url: https://codereview.chromium.org/2361163003 Cr-Commit-Position: refs/heads/master@{#420899} CWE ID:
TemplateURLRef::SearchTermsArgs::ContextualSearchParams::ContextualSearchParams( int version, const std::string& selection, const std::string& base_page_url, int contextual_cards_version) : version(version), start(base::string16::npos), end(base::string16::npos), selection(selection), base_page_url(base_page_url),
171,646
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 js_Ast *callexp(js_State *J) { js_Ast *a = newexp(J); loop: if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; } return a; } Commit Message: CWE ID: CWE-674
static js_Ast *callexp(js_State *J) { js_Ast *a = newexp(J); SAVEREC(); loop: INCREC(); if (jsP_accept(J, '.')) { a = EXP2(MEMBER, a, identifiername(J)); goto loop; } if (jsP_accept(J, '[')) { a = EXP2(INDEX, a, expression(J, 0)); jsP_expect(J, ']'); goto loop; } if (jsP_accept(J, '(')) { a = EXP2(CALL, a, arguments(J)); jsP_expect(J, ')'); goto loop; } POPREC(); return a; }
165,135
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 bpf_map_inc(struct bpf_map *map, bool uref) { atomic_inc(&map->refcnt); if (uref) atomic_inc(&map->usercnt); } Commit Message: bpf: fix refcnt overflow On a system with >32Gbyte of phyiscal memory and infinite RLIMIT_MEMLOCK, the malicious application may overflow 32-bit bpf program refcnt. It's also possible to overflow map refcnt on 1Tb system. Impose 32k hard limit which means that the same bpf program or map cannot be shared by more than 32k processes. Fixes: 1be7f75d1668 ("bpf: enable non-root eBPF programs") Reported-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID:
void bpf_map_inc(struct bpf_map *map, bool uref) /* prog's and map's refcnt limit */ #define BPF_MAX_REFCNT 32768 struct bpf_map *bpf_map_inc(struct bpf_map *map, bool uref) { if (atomic_inc_return(&map->refcnt) > BPF_MAX_REFCNT) { atomic_dec(&map->refcnt); return ERR_PTR(-EBUSY); } if (uref) atomic_inc(&map->usercnt); return map; }
167,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: IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; } Commit Message: Add DCHECK to ensure IndexedDBDispatcher doesn't get re-created. This could happen if there are IDB objects that survive the call to didStopWorkerRunLoop. BUG=121734 TEST= Review URL: http://codereview.chromium.org/9999035 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@131679 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
IndexedDBDispatcher* IndexedDBDispatcher::ThreadSpecificInstance() { if (g_idb_dispatcher_tls.Pointer()->Get() == HAS_BEEN_DELETED) { NOTREACHED() << "Re-instantiating TLS IndexedDBDispatcher."; g_idb_dispatcher_tls.Pointer()->Set(NULL); } if (g_idb_dispatcher_tls.Pointer()->Get()) return g_idb_dispatcher_tls.Pointer()->Get(); IndexedDBDispatcher* dispatcher = new IndexedDBDispatcher; if (WorkerTaskRunner::Instance()->CurrentWorkerId()) webkit_glue::WorkerTaskRunner::Instance()->AddStopObserver(dispatcher); return dispatcher; }
171,039
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if (p == q || size < 16 || size > 256) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); } Commit Message: CWE ID: CWE-189
Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if ((p == q) || (size < 16) || (size > 256)) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); }
168,862
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) { if (paintingDisabled()) return; m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle()))); m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, angleSpan); } Commit Message: Reviewed by Kevin Ollivier. [wx] Fix strokeArc and fillRoundedRect drawing, and add clipPath support. https://bugs.webkit.org/show_bug.cgi?id=60847 git-svn-id: svn://svn.chromium.org/blink/trunk@86502 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
void GraphicsContext::strokeArc(const IntRect& rect, int startAngle, int angleSpan) { if (paintingDisabled()) return; m_data->context->SetPen(wxPen(strokeColor(), strokeThickness(), strokeStyleToWxPenStyle(strokeStyle()))); m_data->context->DrawEllipticArc(rect.x(), rect.y(), rect.width(), rect.height(), startAngle, startAngle + angleSpan); }
170,427
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Cluster* Segment::GetNext(const Cluster* pCurr) { assert(pCurr); assert(pCurr != &m_eos); assert(m_clusters); long idx = pCurr->m_index; if (idx >= 0) { assert(m_clusterCount > 0); assert(idx < m_clusterCount); assert(pCurr == m_clusters[idx]); ++idx; if (idx >= m_clusterCount) return &m_eos; // caller will LoadCluster as desired Cluster* const pNext = m_clusters[idx]; assert(pNext); assert(pNext->m_index >= 0); assert(pNext->m_index == idx); return pNext; } assert(m_clusterPreloadCount > 0); long long pos = pCurr->m_element_start; assert(m_size >= 0); // TODO const long long stop = m_start + m_size; // end of segment { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long id = ReadUInt(m_pReader, pos, len); assert(id == 0x0F43B675); // Cluster ID if (id != 0x0F43B675) return NULL; pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size > 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO pos += size; // consume payload } long long off_next = 0; while (pos < stop) { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long idpos = pos; // pos of next (potential) cluster const long long id = ReadUInt(m_pReader, idpos, len); assert(id > 0); // TODO pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size >= 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO if (size == 0) // weird continue; if (id == 0x0F43B675) { // Cluster ID const long long off_next_ = idpos - m_start; long long pos_; long len_; const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_); assert(status >= 0); if (status > 0) { off_next = off_next_; break; } } pos += size; // consume payload } if (off_next <= 0) return 0; Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else return pNext; } assert(i == j); Cluster* const pNext = Cluster::Create(this, -1, off_next); assert(pNext); const ptrdiff_t idx_next = i - m_clusters; // insertion position PreloadCluster(pNext, idx_next); assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); return pNext; } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
const Cluster* Segment::GetNext(const Cluster* pCurr) { assert(pCurr); assert(pCurr != &m_eos); assert(m_clusters); long idx = pCurr->m_index; if (idx >= 0) { assert(m_clusterCount > 0); assert(idx < m_clusterCount); assert(pCurr == m_clusters[idx]); ++idx; if (idx >= m_clusterCount) return &m_eos; // caller will LoadCluster as desired Cluster* const pNext = m_clusters[idx]; assert(pNext); assert(pNext->m_index >= 0); assert(pNext->m_index == idx); return pNext; } assert(m_clusterPreloadCount > 0); long long pos = pCurr->m_element_start; assert(m_size >= 0); // TODO const long long stop = m_start + m_size; // end of segment { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long id = ReadID(m_pReader, pos, len); if (id != 0x0F43B675) // Cluster ID return NULL; pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size > 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO pos += size; // consume payload } long long off_next = 0; while (pos < stop) { long len; long long result = GetUIntLength(m_pReader, pos, len); assert(result == 0); assert((pos + len) <= stop); // TODO if (result != 0) return NULL; const long long idpos = pos; // pos of next (potential) cluster const long long id = ReadID(m_pReader, idpos, len); if (id < 0) return NULL; pos += len; // consume ID result = GetUIntLength(m_pReader, pos, len); assert(result == 0); // TODO assert((pos + len) <= stop); // TODO const long long size = ReadUInt(m_pReader, pos, len); assert(size >= 0); // TODO pos += len; // consume length of size of element assert((pos + size) <= stop); // TODO if (size == 0) // weird continue; if (id == 0x0F43B675) { // Cluster ID const long long off_next_ = idpos - m_start; long long pos_; long len_; const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_); assert(status >= 0); if (status > 0) { off_next = off_next_; break; } } pos += size; // consume payload } if (off_next <= 0) return 0; Cluster** const ii = m_clusters + m_clusterCount; Cluster** i = ii; Cluster** const jj = ii + m_clusterPreloadCount; Cluster** j = jj; while (i < j) { Cluster** const k = i + (j - i) / 2; assert(k < jj); Cluster* const pNext = *k; assert(pNext); assert(pNext->m_index < 0); pos = pNext->GetPosition(); if (pos < off_next) i = k + 1; else if (pos > off_next) j = k; else return pNext; } assert(i == j); Cluster* const pNext = Cluster::Create(this, -1, off_next); if (pNext == NULL) return NULL; const ptrdiff_t idx_next = i - m_clusters; // insertion position if (!PreloadCluster(pNext, idx_next)) { delete pNext; return NULL; } assert(m_clusters); assert(idx_next < m_clusterSize); assert(m_clusters[idx_next] == pNext); return pNext; }
173,822
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderFrameDevToolsAgentHost::DestroyOnRenderFrameGone() { scoped_refptr<RenderFrameDevToolsAgentHost> protect(this); if (IsAttached()) RevokePolicy(); ForceDetachAllClients(); frame_host_ = nullptr; agent_ptr_.reset(); SetFrameTreeNode(nullptr); Release(); } Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages If the page navigates to web ui, we force detach the debugger extension. [email protected] Bug: 798222 Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3 Reviewed-on: https://chromium-review.googlesource.com/935961 Commit-Queue: Dmitry Gozman <[email protected]> Reviewed-by: Devlin <[email protected]> Reviewed-by: Pavel Feldman <[email protected]> Reviewed-by: Nasko Oskov <[email protected]> Cr-Commit-Position: refs/heads/master@{#540916} CWE ID: CWE-20
void RenderFrameDevToolsAgentHost::DestroyOnRenderFrameGone() { scoped_refptr<RenderFrameDevToolsAgentHost> protect(this); if (IsAttached()) RevokePolicy(); ForceDetachAllSessions(); frame_host_ = nullptr; agent_ptr_.reset(); SetFrameTreeNode(nullptr); Release(); }
173,249
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void adjust_branches(struct bpf_prog *prog, int pos, int delta) { struct bpf_insn *insn = prog->insnsi; int insn_cnt = prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) != BPF_JMP || BPF_OP(insn->code) == BPF_CALL || BPF_OP(insn->code) == BPF_EXIT) continue; /* adjust offset of jmps if necessary */ if (i < pos && i + insn->off + 1 > pos) insn->off += delta; else if (i > pos && i + insn->off + 1 < pos) insn->off -= delta; } } Commit Message: bpf: fix branch offset adjustment on backjumps after patching ctx expansion When ctx access is used, the kernel often needs to expand/rewrite instructions, so after that patching, branch offsets have to be adjusted for both forward and backward jumps in the new eBPF program, but for backward jumps it fails to account the delta. Meaning, for example, if the expansion happens exactly on the insn that sits at the jump target, it doesn't fix up the back jump offset. Analysis on what the check in adjust_branches() is currently doing: /* adjust offset of jmps if necessary */ if (i < pos && i + insn->off + 1 > pos) insn->off += delta; else if (i > pos && i + insn->off + 1 < pos) insn->off -= delta; First condition (forward jumps): Before: After: insns[0] insns[0] insns[1] <--- i/insn insns[1] <--- i/insn insns[2] <--- pos insns[P] <--- pos insns[3] insns[P] `------| delta insns[4] <--- target_X insns[P] `-----| insns[5] insns[3] insns[4] <--- target_X insns[5] First case is if we cross pos-boundary and the jump instruction was before pos. This is handeled correctly. I.e. if i == pos, then this would mean our jump that we currently check was the patchlet itself that we just injected. Since such patchlets are self-contained and have no awareness of any insns before or after the patched one, the delta is correctly not adjusted. Also, for the second condition in case of i + insn->off + 1 == pos, means we jump to that newly patched instruction, so no offset adjustment are needed. That part is correct. Second condition (backward jumps): Before: After: insns[0] insns[0] insns[1] <--- target_X insns[1] <--- target_X insns[2] <--- pos <-- target_Y insns[P] <--- pos <-- target_Y insns[3] insns[P] `------| delta insns[4] <--- i/insn insns[P] `-----| insns[5] insns[3] insns[4] <--- i/insn insns[5] Second interesting case is where we cross pos-boundary and the jump instruction was after pos. Backward jump with i == pos would be impossible and pose a bug somewhere in the patchlet, so the first condition checking i > pos is okay only by itself. However, i + insn->off + 1 < pos does not always work as intended to trigger the adjustment. It works when jump targets would be far off where the delta wouldn't matter. But, for example, where the fixed insn->off before pointed to pos (target_Y), it now points to pos + delta, so that additional room needs to be taken into account for the check. This means that i) both tests here need to be adjusted into pos + delta, and ii) for the second condition, the test needs to be <= as pos itself can be a target in the backjump, too. Fixes: 9bac3d6d548e ("bpf: allow extended BPF programs access skb fields") Signed-off-by: Daniel Borkmann <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-200
static void adjust_branches(struct bpf_prog *prog, int pos, int delta) { struct bpf_insn *insn = prog->insnsi; int insn_cnt = prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) != BPF_JMP || BPF_OP(insn->code) == BPF_CALL || BPF_OP(insn->code) == BPF_EXIT) continue; /* adjust offset of jmps if necessary */ if (i < pos && i + insn->off + 1 > pos) insn->off += delta; else if (i > pos + delta && i + insn->off + 1 <= pos + delta) insn->off -= delta; } }
167,413