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: XvQueryAdaptors( Display *dpy, Window window, unsigned int *p_nAdaptors, XvAdaptorInfo **p_pAdaptors) { XExtDisplayInfo *info = xv_find_display(dpy); xvQueryAdaptorsReq *req; xvQueryAdaptorsReply rep; size_t size; unsigned int ii, jj; char *name; XvAdaptorInfo *pas = NULL, *pa; XvFormat *pfs, *pf; char *buffer = NULL; char *buffer; char *string; xvAdaptorInfo *pa; xvFormat *pf; } u; Commit Message: CWE ID: CWE-125
XvQueryAdaptors( Display *dpy, Window window, unsigned int *p_nAdaptors, XvAdaptorInfo **p_pAdaptors) { XExtDisplayInfo *info = xv_find_display(dpy); xvQueryAdaptorsReq *req; xvQueryAdaptorsReply rep; size_t size; unsigned int ii, jj; char *name; char *end; XvAdaptorInfo *pas = NULL, *pa; XvFormat *pfs, *pf; char *buffer = NULL; char *buffer; char *string; xvAdaptorInfo *pa; xvFormat *pf; } u;
165,009
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_DEFINE2(osf_getdomainname, char __user *, name, int, namelen) { unsigned len; int i; if (!access_ok(VERIFY_WRITE, name, namelen)) return -EFAULT; len = namelen; if (namelen > 32) len = 32; down_read(&uts_sem); for (i = 0; i < len; ++i) { __put_user(utsname()->domainname[i], name + i); if (utsname()->domainname[i] == '\0') break; } up_read(&uts_sem); return 0; } 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_DEFINE2(osf_getdomainname, char __user *, name, int, namelen) { unsigned len; int i; if (!access_ok(VERIFY_WRITE, name, namelen)) return -EFAULT; len = namelen; if (len > 32) len = 32; down_read(&uts_sem); for (i = 0; i < len; ++i) { __put_user(utsname()->domainname[i], name + i); if (utsname()->domainname[i] == '\0') break; } up_read(&uts_sem); return 0; }
165,867
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: find_insert(png_const_charp what, png_charp param) { png_uint_32 chunk = 0; png_charp parameter_list[1024]; int i, nparams; /* Assemble the chunk name */ for (i=0; i<4; ++i) { char ch = what[i]; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) chunk = (chunk << 8) + what[i]; else break; } if (i < 4 || what[4] != 0) { fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what); exit(1); } /* Assemble the parameter list. */ nparams = find_parameters(what, param, parameter_list, 1024); # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) switch (chunk) { case CHUNK(105,67,67,80): /* iCCP */ if (nparams == 2) return make_insert(what, insert_iCCP, nparams, parameter_list); break; case CHUNK(116,69,88,116): /* tEXt */ if (nparams == 2) return make_insert(what, insert_tEXt, nparams, parameter_list); break; case CHUNK(122,84,88,116): /* zTXt */ if (nparams == 2) return make_insert(what, insert_zTXt, nparams, parameter_list); break; case CHUNK(105,84,88,116): /* iTXt */ if (nparams == 4) return make_insert(what, insert_iTXt, nparams, parameter_list); break; case CHUNK(104,73,83,84): /* hIST */ if (nparams <= 256) return make_insert(what, insert_hIST, nparams, parameter_list); break; #if 0 case CHUNK(115,80,76,84): /* sPLT */ return make_insert(what, insert_sPLT, nparams, parameter_list); #endif default: fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n", what); exit(1); } bad_parameter_count(what, nparams); return NULL; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
find_insert(png_const_charp what, png_charp param) { png_uint_32 chunk = 0; png_charp parameter_list[1024]; int i, nparams; /* Assemble the chunk name */ for (i=0; i<4; ++i) { char ch = what[i]; if ((ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)) chunk = (chunk << 8) + what[i]; else break; } if (i < 4 || what[4] != 0) { fprintf(stderr, "makepng --insert \"%s\": invalid chunk name\n", what); exit(1); } /* Assemble the parameter list. */ nparams = find_parameters(what, param, parameter_list, 1024); # define CHUNK(a,b,c,d) (((a)<<24)+((b)<<16)+((c)<<8)+(d)) switch (chunk) { case CHUNK(105,67,67,80): /* iCCP */ if (nparams == 2) return make_insert(what, insert_iCCP, nparams, parameter_list); break; case CHUNK(116,69,88,116): /* tEXt */ if (nparams == 2) return make_insert(what, insert_tEXt, nparams, parameter_list); break; case CHUNK(122,84,88,116): /* zTXt */ if (nparams == 2) return make_insert(what, insert_zTXt, nparams, parameter_list); break; case CHUNK(105,84,88,116): /* iTXt */ if (nparams == 4) return make_insert(what, insert_iTXt, nparams, parameter_list); break; case CHUNK(104,73,83,84): /* hIST */ if (nparams <= 256) return make_insert(what, insert_hIST, nparams, parameter_list); break; case CHUNK(115,66,73,84): /* sBIT */ if (nparams <= 4) return make_insert(what, insert_sBIT, nparams, parameter_list); break; #if 0 case CHUNK(115,80,76,84): /* sPLT */ return make_insert(what, insert_sPLT, nparams, parameter_list); #endif default: fprintf(stderr, "makepng --insert \"%s\": unrecognized chunk name\n", what); exit(1); } bad_parameter_count(what, nparams); return NULL; }
173,578
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ImageFetched(const ContentSuggestion::ID& id, const GURL& url, const base::string16& title, const base::string16& text, base::Time timeout_at, const gfx::Image& image) { if (!ShouldNotifyInState(app_status_listener_.GetState())) { return; // Became foreground while we were fetching the image; forget it. } DVLOG(1) << "Fetched " << image.Size().width() << "x" << image.Size().height() << " image for " << url.spec(); if (ContentSuggestionsNotificationHelper::SendNotification( id, url, title, text, CropSquare(image), timeout_at)) { RecordContentSuggestionsNotificationImpression( id.category().IsKnownCategory(KnownCategories::ARTICLES) ? CONTENT_SUGGESTIONS_ARTICLE : CONTENT_SUGGESTIONS_NONARTICLE); } } Commit Message: NTP: cap number of notifications/day 1 by default; Finch-configurable. BUG=689465 Review-Url: https://codereview.chromium.org/2691023002 Cr-Commit-Position: refs/heads/master@{#450389} CWE ID: CWE-399
void ImageFetched(const ContentSuggestion::ID& id, const GURL& url, const base::string16& title, const base::string16& text, base::Time timeout_at, const gfx::Image& image) { if (!ShouldNotifyInState(app_status_listener_.GetState())) { return; // Became foreground while we were fetching the image; forget it. } DVLOG(1) << "Fetched " << image.Size().width() << "x" << image.Size().height() << " image for " << url.spec(); ConsumeQuota(profile_->GetPrefs()); if (ContentSuggestionsNotificationHelper::SendNotification( id, url, title, text, CropSquare(image), timeout_at)) { RecordContentSuggestionsNotificationImpression( id.category().IsKnownCategory(KnownCategories::ARTICLES) ? CONTENT_SUGGESTIONS_ARTICLE : CONTENT_SUGGESTIONS_NONARTICLE); } }
172,037
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutget *lgp) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops = nfsd4_layout_ops[lgp->lg_layout_type]; __be32 *p; dprintk("%s: err %d\n", __func__, nfserr); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t)); if (!p) goto out; *p++ = cpu_to_be32(1); /* we always set return-on-close */ *p++ = cpu_to_be32(lgp->lg_sid.si_generation); p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque, sizeof(stateid_opaque_t)); *p++ = cpu_to_be32(1); /* we always return a single layout */ p = xdr_encode_hyper(p, lgp->lg_seg.offset); p = xdr_encode_hyper(p, lgp->lg_seg.length); *p++ = cpu_to_be32(lgp->lg_seg.iomode); *p++ = cpu_to_be32(lgp->lg_layout_type); nfserr = ops->encode_layoutget(xdr, lgp); out: kfree(lgp->lg_content); return nfserr; } 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
nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr, struct nfsd4_layoutget *lgp) { struct xdr_stream *xdr = &resp->xdr; const struct nfsd4_layout_ops *ops; __be32 *p; dprintk("%s: err %d\n", __func__, nfserr); if (nfserr) goto out; nfserr = nfserr_resource; p = xdr_reserve_space(xdr, 36 + sizeof(stateid_opaque_t)); if (!p) goto out; *p++ = cpu_to_be32(1); /* we always set return-on-close */ *p++ = cpu_to_be32(lgp->lg_sid.si_generation); p = xdr_encode_opaque_fixed(p, &lgp->lg_sid.si_opaque, sizeof(stateid_opaque_t)); *p++ = cpu_to_be32(1); /* we always return a single layout */ p = xdr_encode_hyper(p, lgp->lg_seg.offset); p = xdr_encode_hyper(p, lgp->lg_seg.length); *p++ = cpu_to_be32(lgp->lg_seg.iomode); *p++ = cpu_to_be32(lgp->lg_layout_type); ops = nfsd4_layout_ops[lgp->lg_layout_type]; nfserr = ops->encode_layoutget(xdr, lgp); out: kfree(lgp->lg_content); return nfserr; }
168,149
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (((int)arg >= cdi->capacity)) return -EINVAL; return cdrom_slot_status(cdi, arg); } Commit Message: cdrom: Fix info leak/OOB read in cdrom_ioctl_drive_status Like d88b6d04: "cdrom: information leak in cdrom_ioctl_media_changed()" There is another cast from unsigned long to int which causes a bounds check to fail with specially crafted input. The value is then used as an index in the slot array in cdrom_slot_status(). Signed-off-by: Scott Bauer <[email protected]> Signed-off-by: Scott Bauer <[email protected]> Cc: [email protected] Signed-off-by: Jens Axboe <[email protected]> CWE ID: CWE-200
static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (arg >= cdi->capacity) return -EINVAL; return cdrom_slot_status(cdi, arg); }
169,035
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XSLStyleSheet::XSLStyleSheet(XSLImportRule* parentRule, const String& originalURL, const KURL& finalURL) : m_ownerNode(0) , m_originalURL(originalURL) , m_finalURL(finalURL) , m_isDisabled(false) , m_embedded(false) , m_processed(false) // Child sheets get marked as processed when the libxslt engine has finally seen them. , m_stylesheetDoc(0) , m_stylesheetDocTaken(false) , m_parentStyleSheet(parentRule ? parentRule->parentStyleSheet() : 0) { } Commit Message: Avoid reparsing an XSLT stylesheet after the first failure. Certain libxslt versions appear to leave the doc in an invalid state when parsing fails. We should cache this result and avoid re-parsing. (The test cannot be converted to text-only due to its invalid stylesheet). [email protected],[email protected],[email protected] BUG=271939 Review URL: https://chromiumcodereview.appspot.com/23103007 git-svn-id: svn://svn.chromium.org/blink/trunk@156248 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
XSLStyleSheet::XSLStyleSheet(XSLImportRule* parentRule, const String& originalURL, const KURL& finalURL) : m_ownerNode(0) , m_originalURL(originalURL) , m_finalURL(finalURL) , m_isDisabled(false) , m_embedded(false) , m_processed(false) // Child sheets get marked as processed when the libxslt engine has finally seen them. , m_stylesheetDoc(0) , m_stylesheetDocTaken(false) , m_compilationFailed(false) , m_parentStyleSheet(parentRule ? parentRule->parentStyleSheet() : 0) { }
171,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: static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } Commit Message: bpf: fix missing error return in check_stack_boundary() Prevent indirect stack accesses at non-constant addresses, which would permit reading and corrupting spilled pointers. Fixes: f1174f77b50c ("bpf/verifier: rework value tracking") Signed-off-by: Jann Horn <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Signed-off-by: Daniel Borkmann <[email protected]> CWE ID: CWE-119
static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i, slot, spi; if (regs[regno].type != PTR_TO_STACK) { /* Allow zero-byte read from NULL, regardless of pointer type */ if (zero_size_allowed && access_size == 0 && register_is_null(regs[regno])) return 0; verbose(env, "R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } /* Only allow fixed-offset stack reads */ if (!tnum_is_const(regs[regno].var_off)) { char tn_buf[48]; tnum_strn(tn_buf, sizeof(tn_buf), regs[regno].var_off); verbose(env, "invalid variable stack read R%d var_off=%s\n", regno, tn_buf); return -EACCES; } off = regs[regno].off + regs[regno].var_off.value; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size < 0 || (access_size == 0 && !zero_size_allowed)) { verbose(env, "invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (env->prog->aux->stack_depth < -off) env->prog->aux->stack_depth = -off; if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { slot = -(off + i) - 1; spi = slot / BPF_REG_SIZE; if (state->allocated_stack <= slot || state->stack[spi].slot_type[slot % BPF_REG_SIZE] != STACK_MISC) { verbose(env, "invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; }
167,640
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: explicit MountState(DriveFsHost* host) : host_(host), mojo_connection_delegate_( host_->delegate_->CreateMojoConnectionDelegate()), pending_token_(base::UnguessableToken::Create()), binding_(this) { source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()}); std::string datadir_option = base::StrCat( {"datadir=", host_->profile_path_.Append(kDataPath) .Append(host_->delegate_->GetAccountId().GetAccountIdKey()) .value()}); chromeos::disks::DiskMountManager::GetInstance()->MountPath( source_path_, "", base::StrCat( {"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}), {datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE, chromeos::MOUNT_ACCESS_MODE_READ_WRITE); auto bootstrap = mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection()); mojom::DriveFsDelegatePtr delegate; binding_.Bind(mojo::MakeRequest(&delegate)); bootstrap->Init( {base::in_place, host_->delegate_->GetAccountId().GetUserEmail()}, mojo::MakeRequest(&drivefs_), std::move(delegate)); PendingConnectionManager::Get().ExpectOpenIpcChannel( pending_token_, base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection, base::Unretained(this))); } Commit Message: Add a fake DriveFS launcher client. Using DriveFS requires building and deploying ChromeOS. Add a client for the fake DriveFS launcher to allow the use of a real DriveFS from a ChromeOS chroot to be used with a target_os="chromeos" build of chrome. This connects to the fake DriveFS launcher using mojo over a unix domain socket named by a command-line flag, using the launcher to create DriveFS instances. Bug: 848126 Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1 Reviewed-on: https://chromium-review.googlesource.com/1098434 Reviewed-by: Xiyuan Xia <[email protected]> Commit-Queue: Sam McNally <[email protected]> Cr-Commit-Position: refs/heads/master@{#567513} CWE ID:
explicit MountState(DriveFsHost* host) : host_(host), mojo_connection_delegate_( host_->delegate_->CreateMojoConnectionDelegate()), pending_token_(base::UnguessableToken::Create()), binding_(this) { source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()}); std::string datadir_option = base::StrCat( {"datadir=", host_->profile_path_.Append(kDataPath) .Append(host_->delegate_->GetAccountId().GetAccountIdKey()) .value()}); auto bootstrap = mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection()); mojom::DriveFsDelegatePtr delegate; binding_.Bind(mojo::MakeRequest(&delegate)); bootstrap->Init( {base::in_place, host_->delegate_->GetAccountId().GetUserEmail()}, mojo::MakeRequest(&drivefs_), std::move(delegate)); PendingConnectionManager::Get().ExpectOpenIpcChannel( pending_token_, base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection, base::Unretained(this))); chromeos::disks::DiskMountManager::GetInstance()->MountPath( source_path_, "", base::StrCat( {"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}), {datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE, chromeos::MOUNT_ACCESS_MODE_READ_WRITE); }
171,729
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_instantiated(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); } Commit Message: KEYS: Fix race between updating and finding a negative key Consolidate KEY_FLAG_INSTANTIATED, KEY_FLAG_NEGATIVE and the rejection error into one field such that: (1) The instantiation state can be modified/read atomically. (2) The error can be accessed atomically with the state. (3) The error isn't stored unioned with the payload pointers. This deals with the problem that the state is spread over three different objects (two bits and a separate variable) and reading or updating them atomically isn't practical, given that not only can uninstantiated keys change into instantiated or rejected keys, but rejected keys can also turn into instantiated keys - and someone accessing the key might not be using any locking. The main side effect of this problem is that what was held in the payload may change, depending on the state. For instance, you might observe the key to be in the rejected state. You then read the cached error, but if the key semaphore wasn't locked, the key might've become instantiated between the two reads - and you might now have something in hand that isn't actually an error code. The state is now KEY_IS_UNINSTANTIATED, KEY_IS_POSITIVE or a negative error code if the key is negatively instantiated. The key_is_instantiated() function is replaced with key_is_positive() to avoid confusion as negative keys are also 'instantiated'. Additionally, barriering is included: (1) Order payload-set before state-set during instantiation. (2) Order state-read before payload-read when using the key. Further separate barriering is necessary if RCU is being used to access the payload content after reading the payload pointers. Fixes: 146aa8b1453b ("KEYS: Merge the type-specific data with the payload data") Cc: [email protected] # v4.4+ Reported-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]> Reviewed-by: Eric Biggers <[email protected]> CWE ID: CWE-20
void big_key_revoke(struct key *key) { struct path *path = (struct path *)&key->payload.data[big_key_path]; /* clear the quota */ key_payload_reserve(key, 0); if (key_is_positive(key) && (size_t)key->payload.data[big_key_len] > BIG_KEY_FILE_THRESHOLD) vfs_truncate(path, 0); }
167,693
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; } else { stack->done = 1; } efree(ent1); return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->type == ST_FIELD && ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } } Commit Message: Fix for bug #72790 and bug #72799 CWE ID: CWE-476
static void php_wddx_pop_element(void *user_data, const XML_Char *name) { st_entry *ent1, *ent2; wddx_stack *stack = (wddx_stack *)user_data; HashTable *target_hash; zend_class_entry **pce; zval *obj; zval *tmp; TSRMLS_FETCH(); /* OBJECTS_FIXME */ if (stack->top == 0) { return; } if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) || !strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) || !strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) || !strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) || !strcmp(name, EL_DATETIME)) { wddx_stack_top(stack, (void**)&ent1); if (!ent1->data) { if (stack->top > 1) { stack->top--; efree(ent1); } else { stack->done = 1; } return; } if (!strcmp(name, EL_BINARY)) { int new_len=0; unsigned char *new_str; new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len); STR_FREE(Z_STRVAL_P(ent1->data)); if (new_str) { Z_STRVAL_P(ent1->data) = new_str; Z_STRLEN_P(ent1->data) = new_len; } else { ZVAL_EMPTY_STRING(ent1->data); } } /* Call __wakeup() method on the object. */ if (Z_TYPE_P(ent1->data) == IS_OBJECT) { zval *fname, *retval = NULL; MAKE_STD_ZVAL(fname); ZVAL_STRING(fname, "__wakeup", 1); call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC); zval_dtor(fname); FREE_ZVAL(fname); if (retval) { zval_ptr_dtor(&retval); } } if (stack->top > 1) { stack->top--; wddx_stack_top(stack, (void**)&ent2); /* if non-existent field */ if (ent2->data == NULL) { zval_ptr_dtor(&ent1->data); efree(ent1); return; } if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) { target_hash = HASH_OF(ent2->data); if (ent1->varname) { if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) && Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) && ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) { zend_bool incomplete_class = 0; zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) { incomplete_class = 1; pce = &PHP_IC_ENTRY; } /* Initialize target object */ MAKE_STD_ZVAL(obj); object_init_ex(obj, *pce); /* Merge current hashtable with object's default properties */ zend_hash_merge(Z_OBJPROP_P(obj), Z_ARRVAL_P(ent2->data), (void (*)(void *)) zval_add_ref, (void *) &tmp, sizeof(zval *), 0); if (incomplete_class) { php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data)); } /* Clean up old array entry */ zval_ptr_dtor(&ent2->data); /* Set stack entry to point to the newly created object */ ent2->data = obj; /* Clean up class name var entry */ zval_ptr_dtor(&ent1->data); } else if (Z_TYPE_P(ent2->data) == IS_OBJECT) { zend_class_entry *old_scope = EG(scope); EG(scope) = Z_OBJCE_P(ent2->data); Z_DELREF_P(ent1->data); add_property_zval(ent2->data, ent1->varname, ent1->data); EG(scope) = old_scope; } else { zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL); } efree(ent1->varname); } else { zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL); } } efree(ent1); } else { stack->done = 1; } } else if (!strcmp(name, EL_VAR) && stack->varname) { efree(stack->varname); stack->varname = NULL; } else if (!strcmp(name, EL_FIELD)) { st_entry *ent; wddx_stack_top(stack, (void **)&ent); efree(ent); stack->top--; } }
166,949
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: WORD32 ih264d_parse_sei_message(dec_struct_t *ps_dec, dec_bit_stream_t *ps_bitstrm) { UWORD32 ui4_payload_type, ui4_payload_size; UWORD32 u4_bits; WORD32 i4_status = 0; do { ui4_payload_type = 0; u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); while(0xff == u4_bits) { u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); ui4_payload_type += 255; } ui4_payload_type += u4_bits; ui4_payload_size = 0; u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); while(0xff == u4_bits) { u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); ui4_payload_size += 255; } ui4_payload_size += u4_bits; i4_status = ih264d_parse_sei_payload(ps_bitstrm, ui4_payload_type, ui4_payload_size, ps_dec); if(i4_status == -1) { i4_status = 0; break; } if(i4_status != OK) return i4_status; if(ih264d_check_byte_aligned(ps_bitstrm) == 0) { u4_bits = ih264d_get_bit_h264(ps_bitstrm); if(0 == u4_bits) { H264_DEC_DEBUG_PRINT("\nError in parsing SEI message"); } while(0 == ih264d_check_byte_aligned(ps_bitstrm)) { u4_bits = ih264d_get_bit_h264(ps_bitstrm); if(u4_bits) { H264_DEC_DEBUG_PRINT("\nError in parsing SEI message"); } } } } while(ps_bitstrm->u4_ofst < ps_bitstrm->u4_max_ofst); return (i4_status); } Commit Message: Decoder: Increased allocation and added checks in sei parsing. This prevents heap overflow while parsing sei_message. Bug: 63122634 Test: ran PoC on unpatched/patched Change-Id: I61c1ff4ac053a060be8c24da4671db985cac628c (cherry picked from commit f2b70d353768af8d4ead7f32497be05f197925ef) CWE ID: CWE-200
WORD32 ih264d_parse_sei_message(dec_struct_t *ps_dec, dec_bit_stream_t *ps_bitstrm) { UWORD32 ui4_payload_type, ui4_payload_size; UWORD32 u4_bits; WORD32 i4_status = 0; do { ui4_payload_type = 0; u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); while(0xff == u4_bits && !EXCEED_OFFSET(ps_bitstrm)) { u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); ui4_payload_type += 255; } ui4_payload_type += u4_bits; ui4_payload_size = 0; u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); while(0xff == u4_bits && !EXCEED_OFFSET(ps_bitstrm)) { u4_bits = ih264d_get_bits_h264(ps_bitstrm, 8); ui4_payload_size += 255; } ui4_payload_size += u4_bits; i4_status = ih264d_parse_sei_payload(ps_bitstrm, ui4_payload_type, ui4_payload_size, ps_dec); if(i4_status == -1) { i4_status = 0; break; } if(i4_status != OK) return i4_status; if(ih264d_check_byte_aligned(ps_bitstrm) == 0) { u4_bits = ih264d_get_bit_h264(ps_bitstrm); if(0 == u4_bits) { H264_DEC_DEBUG_PRINT("\nError in parsing SEI message"); } while(0 == ih264d_check_byte_aligned(ps_bitstrm) && !EXCEED_OFFSET(ps_bitstrm)) { u4_bits = ih264d_get_bit_h264(ps_bitstrm); if(u4_bits) { H264_DEC_DEBUG_PRINT("\nError in parsing SEI message"); } } } } while(ps_bitstrm->u4_ofst < ps_bitstrm->u4_max_ofst); return (i4_status); }
174,107
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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[]) { p_fm_config_conx_hdlt hdl; int instance = 0; fm_mgr_config_errno_t res; char *rem_addr = NULL; char *community = "public"; char Opts[256]; int arg; char *command; int i; /* Get options at the command line (overide default values) */ strcpy(Opts, "i:d:h-"); while ((arg = getopt(argc, argv, Opts)) != EOF) { switch (arg) { case 'h': case '-': usage(argv[0]); return(0); case 'i': instance = atol(optarg); break; case 'd': rem_addr = optarg; break; default: usage(argv[0]); return(-1); } } if(optind >= argc){ fprintf(stderr, "Command required\n"); usage(argv[0]); return -1; } command = argv[optind++]; printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance); if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK) { fprintf(stderr, "Failed to initialize the client handle: %d\n", res); goto die_clean; } if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK) { fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res)); goto die_clean; } for(i=0;i<commandListLen;i++){ if(strcmp(command,commandList[i].name) == 0){ return commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]); } } fprintf(stderr, "Command (%s) is not valid\n",command); usage(argv[0]); res = -1; die_clean: if (hdl) free(hdl); return res; } Commit Message: Fix scripts and code that use well-known tmp files. CWE ID: CWE-362
int main(int argc, char *argv[]) { p_fm_config_conx_hdlt hdl = NULL; int instance = 0; fm_mgr_config_errno_t res; char *rem_addr = NULL; char *community = "public"; char Opts[256]; int arg; char *command; int i; /* Get options at the command line (overide default values) */ strcpy(Opts, "i:d:h-"); while ((arg = getopt(argc, argv, Opts)) != EOF) { switch (arg) { case 'h': case '-': usage(argv[0]); return(0); case 'i': instance = atol(optarg); break; case 'd': rem_addr = optarg; break; default: usage(argv[0]); return(-1); } } if(optind >= argc){ fprintf(stderr, "Command required\n"); usage(argv[0]); return -1; } command = argv[optind++]; printf("Connecting to %s FM instance %d\n", (rem_addr==NULL) ? "LOCAL":rem_addr, instance); if((res = fm_mgr_config_init(&hdl,instance, rem_addr, community)) != FM_CONF_OK) { fprintf(stderr, "Failed to initialize the client handle: %d\n", res); goto cleanup; } if((res = fm_mgr_config_connect(hdl)) != FM_CONF_OK) { fprintf(stderr, "Failed to connect: (%d) %s\n",res,fm_mgr_get_error_str(res)); goto cleanup; } for(i=0;i<commandListLen;i++){ if(strcmp(command,commandList[i].name) == 0){ res = commandList[i].cmdPtr(hdl, commandList[i].mgr, (argc - optind), &argv[optind]); goto cleanup; } } fprintf(stderr, "Command (%s) is not valid\n",command); usage(argv[0]); res = -1; cleanup: if (hdl) { if (hdl->sm_hdl) { if (hdl->sm_hdl->c_path[0]) unlink(hdl->sm_hdl->c_path); } if (hdl->pm_hdl) { if (hdl->pm_hdl->c_path[0]) unlink(hdl->pm_hdl->c_path); } if (hdl->fe_hdl) { if (hdl->fe_hdl->c_path[0]) unlink(hdl->fe_hdl->c_path); } free(hdl); } return res; }
170,127
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) { attributes->usage = (audio_usage_t) parcel.readInt32(); attributes->content_type = (audio_content_type_t) parcel.readInt32(); attributes->source = (audio_source_t) parcel.readInt32(); attributes->flags = (audio_flags_mask_t) parcel.readInt32(); const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); if (hasFlattenedTag) { String16 tags = parcel.readString16(); ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); if (realTagSize <= 0) { strcpy(attributes->tags, ""); } else { size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; utf16_to_utf8(tags.string(), tagSize, attributes->tags); } } else { ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); strcpy(attributes->tags, ""); } } Commit Message: Add bound checks to utf16_to_utf8 Bug: 29250543 Change-Id: I3518416e89ed901021970958fb6005fd69129f7c (cherry picked from commit 1d3f4278b2666d1a145af2f54782c993aa07d1d9) CWE ID: CWE-119
void unmarshallAudioAttributes(const Parcel& parcel, audio_attributes_t *attributes) { attributes->usage = (audio_usage_t) parcel.readInt32(); attributes->content_type = (audio_content_type_t) parcel.readInt32(); attributes->source = (audio_source_t) parcel.readInt32(); attributes->flags = (audio_flags_mask_t) parcel.readInt32(); const bool hasFlattenedTag = (parcel.readInt32() == kAudioAttributesMarshallTagFlattenTags); if (hasFlattenedTag) { String16 tags = parcel.readString16(); ssize_t realTagSize = utf16_to_utf8_length(tags.string(), tags.size()); if (realTagSize <= 0) { strcpy(attributes->tags, ""); } else { size_t tagSize = realTagSize > AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 ? AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - 1 : realTagSize; utf16_to_utf8(tags.string(), tagSize, attributes->tags, sizeof(attributes->tags) / sizeof(attributes->tags[0])); } } else { ALOGE("unmarshallAudioAttributes() received unflattened tags, ignoring tag values"); strcpy(attributes->tags, ""); } }
174,159
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg) { void *choice; struct menu *m; int err; #ifdef CONFIG_CMD_BMP /* display BMP if available */ if (cfg->bmp) { if (get_relfile(cmdtp, cfg->bmp, image_load_addr)) { run_command("cls", 0); bmp_display(image_load_addr, BMP_ALIGN_CENTER, BMP_ALIGN_CENTER); } else { printf("Skipping background bmp %s for failure\n", cfg->bmp); } } #endif m = pxe_menu_to_menu(cfg); if (!m) return; err = menu_get_choice(m, &choice); menu_destroy(m); /* * err == 1 means we got a choice back from menu_get_choice. * * err == -ENOENT if the menu was setup to select the default but no * default was set. in that case, we should continue trying to boot * labels that haven't been attempted yet. * * otherwise, the user interrupted or there was some other error and * we give up. */ if (err == 1) { err = label_boot(cmdtp, choice); if (!err) return; } else if (err != -ENOENT) { return; } boot_unattempted_labels(cmdtp, cfg); } Commit Message: Merge branch '2020-01-22-master-imports' - Re-add U8500 platform support - Add bcm968360bg support - Assorted Keymile fixes - Other assorted bugfixes CWE ID: CWE-787
void handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg) { void *choice; struct menu *m; int err; #ifdef CONFIG_CMD_BMP /* display BMP if available */ if (cfg->bmp) { if (get_relfile(cmdtp, cfg->bmp, image_load_addr)) { if (CONFIG_IS_ENABLED(CMD_CLS)) run_command("cls", 0); bmp_display(image_load_addr, BMP_ALIGN_CENTER, BMP_ALIGN_CENTER); } else { printf("Skipping background bmp %s for failure\n", cfg->bmp); } } #endif m = pxe_menu_to_menu(cfg); if (!m) return; err = menu_get_choice(m, &choice); menu_destroy(m); /* * err == 1 means we got a choice back from menu_get_choice. * * err == -ENOENT if the menu was setup to select the default but no * default was set. in that case, we should continue trying to boot * labels that haven't been attempted yet. * * otherwise, the user interrupted or there was some other error and * we give up. */ if (err == 1) { err = label_boot(cmdtp, choice); if (!err) return; } else if (err != -ENOENT) { return; } boot_unattempted_labels(cmdtp, cfg); }
169,637
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DocumentLoader::CommitNavigation(const AtomicString& mime_type, const KURL& overriding_url) { if (state_ != kProvisional) return; if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) { SetHistoryItemStateForCommit( GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_, HistoryNavigationType::kDifferentDocument); } DCHECK_EQ(state_, kProvisional); GetFrameLoader().CommitProvisionalLoad(); if (!frame_) return; const AtomicString& encoding = GetResponse().TextEncodingName(); Document* owner_document = nullptr; if (Document::ShouldInheritSecurityOriginFromOwner(Url())) { Frame* owner_frame = frame_->Tree().Parent(); if (!owner_frame) owner_frame = frame_->Loader().Opener(); if (owner_frame && owner_frame->IsLocalFrame()) owner_document = ToLocalFrame(owner_frame)->GetDocument(); } DCHECK(frame_->GetPage()); ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing; if (!Document::ThreadedParsingEnabledForTesting()) parsing_policy = kForceSynchronousParsing; InstallNewDocument(Url(), owner_document, frame_->ShouldReuseDefaultView(Url()) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew, mime_type, encoding, InstallNewDocumentReason::kNavigation, parsing_policy, overriding_url); parser_->SetDocumentWasLoadedAsPartOfNavigation(); if (request_.WasDiscarded()) frame_->GetDocument()->SetWasDiscarded(true); frame_->GetDocument()->MaybeHandleHttpRefresh( response_.HttpHeaderField(HTTPNames::Refresh), Document::kHttpRefreshFromHeader); } Commit Message: Prevent sandboxed documents from reusing the default window Bug: 377995 Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541 Reviewed-on: https://chromium-review.googlesource.com/983558 Commit-Queue: Andy Paicu <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Cr-Commit-Position: refs/heads/master@{#567663} CWE ID: CWE-285
void DocumentLoader::CommitNavigation(const AtomicString& mime_type, const KURL& overriding_url) { if (state_ != kProvisional) return; if (!GetFrameLoader().StateMachine()->CreatingInitialEmptyDocument()) { SetHistoryItemStateForCommit( GetFrameLoader().GetDocumentLoader()->GetHistoryItem(), load_type_, HistoryNavigationType::kDifferentDocument); } DCHECK_EQ(state_, kProvisional); GetFrameLoader().CommitProvisionalLoad(); if (!frame_) return; const AtomicString& encoding = GetResponse().TextEncodingName(); Document* owner_document = nullptr; if (Document::ShouldInheritSecurityOriginFromOwner(Url())) { Frame* owner_frame = frame_->Tree().Parent(); if (!owner_frame) owner_frame = frame_->Loader().Opener(); if (owner_frame && owner_frame->IsLocalFrame()) owner_document = ToLocalFrame(owner_frame)->GetDocument(); } DCHECK(frame_->GetPage()); ParserSynchronizationPolicy parsing_policy = kAllowAsynchronousParsing; if (!Document::ThreadedParsingEnabledForTesting()) parsing_policy = kForceSynchronousParsing; InstallNewDocument( Url(), owner_document, frame_->ShouldReuseDefaultView(Url(), GetContentSecurityPolicy()) ? WebGlobalObjectReusePolicy::kUseExisting : WebGlobalObjectReusePolicy::kCreateNew, mime_type, encoding, InstallNewDocumentReason::kNavigation, parsing_policy, overriding_url); parser_->SetDocumentWasLoadedAsPartOfNavigation(); if (request_.WasDiscarded()) frame_->GetDocument()->SetWasDiscarded(true); frame_->GetDocument()->MaybeHandleHttpRefresh( response_.HttpHeaderField(HTTPNames::Refresh), Document::kHttpRefreshFromHeader); }
173,197
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static int DefragMfIpv6Test(void) { int retval = 0; int ip_id = 9; Packet *p = NULL; DefragInit(); Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8); Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8); Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8); if (p1 == NULL || p2 == NULL || p3 == NULL) { goto end; } p = Defrag(NULL, NULL, p1, NULL); if (p != NULL) { goto end; } p = Defrag(NULL, NULL, p2, NULL); if (p != NULL) { goto end; } /* This should return a packet as MF=0. */ p = Defrag(NULL, NULL, p3, NULL); if (p == NULL) { goto end; } /* For IPv6 the expected length is just the length of the payload * of 2 fragments, so 16. */ if (IPV6_GET_PLEN(p) != 16) { goto end; } retval = 1; end: if (p1 != NULL) { SCFree(p1); } if (p2 != NULL) { SCFree(p2); } if (p3 != NULL) { SCFree(p3); } if (p != NULL) { SCFree(p); } DefragDestroy(); return retval; } Commit Message: defrag - take protocol into account during re-assembly The IP protocol was not being used to match fragments with their packets allowing a carefully constructed packet with a different protocol to be matched, allowing re-assembly to complete, creating a packet that would not be re-assembled by the destination host. CWE ID: CWE-358
static int DefragMfIpv6Test(void) { int retval = 0; int ip_id = 9; Packet *p = NULL; DefragInit(); Packet *p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 2, 1, 'C', 8); Packet *p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 0, 1, 'A', 8); Packet *p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 1, 0, 'B', 8); if (p1 == NULL || p2 == NULL || p3 == NULL) { goto end; } p = Defrag(NULL, NULL, p1, NULL); if (p != NULL) { goto end; } p = Defrag(NULL, NULL, p2, NULL); if (p != NULL) { goto end; } /* This should return a packet as MF=0. */ p = Defrag(NULL, NULL, p3, NULL); if (p == NULL) { goto end; } /* For IPv6 the expected length is just the length of the payload * of 2 fragments, so 16. */ if (IPV6_GET_PLEN(p) != 16) { goto end; } retval = 1; end: if (p1 != NULL) { SCFree(p1); } if (p2 != NULL) { SCFree(p2); } if (p3 != NULL) { SCFree(p3); } if (p != NULL) { SCFree(p); } DefragDestroy(); return retval; }
168,300
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xfs_attr3_leaf_getvalue( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; int valuelen; leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); ASSERT(args->index < ichdr.count); entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); ASSERT(name_loc->namelen == args->namelen); ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0); valuelen = be16_to_cpu(name_loc->valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; memcpy(args->value, &name_loc->nameval[args->namelen], valuelen); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); ASSERT(name_rmt->namelen == args->namelen); ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0); valuelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount, valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; } return 0; } Commit Message: xfs: remote attribute overwrite causes transaction overrun Commit e461fcb ("xfs: remote attribute lookups require the value length") passes the remote attribute length in the xfs_da_args structure on lookup so that CRC calculations and validity checking can be performed correctly by related code. This, unfortunately has the side effect of changing the args->valuelen parameter in cases where it shouldn't. That is, when we replace a remote attribute, the incoming replacement stores the value and length in args->value and args->valuelen, but then the lookup which finds the existing remote attribute overwrites args->valuelen with the length of the remote attribute being replaced. Hence when we go to create the new attribute, we create it of the size of the existing remote attribute, not the size it is supposed to be. When the new attribute is much smaller than the old attribute, this results in a transaction overrun and an ASSERT() failure on a debug kernel: XFS: Assertion failed: tp->t_blk_res_used <= tp->t_blk_res, file: fs/xfs/xfs_trans.c, line: 331 Fix this by keeping the remote attribute value length separate to the attribute value length in the xfs_da_args structure. The enables us to pass the length of the remote attribute to be removed without overwriting the new attribute's length. Also, ensure that when we save remote block contexts for a later rename we zero the original state variables so that we don't confuse the state of the attribute to be removes with the state of the new attribute that we just added. [Spotted by Brain Foster.] Signed-off-by: Dave Chinner <[email protected]> Reviewed-by: Brian Foster <[email protected]> Signed-off-by: Dave Chinner <[email protected]> CWE ID: CWE-19
xfs_attr3_leaf_getvalue( struct xfs_buf *bp, struct xfs_da_args *args) { struct xfs_attr_leafblock *leaf; struct xfs_attr3_icleaf_hdr ichdr; struct xfs_attr_leaf_entry *entry; struct xfs_attr_leaf_name_local *name_loc; struct xfs_attr_leaf_name_remote *name_rmt; int valuelen; leaf = bp->b_addr; xfs_attr3_leaf_hdr_from_disk(&ichdr, leaf); ASSERT(ichdr.count < XFS_LBSIZE(args->dp->i_mount) / 8); ASSERT(args->index < ichdr.count); entry = &xfs_attr3_leaf_entryp(leaf)[args->index]; if (entry->flags & XFS_ATTR_LOCAL) { name_loc = xfs_attr3_leaf_name_local(leaf, args->index); ASSERT(name_loc->namelen == args->namelen); ASSERT(memcmp(args->name, name_loc->nameval, args->namelen) == 0); valuelen = be16_to_cpu(name_loc->valuelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = valuelen; return 0; } if (args->valuelen < valuelen) { args->valuelen = valuelen; return XFS_ERROR(ERANGE); } args->valuelen = valuelen; memcpy(args->value, &name_loc->nameval[args->namelen], valuelen); } else { name_rmt = xfs_attr3_leaf_name_remote(leaf, args->index); ASSERT(name_rmt->namelen == args->namelen); ASSERT(memcmp(args->name, name_rmt->name, args->namelen) == 0); args->rmtvaluelen = be32_to_cpu(name_rmt->valuelen); args->rmtblkno = be32_to_cpu(name_rmt->valueblk); args->rmtblkcnt = xfs_attr3_rmt_blocks(args->dp->i_mount, args->rmtvaluelen); if (args->flags & ATTR_KERNOVAL) { args->valuelen = args->rmtvaluelen; return 0; } if (args->valuelen < args->rmtvaluelen) { args->valuelen = args->rmtvaluelen; return XFS_ERROR(ERANGE); } args->valuelen = args->rmtvaluelen; } return 0; }
166,736
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FrameSelection::SetSelectionDeprecated( const SelectionInDOMTree& passed_selection, const SetSelectionData& options) { DCHECK(IsAvailable()); passed_selection.AssertValidFor(GetDocument()); SelectionInDOMTree::Builder builder(passed_selection); if (ShouldAlwaysUseDirectionalSelection(frame_)) builder.SetIsDirectional(true); SelectionInDOMTree new_selection = builder.Build(); if (granularity_strategy_ && !options.DoNotClearStrategy()) granularity_strategy_->Clear(); granularity_ = options.Granularity(); if (options.ShouldCloseTyping()) TypingCommand::CloseTyping(frame_); if (options.ShouldClearTypingStyle()) frame_->GetEditor().ClearTypingStyle(); const SelectionInDOMTree old_selection_in_dom_tree = selection_editor_->GetSelectionInDOMTree(); if (old_selection_in_dom_tree == new_selection) return false; selection_editor_->SetSelection(new_selection); ScheduleVisualUpdateForPaintInvalidationIfNeeded(); const Document& current_document = GetDocument(); frame_->GetEditor().RespondToChangedSelection( old_selection_in_dom_tree.ComputeStartPosition(), options.ShouldCloseTyping() ? TypingContinuation::kEnd : TypingContinuation::kContinue); DCHECK_EQ(current_document, GetDocument()); return true; } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
bool FrameSelection::SetSelectionDeprecated( const SelectionInDOMTree& passed_selection, const SetSelectionData& options) { DCHECK(IsAvailable()); passed_selection.AssertValidFor(GetDocument()); SelectionInDOMTree::Builder builder(passed_selection); if (ShouldAlwaysUseDirectionalSelection(frame_)) builder.SetIsDirectional(true); SelectionInDOMTree new_selection = builder.Build(); if (granularity_strategy_ && !options.DoNotClearStrategy()) granularity_strategy_->Clear(); granularity_ = options.Granularity(); if (options.ShouldCloseTyping()) TypingCommand::CloseTyping(frame_); if (options.ShouldClearTypingStyle()) frame_->GetEditor().ClearTypingStyle(); const SelectionInDOMTree old_selection_in_dom_tree = selection_editor_->GetSelectionInDOMTree(); const bool is_changed = old_selection_in_dom_tree != new_selection; const bool should_show_handle = options.ShouldShowHandle(); if (!is_changed && is_handle_visible_ == should_show_handle) return false; if (is_changed) selection_editor_->SetSelection(new_selection); is_handle_visible_ = should_show_handle; ScheduleVisualUpdateForPaintInvalidationIfNeeded(); const Document& current_document = GetDocument(); frame_->GetEditor().RespondToChangedSelection( old_selection_in_dom_tree.ComputeStartPosition(), options.ShouldCloseTyping() ? TypingContinuation::kEnd : TypingContinuation::kContinue); DCHECK_EQ(current_document, GetDocument()); return true; }
171,760
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = mWidth * mHeight * 3 / 2; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); } Commit Message: codecs: check OMX buffer size before use in (h263|h264)dec Bug: 27833616 Change-Id: I0fd599b3da431425d89236ffdd9df423c11947c0 CWE ID: CWE-20
void SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { bool SoftAVC::drainOneOutputBuffer(int32_t picId, uint8_t* data) { List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex); BufferInfo *outInfo = *outQueue.begin(); OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; OMX_U32 frameSize = mWidth * mHeight * 3 / 2; if (outHeader->nAllocLen - outHeader->nOffset < frameSize) { android_errorWriteLog(0x534e4554, "27833616"); return false; } outQueue.erase(outQueue.begin()); OMX_BUFFERHEADERTYPE *header = mPicToHeaderMap.valueFor(picId); outHeader->nTimeStamp = header->nTimeStamp; outHeader->nFlags = header->nFlags; outHeader->nFilledLen = frameSize; uint8_t *dst = outHeader->pBuffer + outHeader->nOffset; const uint8_t *srcY = data; const uint8_t *srcU = srcY + mWidth * mHeight; const uint8_t *srcV = srcU + mWidth * mHeight / 4; size_t srcYStride = mWidth; size_t srcUStride = mWidth / 2; size_t srcVStride = srcUStride; copyYV12FrameToOutputBuffer(dst, srcY, srcU, srcV, srcYStride, srcUStride, srcVStride); mPicToHeaderMap.removeItem(picId); delete header; outInfo->mOwnedByUs = false; notifyFillBufferDone(outHeader); return true; }
174,177
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DevToolsWindow::InspectedContentsClosing() { web_contents_->GetRenderViewHost()->ClosePage(); } Commit Message: DevTools: handle devtools renderer unresponsiveness during beforeunload event interception This patch fixes the crash which happenes under the following conditions: 1. DevTools window is in undocked state 2. DevTools renderer is unresponsive 3. User attempts to close inspected page BUG=322380 Review URL: https://codereview.chromium.org/84883002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@237611 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void DevToolsWindow::InspectedContentsClosing() { intercepted_page_beforeunload_ = false; web_contents_->GetRenderViewHost()->ClosePage(); }
171,267
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void WebGLRenderingContextBase::TexImageHelperHTMLVideoElement( const SecurityOrigin* security_origin, TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, HTMLVideoElement* video, const IntRect& source_image_rect, GLsizei depth, GLint unpack_image_height, ExceptionState& exception_state) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateHTMLVideoElement(security_origin, func_name, video, exception_state)) return; WebGLTexture* texture = ValidateTexImageBinding(func_name, function_id, target); if (!texture) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, 0, format, type, xoffset, yoffset, zoffset)) return; WebMediaPlayer::VideoFrameUploadMetadata frame_metadata = {}; int already_uploaded_id = -1; WebMediaPlayer::VideoFrameUploadMetadata* frame_metadata_ptr = nullptr; if (RuntimeEnabledFeatures::ExperimentalCanvasFeaturesEnabled()) { already_uploaded_id = texture->GetLastUploadedVideoFrameId(); frame_metadata_ptr = &frame_metadata; } bool source_image_rect_is_default = source_image_rect == SentinelEmptyRect() || source_image_rect == IntRect(0, 0, video->videoWidth(), video->videoHeight()); const bool use_copyTextureCHROMIUM = function_id == kTexImage2D && source_image_rect_is_default && depth == 1 && GL_TEXTURE_2D == target && CanUseTexImageByGPU(format, type); if (use_copyTextureCHROMIUM) { DCHECK_EQ(xoffset, 0); DCHECK_EQ(yoffset, 0); DCHECK_EQ(zoffset, 0); if (video->CopyVideoTextureToPlatformTexture( ContextGL(), target, texture->Object(), internalformat, format, type, level, unpack_premultiply_alpha_, unpack_flip_y_, already_uploaded_id, frame_metadata_ptr)) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } if (source_image_rect_is_default) { ScopedUnpackParametersResetRestore( this, unpack_flip_y_ || unpack_premultiply_alpha_); if (video->TexImageImpl( static_cast<WebMediaPlayer::TexImageFunctionID>(function_id), target, ContextGL(), texture->Object(), level, ConvertTexInternalFormat(internalformat, type), format, type, xoffset, yoffset, zoffset, unpack_flip_y_, unpack_premultiply_alpha_ && unpack_colorspace_conversion_ == GL_NONE)) { texture->ClearLastUploadedFrame(); return; } } if (use_copyTextureCHROMIUM) { std::unique_ptr<ImageBufferSurface> surface = WTF::WrapUnique(new AcceleratedImageBufferSurface( IntSize(video->videoWidth(), video->videoHeight()))); if (surface->IsValid()) { std::unique_ptr<ImageBuffer> image_buffer( ImageBuffer::Create(std::move(surface))); if (image_buffer) { video->PaintCurrentFrame( image_buffer->Canvas(), IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr, already_uploaded_id, frame_metadata_ptr); TexImage2DBase(target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, nullptr); if (image_buffer->CopyToPlatformTexture( FunctionIDToSnapshotReason(function_id), ContextGL(), target, texture->Object(), unpack_premultiply_alpha_, unpack_flip_y_, IntPoint(0, 0), IntRect(0, 0, video->videoWidth(), video->videoHeight()))) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } } } scoped_refptr<Image> image = VideoFrameToImage(video, already_uploaded_id, frame_metadata_ptr); if (!image) return; TexImageImpl(function_id, target, level, internalformat, xoffset, yoffset, zoffset, format, type, image.get(), WebGLImageConversion::kHtmlDomVideo, unpack_flip_y_, unpack_premultiply_alpha_, source_image_rect, depth, unpack_image_height); texture->UpdateLastUploadedFrame(frame_metadata); } Commit Message: Tighten about IntRect use in WebGL with overflow detection BUG=784183 TEST=test case in the bug in ASAN build [email protected] Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel Change-Id: Ie25ca328af99de7828e28e6a6e3d775f1bebc43f Reviewed-on: https://chromium-review.googlesource.com/811826 Reviewed-by: Kenneth Russell <[email protected]> Commit-Queue: Zhenyao Mo <[email protected]> Cr-Commit-Position: refs/heads/master@{#522213} CWE ID: CWE-125
void WebGLRenderingContextBase::TexImageHelperHTMLVideoElement( const SecurityOrigin* security_origin, TexImageFunctionID function_id, GLenum target, GLint level, GLint internalformat, GLenum format, GLenum type, GLint xoffset, GLint yoffset, GLint zoffset, HTMLVideoElement* video, const IntRect& source_image_rect, GLsizei depth, GLint unpack_image_height, ExceptionState& exception_state) { const char* func_name = GetTexImageFunctionName(function_id); if (isContextLost()) return; if (!ValidateHTMLVideoElement(security_origin, func_name, video, exception_state)) return; WebGLTexture* texture = ValidateTexImageBinding(func_name, function_id, target); if (!texture) return; TexImageFunctionType function_type; if (function_id == kTexImage2D || function_id == kTexImage3D) function_type = kTexImage; else function_type = kTexSubImage; if (!ValidateTexFunc(func_name, function_type, kSourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 1, 0, format, type, xoffset, yoffset, zoffset)) return; WebMediaPlayer::VideoFrameUploadMetadata frame_metadata = {}; int already_uploaded_id = -1; WebMediaPlayer::VideoFrameUploadMetadata* frame_metadata_ptr = nullptr; if (RuntimeEnabledFeatures::ExperimentalCanvasFeaturesEnabled()) { already_uploaded_id = texture->GetLastUploadedVideoFrameId(); frame_metadata_ptr = &frame_metadata; } if (!source_image_rect.IsValid()) { SynthesizeGLError(GL_INVALID_OPERATION, func_name, "source sub-rectangle specified via pixel unpack " "parameters is invalid"); return; } bool source_image_rect_is_default = source_image_rect == SentinelEmptyRect() || source_image_rect == IntRect(0, 0, video->videoWidth(), video->videoHeight()); const bool use_copyTextureCHROMIUM = function_id == kTexImage2D && source_image_rect_is_default && depth == 1 && GL_TEXTURE_2D == target && CanUseTexImageByGPU(format, type); if (use_copyTextureCHROMIUM) { DCHECK_EQ(xoffset, 0); DCHECK_EQ(yoffset, 0); DCHECK_EQ(zoffset, 0); if (video->CopyVideoTextureToPlatformTexture( ContextGL(), target, texture->Object(), internalformat, format, type, level, unpack_premultiply_alpha_, unpack_flip_y_, already_uploaded_id, frame_metadata_ptr)) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } if (source_image_rect_is_default) { ScopedUnpackParametersResetRestore( this, unpack_flip_y_ || unpack_premultiply_alpha_); if (video->TexImageImpl( static_cast<WebMediaPlayer::TexImageFunctionID>(function_id), target, ContextGL(), texture->Object(), level, ConvertTexInternalFormat(internalformat, type), format, type, xoffset, yoffset, zoffset, unpack_flip_y_, unpack_premultiply_alpha_ && unpack_colorspace_conversion_ == GL_NONE)) { texture->ClearLastUploadedFrame(); return; } } if (use_copyTextureCHROMIUM) { std::unique_ptr<ImageBufferSurface> surface = WTF::WrapUnique(new AcceleratedImageBufferSurface( IntSize(video->videoWidth(), video->videoHeight()))); if (surface->IsValid()) { std::unique_ptr<ImageBuffer> image_buffer( ImageBuffer::Create(std::move(surface))); if (image_buffer) { video->PaintCurrentFrame( image_buffer->Canvas(), IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr, already_uploaded_id, frame_metadata_ptr); TexImage2DBase(target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, nullptr); if (image_buffer->CopyToPlatformTexture( FunctionIDToSnapshotReason(function_id), ContextGL(), target, texture->Object(), unpack_premultiply_alpha_, unpack_flip_y_, IntPoint(0, 0), IntRect(0, 0, video->videoWidth(), video->videoHeight()))) { texture->UpdateLastUploadedFrame(frame_metadata); return; } } } } scoped_refptr<Image> image = VideoFrameToImage(video, already_uploaded_id, frame_metadata_ptr); if (!image) return; TexImageImpl(function_id, target, level, internalformat, xoffset, yoffset, zoffset, format, type, image.get(), WebGLImageConversion::kHtmlDomVideo, unpack_flip_y_, unpack_premultiply_alpha_, source_image_rect, depth, unpack_image_height); texture->UpdateLastUploadedFrame(frame_metadata); }
172,667
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserEventRouter::TabPinnedStateChanged(WebContents* contents, int index) { TabStripModel* tab_strip = NULL; int tab_index; if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) { DictionaryValue* changed_properties = new DictionaryValue(); changed_properties->SetBoolean(tab_keys::kPinnedKey, tab_strip->IsTabPinned(tab_index)); DispatchTabUpdatedEvent(contents, changed_properties); } } Commit Message: Do not pass URLs in onUpdated events to extensions unless they have the "tabs" permission. BUG=168442 Review URL: https://chromiumcodereview.appspot.com/11824004 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@176406 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-264
void BrowserEventRouter::TabPinnedStateChanged(WebContents* contents, int index) { TabStripModel* tab_strip = NULL; int tab_index; if (ExtensionTabUtil::GetTabStripModel(contents, &tab_strip, &tab_index)) { scoped_ptr<DictionaryValue> changed_properties(new DictionaryValue()); changed_properties->SetBoolean(tab_keys::kPinnedKey, tab_strip->IsTabPinned(tab_index)); DispatchTabUpdatedEvent(contents, changed_properties.Pass()); } }
171,451
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_tinterrupt(struct snd_timer_instance *timeri, unsigned long resolution, unsigned long ticks) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread *r, r1; struct timespec tstamp; int prev, append = 0; memset(&tstamp, 0, sizeof(tstamp)); spin_lock(&tu->qlock); if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) | (1 << SNDRV_TIMER_EVENT_TICK))) == 0) { spin_unlock(&tu->qlock); return; } if (tu->last_resolution != resolution || ticks > 0) { if (timer_tstamp_monotonic) ktime_get_ts(&tstamp); else getnstimeofday(&tstamp); } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) && tu->last_resolution != resolution) { r1.event = SNDRV_TIMER_EVENT_RESOLUTION; r1.tstamp = tstamp; r1.val = resolution; snd_timer_user_append_to_tqueue(tu, &r1); tu->last_resolution = resolution; append++; } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0) goto __wake; if (ticks == 0) goto __wake; if (tu->qused > 0) { prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1; r = &tu->tqueue[prev]; if (r->event == SNDRV_TIMER_EVENT_TICK) { r->tstamp = tstamp; r->val += ticks; append++; goto __wake; } } r1.event = SNDRV_TIMER_EVENT_TICK; r1.tstamp = tstamp; r1.val = ticks; snd_timer_user_append_to_tqueue(tu, &r1); append++; __wake: spin_unlock(&tu->qlock); if (append == 0) return; kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); } Commit Message: ALSA: timer: Fix leak in events via snd_timer_user_tinterrupt 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_tinterrupt(struct snd_timer_instance *timeri, unsigned long resolution, unsigned long ticks) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread *r, r1; struct timespec tstamp; int prev, append = 0; memset(&tstamp, 0, sizeof(tstamp)); spin_lock(&tu->qlock); if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) | (1 << SNDRV_TIMER_EVENT_TICK))) == 0) { spin_unlock(&tu->qlock); return; } if (tu->last_resolution != resolution || ticks > 0) { if (timer_tstamp_monotonic) ktime_get_ts(&tstamp); else getnstimeofday(&tstamp); } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) && tu->last_resolution != resolution) { memset(&r1, 0, sizeof(r1)); r1.event = SNDRV_TIMER_EVENT_RESOLUTION; r1.tstamp = tstamp; r1.val = resolution; snd_timer_user_append_to_tqueue(tu, &r1); tu->last_resolution = resolution; append++; } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0) goto __wake; if (ticks == 0) goto __wake; if (tu->qused > 0) { prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1; r = &tu->tqueue[prev]; if (r->event == SNDRV_TIMER_EVENT_TICK) { r->tstamp = tstamp; r->val += ticks; append++; goto __wake; } } r1.event = SNDRV_TIMER_EVENT_TICK; r1.tstamp = tstamp; r1.val = ticks; snd_timer_user_append_to_tqueue(tu, &r1); append++; __wake: spin_unlock(&tu->qlock); if (append == 0) return; kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); }
167,236
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 try_read_command(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if (c->protocol == negotiating_prot || c->transport == udp_transport) { if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; } else { c->protocol = ascii_prot; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } } if (c->protocol == binary_prot) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_string(c, "SERVER_ERROR out of memory"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } } else { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) return 0; cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); } return 1; } Commit Message: Issue 102: Piping null to the server will crash it CWE ID: CWE-20
static int try_read_command(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if (c->protocol == negotiating_prot || c->transport == udp_transport) { if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; } else { c->protocol = ascii_prot; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } } if (c->protocol == binary_prot) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_string(c, "SERVER_ERROR out of memory"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } } else { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (strcmp(ptr, "get ") && strcmp(ptr, "gets ")) { conn_set_state(c, conn_closing); return 1; } } return 0; } cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); } return 1; }
169,875
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr); close(sk); return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static int tap_if_down(const char *devname) { struct ifreq ifr; int sk; sk = socket(AF_INET, SOCK_DGRAM, 0); if (sk < 0) return -1; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, devname, IF_NAMESIZE - 1); ifr.ifr_flags &= ~IFF_UP; TEMP_FAILURE_RETRY(ioctl(sk, SIOCSIFFLAGS, (caddr_t) &ifr)); close(sk); return 0; }
173,448
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SpeechSynthesisLibrary* CrosLibrary::GetSpeechSynthesisLibrary() { return speech_synthesis_lib_.GetDefaultImpl(use_stub_impl_); } Commit Message: chromeos: Replace copy-and-pasted code with macros. This replaces a bunch of duplicated-per-library cros function definitions and comments. BUG=none TEST=built it Review URL: http://codereview.chromium.org/6086007 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-189
SpeechSynthesisLibrary* CrosLibrary::GetSpeechSynthesisLibrary() {
170,630
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void FrameSelection::MoveCaretSelection(const IntPoint& point) { DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); Element* const editable = ComputeVisibleSelectionInDOMTree().RootEditableElement(); if (!editable) return; const VisiblePosition position = VisiblePositionForContentsPoint(point, GetFrame()); SelectionInDOMTree::Builder builder; builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional()); builder.SetIsHandleVisible(true); if (position.IsNotNull()) builder.Collapse(position.ToPositionWithAffinity()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(SetSelectionBy::kUser) .Build()); } Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate| since handle visibility is used only for setting |FrameSelection|, hence it is a redundant member variable of |SelectionTemplate|. Bug: 742093 Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e Reviewed-on: https://chromium-review.googlesource.com/595389 Commit-Queue: Yoshifumi Inoue <[email protected]> Reviewed-by: Xiaocheng Hu <[email protected]> Reviewed-by: Kent Tamura <[email protected]> Cr-Commit-Position: refs/heads/master@{#491660} CWE ID: CWE-119
void FrameSelection::MoveCaretSelection(const IntPoint& point) { DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); Element* const editable = ComputeVisibleSelectionInDOMTree().RootEditableElement(); if (!editable) return; const VisiblePosition position = VisiblePositionForContentsPoint(point, GetFrame()); SelectionInDOMTree::Builder builder; builder.SetIsDirectional(GetSelectionInDOMTree().IsDirectional()); if (position.IsNotNull()) builder.Collapse(position.ToPositionWithAffinity()); SetSelection(builder.Build(), SetSelectionData::Builder() .SetShouldCloseTyping(true) .SetShouldClearTypingStyle(true) .SetSetSelectionBy(SetSelectionBy::kUser) .SetShouldShowHandle(true) .Build()); }
171,756
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: px_crypt_des(const char *key, const char *setting) { int i; uint32 count, salt, l, r0, r1, keybuf[2]; char *p; uint8 *q; static char output[21]; if (!des_initialised) des_init(); /* * Copy the key, shifting each character up by one bit and padding with * zeros. */ q = (uint8 *) keybuf; while (q - (uint8 *) keybuf - 8) { if ((*q++ = *key << 1)) key++; } if (des_setkey((char *) keybuf)) #ifndef DISABLE_XDES if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: setting - underscore, 4 bytes of count, 4 bytes of * salt key - unlimited characters */ for (i = 1, count = 0L; i < 5; i++) count |= ascii_to_bin(setting[i]) << (i - 1) * 6; for (i = 5, salt = 0L; i < 9; i++) salt |= ascii_to_bin(setting[i]) << (i - 5) * 6; while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((char *) keybuf, (char *) keybuf, 0L, 1)) return (NULL); /* * And XOR with the next 8 characters of the key. */ q = (uint8 *) keybuf; while (q - (uint8 *) keybuf - 8 && *key) *q++ ^= *key++ << 1; if (des_setkey((char *) keybuf)) return (NULL); } strncpy(output, setting, 9); /* * Double check that we weren't given a short setting. If we were, the * above code will probably have created weird values for count and * salt, but we don't really care. Just make sure the output string * doesn't have an extra NUL in it. */ output[9] = '\0'; p = output + strlen(output); } else #endif /* !DISABLE_XDES */ { /* * "old"-style: setting - 2 bytes of salt key - up to 8 characters */ count = 25; salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); output[0] = setting[0]; /* * If the encrypted password that the salt was extracted from is only * 1 character long, the salt will be corrupted. We need to ensure * that the output string doesn't have an extra NUL in it! */ output[1] = setting[1] ? setting[1] : output[0]; p = output + 2; } setup_salt(salt); /* * Do it. */ if (do_des(0L, 0L, &r0, &r1, count)) return (NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = _crypt_a64[(l >> 18) & 0x3f]; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = _crypt_a64[(l >> 18) & 0x3f]; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; l = r1 << 2; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; *p = 0; return (output); } Commit Message: CWE ID: CWE-310
px_crypt_des(const char *key, const char *setting) { int i; uint32 count, salt, l, r0, r1, keybuf[2]; char *p; uint8 *q; static char output[21]; if (!des_initialised) des_init(); /* * Copy the key, shifting each character up by one bit and padding with * zeros. */ q = (uint8 *) keybuf; while (q - (uint8 *) keybuf - 8) { *q++ = *key << 1; if (*key != '\0') key++; } if (des_setkey((char *) keybuf)) #ifndef DISABLE_XDES if (*setting == _PASSWORD_EFMT1) { /* * "new"-style: setting - underscore, 4 bytes of count, 4 bytes of * salt key - unlimited characters */ for (i = 1, count = 0L; i < 5; i++) count |= ascii_to_bin(setting[i]) << (i - 1) * 6; for (i = 5, salt = 0L; i < 9; i++) salt |= ascii_to_bin(setting[i]) << (i - 5) * 6; while (*key) { /* * Encrypt the key with itself. */ if (des_cipher((char *) keybuf, (char *) keybuf, 0L, 1)) return (NULL); /* * And XOR with the next 8 characters of the key. */ q = (uint8 *) keybuf; while (q - (uint8 *) keybuf - 8 && *key) *q++ ^= *key++ << 1; if (des_setkey((char *) keybuf)) return (NULL); } strncpy(output, setting, 9); /* * Double check that we weren't given a short setting. If we were, the * above code will probably have created weird values for count and * salt, but we don't really care. Just make sure the output string * doesn't have an extra NUL in it. */ output[9] = '\0'; p = output + strlen(output); } else #endif /* !DISABLE_XDES */ { /* * "old"-style: setting - 2 bytes of salt key - up to 8 characters */ count = 25; salt = (ascii_to_bin(setting[1]) << 6) | ascii_to_bin(setting[0]); output[0] = setting[0]; /* * If the encrypted password that the salt was extracted from is only * 1 character long, the salt will be corrupted. We need to ensure * that the output string doesn't have an extra NUL in it! */ output[1] = setting[1] ? setting[1] : output[0]; p = output + 2; } setup_salt(salt); /* * Do it. */ if (do_des(0L, 0L, &r0, &r1, count)) return (NULL); /* * Now encode the result... */ l = (r0 >> 8); *p++ = _crypt_a64[(l >> 18) & 0x3f]; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; l = (r0 << 16) | ((r1 >> 16) & 0xffff); *p++ = _crypt_a64[(l >> 18) & 0x3f]; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; l = r1 << 2; *p++ = _crypt_a64[(l >> 12) & 0x3f]; *p++ = _crypt_a64[(l >> 6) & 0x3f]; *p++ = _crypt_a64[l & 0x3f]; *p = 0; return (output); }
165,027
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 readpng2_init(mainprog_info *mainprog_ptr) { png_structp png_ptr; /* note: temporary variables! */ png_infop info_ptr; /* could also replace libpng warning-handler (final NULL), but no need: */ png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, mainprog_ptr, readpng2_error_handler, readpng2_warning_handler); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function, unless an alternate error handler was installed-- * but compatible error handlers must either use longjmp() themselves * (as in this program) or exit immediately, so here we are: */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED /* prepare the reader to ignore all recognized chunks whose data won't be * used, i.e., all chunks recognized by libpng except for IHDR, PLTE, IDAT, * IEND, tRNS, bKGD, gAMA, and sRGB (small performance improvement) */ { /* These byte strings were copied from png.h. If a future version * of readpng2.c recognizes more chunks, add them to this list. */ static PNG_CONST png_byte chunks_to_process[] = { 98, 75, 71, 68, '\0', /* bKGD */ 103, 65, 77, 65, '\0', /* gAMA */ 115, 82, 71, 66, '\0', /* sRGB */ }; /* Ignore all chunks except for IHDR, PLTE, tRNS, IDAT, and IEND */ png_set_keep_unknown_chunks(png_ptr, -1 /* PNG_HANDLE_CHUNK_NEVER */, NULL, -1); /* But do not ignore chunks in the "chunks_to_process" list */ png_set_keep_unknown_chunks(png_ptr, 0 /* PNG_HANDLE_CHUNK_AS_DEFAULT */, chunks_to_process, sizeof(chunks_to_process)/5); } #endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */ /* instead of doing png_init_io() here, now we set up our callback * functions for progressive decoding */ png_set_progressive_read_fn(png_ptr, mainprog_ptr, readpng2_info_callback, readpng2_row_callback, readpng2_end_callback); /* make sure we save our pointers for use in readpng2_decode_data() */ mainprog_ptr->png_ptr = png_ptr; mainprog_ptr->info_ptr = info_ptr; /* and that's all there is to initialization */ return 0; } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
int readpng2_init(mainprog_info *mainprog_ptr) { png_structp png_ptr; /* note: temporary variables! */ png_infop info_ptr; /* could also replace libpng warning-handler (final NULL), but no need: */ png_ptr = png_create_read_struct(png_get_libpng_ver(NULL), mainprog_ptr, readpng2_error_handler, readpng2_warning_handler); if (!png_ptr) return 4; /* out of memory */ info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, NULL, NULL); return 4; /* out of memory */ } /* we could create a second info struct here (end_info), but it's only * useful if we want to keep pre- and post-IDAT chunk info separated * (mainly for PNG-aware image editors and converters) */ /* setjmp() must be called in every function that calls a PNG-reading * libpng function, unless an alternate error handler was installed-- * but compatible error handlers must either use longjmp() themselves * (as in this program) or exit immediately, so here we are: */ if (setjmp(mainprog_ptr->jmpbuf)) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return 2; } #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED /* prepare the reader to ignore all recognized chunks whose data won't be * used, i.e., all chunks recognized by libpng except for IHDR, PLTE, IDAT, * IEND, tRNS, bKGD, gAMA, and sRGB (small performance improvement) */ { /* These byte strings were copied from png.h. If a future version * of readpng2.c recognizes more chunks, add them to this list. */ static PNG_CONST png_byte chunks_to_process[] = { 98, 75, 71, 68, '\0', /* bKGD */ 103, 65, 77, 65, '\0', /* gAMA */ 115, 82, 71, 66, '\0', /* sRGB */ }; /* Ignore all chunks except for IHDR, PLTE, tRNS, IDAT, and IEND */ png_set_keep_unknown_chunks(png_ptr, -1 /* PNG_HANDLE_CHUNK_NEVER */, NULL, -1); /* But do not ignore chunks in the "chunks_to_process" list */ png_set_keep_unknown_chunks(png_ptr, 0 /* PNG_HANDLE_CHUNK_AS_DEFAULT */, chunks_to_process, sizeof(chunks_to_process)/5); } #endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */ /* instead of doing png_init_io() here, now we set up our callback * functions for progressive decoding */ png_set_progressive_read_fn(png_ptr, mainprog_ptr, readpng2_info_callback, readpng2_row_callback, readpng2_end_callback); /* make sure we save our pointers for use in readpng2_decode_data() */ mainprog_ptr->png_ptr = png_ptr; mainprog_ptr->info_ptr = info_ptr; /* and that's all there is to initialization */ return 0; }
173,570
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void ext4_end_io_work(struct work_struct *work) { ext4_io_end_t *io = container_of(work, ext4_io_end_t, work); struct inode *inode = io->inode; int ret = 0; mutex_lock(&inode->i_mutex); ret = ext4_end_io_nolock(io); if (ret >= 0) { if (!list_empty(&io->list)) list_del_init(&io->list); ext4_free_io_end(io); } mutex_unlock(&inode->i_mutex); } 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 void ext4_end_io_work(struct work_struct *work) { ext4_io_end_t *io = container_of(work, ext4_io_end_t, work); struct inode *inode = io->inode; struct ext4_inode_info *ei = EXT4_I(inode); unsigned long flags; int ret; mutex_lock(&inode->i_mutex); ret = ext4_end_io_nolock(io); if (ret < 0) { mutex_unlock(&inode->i_mutex); return; } spin_lock_irqsave(&ei->i_completed_io_lock, flags); if (!list_empty(&io->list)) list_del_init(&io->list); spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); mutex_unlock(&inode->i_mutex); ext4_free_io_end(io); }
167,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Camera3Device::createDefaultRequest(int templateId, CameraMetadata *request) { ATRACE_CALL(); ALOGV("%s: for template %d", __FUNCTION__, templateId); Mutex::Autolock il(mInterfaceLock); Mutex::Autolock l(mLock); switch (mStatus) { case STATUS_ERROR: CLOGE("Device has encountered a serious error"); return INVALID_OPERATION; case STATUS_UNINITIALIZED: CLOGE("Device is not initialized!"); return INVALID_OPERATION; case STATUS_UNCONFIGURED: case STATUS_CONFIGURED: case STATUS_ACTIVE: break; default: SET_ERR_L("Unexpected status: %d", mStatus); return INVALID_OPERATION; } if (!mRequestTemplateCache[templateId].isEmpty()) { *request = mRequestTemplateCache[templateId]; return OK; } const camera_metadata_t *rawRequest; ATRACE_BEGIN("camera3->construct_default_request_settings"); rawRequest = mHal3Device->ops->construct_default_request_settings( mHal3Device, templateId); ATRACE_END(); if (rawRequest == NULL) { ALOGI("%s: template %d is not supported on this camera device", __FUNCTION__, templateId); return BAD_VALUE; } *request = rawRequest; mRequestTemplateCache[templateId] = rawRequest; return OK; } Commit Message: Camera3Device: Validate template ID Validate template ID before creating a default request. Bug: 26866110 Bug: 27568958 Change-Id: Ifda457024f1d5c2b1382f189c1a8d5fda852d30d CWE ID: CWE-264
status_t Camera3Device::createDefaultRequest(int templateId, CameraMetadata *request) { ATRACE_CALL(); ALOGV("%s: for template %d", __FUNCTION__, templateId); if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) { android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110", IPCThreadState::self()->getCallingUid(), NULL, 0); return BAD_VALUE; } Mutex::Autolock il(mInterfaceLock); Mutex::Autolock l(mLock); switch (mStatus) { case STATUS_ERROR: CLOGE("Device has encountered a serious error"); return INVALID_OPERATION; case STATUS_UNINITIALIZED: CLOGE("Device is not initialized!"); return INVALID_OPERATION; case STATUS_UNCONFIGURED: case STATUS_CONFIGURED: case STATUS_ACTIVE: break; default: SET_ERR_L("Unexpected status: %d", mStatus); return INVALID_OPERATION; } if (!mRequestTemplateCache[templateId].isEmpty()) { *request = mRequestTemplateCache[templateId]; return OK; } const camera_metadata_t *rawRequest; ATRACE_BEGIN("camera3->construct_default_request_settings"); rawRequest = mHal3Device->ops->construct_default_request_settings( mHal3Device, templateId); ATRACE_END(); if (rawRequest == NULL) { ALOGI("%s: template %d is not supported on this camera device", __FUNCTION__, templateId); return BAD_VALUE; } *request = rawRequest; mRequestTemplateCache[templateId] = rawRequest; return OK; }
173,883
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int sh_num) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; const char *interp = ""; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) == -1) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment 0x%lx", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; interp = (const char *)nbuf; } else interp = "*empty*"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; } Commit Message: Bail out on partial reads, from Alexander Cherepanov CWE ID: CWE-20
dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, size_t size, off_t fsize, int *flags, int sh_num) { Elf32_Phdr ph32; Elf64_Phdr ph64; const char *linking_style = "statically"; const char *interp = ""; unsigned char nbuf[BUFSIZ]; char ibuf[BUFSIZ]; ssize_t bufsize; size_t offset, align, len; if (size != xph_sizeof) { if (file_printf(ms, ", corrupted program header size") == -1) return -1; return 0; } for ( ; num; num--) { if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { file_badread(ms); return -1; } off += size; bufsize = 0; align = 4; /* Things we can determine before we seek */ switch (xph_type) { case PT_DYNAMIC: linking_style = "dynamically"; break; case PT_NOTE: if (sh_num) /* Did this through section headers */ continue; if (((align = xph_align) & 0x80000000UL) != 0 || align < 4) { if (file_printf(ms, ", invalid note alignment 0x%lx", (unsigned long)align) == -1) return -1; align = 4; } /*FALLTHROUGH*/ case PT_INTERP: len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf); bufsize = pread(fd, nbuf, len, xph_offset); if (bufsize == -1) { file_badread(ms); return -1; } break; default: if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { /* Maybe warn here? */ continue; } break; } /* Things we can determine when we seek */ switch (xph_type) { case PT_INTERP: if (bufsize && nbuf[0]) { nbuf[bufsize - 1] = '\0'; interp = (const char *)nbuf; } else interp = "*empty*"; break; case PT_NOTE: /* * This is a PT_NOTE section; loop through all the notes * in the section. */ offset = 0; for (;;) { if (offset >= (size_t)bufsize) break; offset = donote(ms, nbuf, offset, (size_t)bufsize, clazz, swap, align, flags); if (offset == 0) break; } break; default: break; } } if (file_printf(ms, ", %s linked", linking_style) == -1) return -1; if (interp[0]) if (file_printf(ms, ", interpreter %s", file_printable(ibuf, sizeof(ibuf), interp)) == -1) return -1; return 0; }
166,768
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: fix_transited_encoding(krb5_context context, krb5_kdc_configuration *config, krb5_boolean check_policy, const TransitedEncoding *tr, EncTicketPart *et, const char *client_realm, const char *server_realm, const char *tgt_realm) { krb5_error_code ret = 0; char **realms, **tmp; unsigned int num_realms; size_t i; switch (tr->tr_type) { case DOMAIN_X500_COMPRESS: break; case 0: /* * Allow empty content of type 0 because that is was Microsoft * generates in their TGT. */ if (tr->contents.length == 0) break; kdc_log(context, config, 0, "Transited type 0 with non empty content"); return KRB5KDC_ERR_TRTYPE_NOSUPP; default: kdc_log(context, config, 0, "Unknown transited type: %u", tr->tr_type); return KRB5KDC_ERR_TRTYPE_NOSUPP; } ret = krb5_domain_x500_decode(context, tr->contents, &realms, &num_realms, client_realm, server_realm); if(ret){ krb5_warn(context, ret, "Decoding transited encoding"); return ret; } if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) { /* not us, so add the previous realm to transited set */ if (num_realms + 1 > UINT_MAX/sizeof(*realms)) { ret = ERANGE; goto free_realms; } tmp = realloc(realms, (num_realms + 1) * sizeof(*realms)); if(tmp == NULL){ ret = ENOMEM; goto free_realms; } realms = tmp; realms[num_realms] = strdup(tgt_realm); if(realms[num_realms] == NULL){ ret = ENOMEM; goto free_realms; } num_realms++; } if(num_realms == 0) { if(strcmp(client_realm, server_realm)) kdc_log(context, config, 0, "cross-realm %s -> %s", client_realm, server_realm); } else { size_t l = 0; char *rs; for(i = 0; i < num_realms; i++) l += strlen(realms[i]) + 2; rs = malloc(l); if(rs != NULL) { *rs = '\0'; for(i = 0; i < num_realms; i++) { if(i > 0) strlcat(rs, ", ", l); strlcat(rs, realms[i], l); } kdc_log(context, config, 0, "cross-realm %s -> %s via [%s]", client_realm, server_realm, rs); free(rs); } } if(check_policy) { ret = krb5_check_transited(context, client_realm, server_realm, realms, num_realms, NULL); if(ret) { krb5_warn(context, ret, "cross-realm %s -> %s", client_realm, server_realm); goto free_realms; } et->flags.transited_policy_checked = 1; } et->transited.tr_type = DOMAIN_X500_COMPRESS; ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents); if(ret) krb5_warn(context, ret, "Encoding transited encoding"); free_realms: for(i = 0; i < num_realms; i++) free(realms[i]); free(realms); return ret; } Commit Message: Fix transit path validation CVE-2017-6594 Commit f469fc6 (2010-10-02) inadvertently caused the previous hop realm to not be added to the transit path of issued tickets. This may, in some cases, enable bypass of capath policy in Heimdal versions 1.5 through 7.2. Note, this may break sites that rely on the bug. With the bug some incomplete [capaths] worked, that should not have. These may now break authentication in some cross-realm configurations. CWE ID: CWE-295
fix_transited_encoding(krb5_context context, krb5_kdc_configuration *config, krb5_boolean check_policy, const TransitedEncoding *tr, EncTicketPart *et, const char *client_realm, const char *server_realm, const char *tgt_realm) { krb5_error_code ret = 0; char **realms, **tmp; unsigned int num_realms; size_t i; switch (tr->tr_type) { case DOMAIN_X500_COMPRESS: break; case 0: /* * Allow empty content of type 0 because that is was Microsoft * generates in their TGT. */ if (tr->contents.length == 0) break; kdc_log(context, config, 0, "Transited type 0 with non empty content"); return KRB5KDC_ERR_TRTYPE_NOSUPP; default: kdc_log(context, config, 0, "Unknown transited type: %u", tr->tr_type); return KRB5KDC_ERR_TRTYPE_NOSUPP; } ret = krb5_domain_x500_decode(context, tr->contents, &realms, &num_realms, client_realm, server_realm); if(ret){ krb5_warn(context, ret, "Decoding transited encoding"); return ret; } /* * If the realm of the presented tgt is neither the client nor the server * realm, it is a transit realm and must be added to transited set. */ if(strcmp(client_realm, tgt_realm) && strcmp(server_realm, tgt_realm)) { if (num_realms + 1 > UINT_MAX/sizeof(*realms)) { ret = ERANGE; goto free_realms; } tmp = realloc(realms, (num_realms + 1) * sizeof(*realms)); if(tmp == NULL){ ret = ENOMEM; goto free_realms; } realms = tmp; realms[num_realms] = strdup(tgt_realm); if(realms[num_realms] == NULL){ ret = ENOMEM; goto free_realms; } num_realms++; } if(num_realms == 0) { if(strcmp(client_realm, server_realm)) kdc_log(context, config, 0, "cross-realm %s -> %s", client_realm, server_realm); } else { size_t l = 0; char *rs; for(i = 0; i < num_realms; i++) l += strlen(realms[i]) + 2; rs = malloc(l); if(rs != NULL) { *rs = '\0'; for(i = 0; i < num_realms; i++) { if(i > 0) strlcat(rs, ", ", l); strlcat(rs, realms[i], l); } kdc_log(context, config, 0, "cross-realm %s -> %s via [%s]", client_realm, server_realm, rs); free(rs); } } if(check_policy) { ret = krb5_check_transited(context, client_realm, server_realm, realms, num_realms, NULL); if(ret) { krb5_warn(context, ret, "cross-realm %s -> %s", client_realm, server_realm); goto free_realms; } et->flags.transited_policy_checked = 1; } et->transited.tr_type = DOMAIN_X500_COMPRESS; ret = krb5_domain_x500_encode(realms, num_realms, &et->transited.contents); if(ret) krb5_warn(context, ret, "Encoding transited encoding"); free_realms: for(i = 0; i < num_realms; i++) free(realms[i]); free(realms); return ret; }
168,325
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SeekHead::Entry* SeekHead::GetEntry(int idx) const { if (idx < 0) return 0; if (idx >= m_entry_count) return 0; return m_entries + idx; } 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 SeekHead::Entry* SeekHead::GetEntry(int idx) const
174,317
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) { struct ip_options *sopt; unsigned char *sptr, *dptr; int soffset, doffset; int optlen; __be32 daddr; memset(dopt, 0, sizeof(struct ip_options)); sopt = &(IPCB(skb)->opt); if (sopt->optlen == 0) { dopt->optlen = 0; return 0; } sptr = skb_network_header(skb); dptr = dopt->__data; daddr = skb_rtable(skb)->rt_spec_dst; if (sopt->rr) { optlen = sptr[sopt->rr+1]; soffset = sptr[sopt->rr+2]; dopt->rr = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->rr, optlen); if (sopt->rr_needaddr && soffset <= optlen) { if (soffset + 3 > optlen) return -EINVAL; dptr[2] = soffset + 4; dopt->rr_needaddr = 1; } dptr += optlen; dopt->optlen += optlen; } if (sopt->ts) { optlen = sptr[sopt->ts+1]; soffset = sptr[sopt->ts+2]; dopt->ts = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->ts, optlen); if (soffset <= optlen) { if (sopt->ts_needaddr) { if (soffset + 3 > optlen) return -EINVAL; dopt->ts_needaddr = 1; soffset += 4; } if (sopt->ts_needtime) { if (soffset + 3 > optlen) return -EINVAL; if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) { dopt->ts_needtime = 1; soffset += 4; } else { dopt->ts_needtime = 0; if (soffset + 7 <= optlen) { __be32 addr; memcpy(&addr, dptr+soffset-1, 4); if (inet_addr_type(dev_net(skb_dst(skb)->dev), addr) != RTN_UNICAST) { dopt->ts_needtime = 1; soffset += 8; } } } } dptr[2] = soffset; } dptr += optlen; dopt->optlen += optlen; } if (sopt->srr) { unsigned char * start = sptr+sopt->srr; __be32 faddr; optlen = start[1]; soffset = start[2]; doffset = 0; if (soffset > optlen) soffset = optlen + 1; soffset -= 4; if (soffset > 3) { memcpy(&faddr, &start[soffset-1], 4); for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4) memcpy(&dptr[doffset-1], &start[soffset-1], 4); /* * RFC1812 requires to fix illegal source routes. */ if (memcmp(&ip_hdr(skb)->saddr, &start[soffset + 3], 4) == 0) doffset -= 4; } if (doffset > 3) { memcpy(&start[doffset-1], &daddr, 4); dopt->faddr = faddr; dptr[0] = start[0]; dptr[1] = doffset+3; dptr[2] = 4; dptr += doffset+3; dopt->srr = dopt->optlen + sizeof(struct iphdr); dopt->optlen += doffset+3; dopt->is_strictroute = sopt->is_strictroute; } } if (sopt->cipso) { optlen = sptr[sopt->cipso+1]; dopt->cipso = dopt->optlen+sizeof(struct iphdr); memcpy(dptr, sptr+sopt->cipso, optlen); dptr += optlen; dopt->optlen += optlen; } while (dopt->optlen & 3) { *dptr++ = IPOPT_END; dopt->optlen++; } return 0; } Commit Message: inet: add RCU protection to inet->opt We lack proper synchronization to manipulate inet->opt ip_options Problem is ip_make_skb() calls ip_setup_cork() and ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options), without any protection against another thread manipulating inet->opt. Another thread can change inet->opt pointer and free old one under us. Use RCU to protect inet->opt (changed to inet->inet_opt). Instead of handling atomic refcounts, just copy ip_options when necessary, to avoid cache line dirtying. We cant insert an rcu_head in struct ip_options since its included in skb->cb[], so this patch is large because I had to introduce a new ip_options_rcu structure. Signed-off-by: Eric Dumazet <[email protected]> Cc: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-362
int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) int ip_options_echo(struct ip_options *dopt, struct sk_buff *skb) { const struct ip_options *sopt; unsigned char *sptr, *dptr; int soffset, doffset; int optlen; __be32 daddr; memset(dopt, 0, sizeof(struct ip_options)); sopt = &(IPCB(skb)->opt); if (sopt->optlen == 0) return 0; sptr = skb_network_header(skb); dptr = dopt->__data; daddr = skb_rtable(skb)->rt_spec_dst; if (sopt->rr) { optlen = sptr[sopt->rr+1]; soffset = sptr[sopt->rr+2]; dopt->rr = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->rr, optlen); if (sopt->rr_needaddr && soffset <= optlen) { if (soffset + 3 > optlen) return -EINVAL; dptr[2] = soffset + 4; dopt->rr_needaddr = 1; } dptr += optlen; dopt->optlen += optlen; } if (sopt->ts) { optlen = sptr[sopt->ts+1]; soffset = sptr[sopt->ts+2]; dopt->ts = dopt->optlen + sizeof(struct iphdr); memcpy(dptr, sptr+sopt->ts, optlen); if (soffset <= optlen) { if (sopt->ts_needaddr) { if (soffset + 3 > optlen) return -EINVAL; dopt->ts_needaddr = 1; soffset += 4; } if (sopt->ts_needtime) { if (soffset + 3 > optlen) return -EINVAL; if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) { dopt->ts_needtime = 1; soffset += 4; } else { dopt->ts_needtime = 0; if (soffset + 7 <= optlen) { __be32 addr; memcpy(&addr, dptr+soffset-1, 4); if (inet_addr_type(dev_net(skb_dst(skb)->dev), addr) != RTN_UNICAST) { dopt->ts_needtime = 1; soffset += 8; } } } } dptr[2] = soffset; } dptr += optlen; dopt->optlen += optlen; } if (sopt->srr) { unsigned char *start = sptr+sopt->srr; __be32 faddr; optlen = start[1]; soffset = start[2]; doffset = 0; if (soffset > optlen) soffset = optlen + 1; soffset -= 4; if (soffset > 3) { memcpy(&faddr, &start[soffset-1], 4); for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4) memcpy(&dptr[doffset-1], &start[soffset-1], 4); /* * RFC1812 requires to fix illegal source routes. */ if (memcmp(&ip_hdr(skb)->saddr, &start[soffset + 3], 4) == 0) doffset -= 4; } if (doffset > 3) { memcpy(&start[doffset-1], &daddr, 4); dopt->faddr = faddr; dptr[0] = start[0]; dptr[1] = doffset+3; dptr[2] = 4; dptr += doffset+3; dopt->srr = dopt->optlen + sizeof(struct iphdr); dopt->optlen += doffset+3; dopt->is_strictroute = sopt->is_strictroute; } } if (sopt->cipso) { optlen = sptr[sopt->cipso+1]; dopt->cipso = dopt->optlen+sizeof(struct iphdr); memcpy(dptr, sptr+sopt->cipso, optlen); dptr += optlen; dopt->optlen += optlen; } while (dopt->optlen & 3) { *dptr++ = IPOPT_END; dopt->optlen++; } return 0; }
165,557
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 Segment::AppendCluster(Cluster* pCluster) { assert(pCluster); assert(pCluster->m_index >= 0); const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); const long idx = pCluster->m_index; assert(idx == m_clusterCount); if (count >= size) { const long n = (size <= 0) ? 2048 : 2*size; Cluster** const qq = new Cluster*[n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; } if (m_clusterPreloadCount > 0) { assert(m_clusters); Cluster** const p = m_clusters + m_clusterCount; assert(*p); assert((*p)->m_index < 0); Cluster** q = p + m_clusterPreloadCount; assert(q < (m_clusters + size)); for (;;) { Cluster** const qq = q - 1; assert((*qq)->m_index < 0); *q = *qq; q = qq; if (q == p) break; } } m_clusters[idx] = pCluster; ++m_clusterCount; } 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
void Segment::AppendCluster(Cluster* pCluster) const long count = m_clusterCount + m_clusterPreloadCount; long& size = m_clusterSize; assert(size >= count); const long idx = pCluster->m_index; assert(idx == m_clusterCount); if (count >= size) { const long n = (size <= 0) ? 2048 : 2 * size; Cluster** const qq = new Cluster* [n]; Cluster** q = qq; Cluster** p = m_clusters; Cluster** const pp = p + count; while (p != pp) *q++ = *p++; delete[] m_clusters; m_clusters = qq; size = n; }
174,237
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 nested_vmx_exit_handled(struct kvm_vcpu *vcpu) { u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO); struct vcpu_vmx *vmx = to_vmx(vcpu); struct vmcs12 *vmcs12 = get_vmcs12(vcpu); u32 exit_reason = vmx->exit_reason; trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, vmcs_readl(EXIT_QUALIFICATION), vmx->idt_vectoring_info, intr_info, vmcs_read32(VM_EXIT_INTR_ERROR_CODE), KVM_ISA_VMX); if (vmx->nested.nested_run_pending) return false; if (unlikely(vmx->fail)) { pr_info_ratelimited("%s failed vm entry %x\n", __func__, vmcs_read32(VM_INSTRUCTION_ERROR)); return true; } switch (exit_reason) { case EXIT_REASON_EXCEPTION_NMI: if (!is_exception(intr_info)) return false; else if (is_page_fault(intr_info)) return enable_ept; else if (is_no_device(intr_info) && !(vmcs12->guest_cr0 & X86_CR0_TS)) return false; else if (is_debug(intr_info) && vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) return false; else if (is_breakpoint(intr_info) && vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) return false; return vmcs12->exception_bitmap & (1u << (intr_info & INTR_INFO_VECTOR_MASK)); case EXIT_REASON_EXTERNAL_INTERRUPT: return false; case EXIT_REASON_TRIPLE_FAULT: return true; case EXIT_REASON_PENDING_INTERRUPT: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING); case EXIT_REASON_NMI_WINDOW: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING); case EXIT_REASON_TASK_SWITCH: return true; case EXIT_REASON_CPUID: if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa) return false; return true; case EXIT_REASON_HLT: return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING); case EXIT_REASON_INVD: return true; case EXIT_REASON_INVLPG: return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING); case EXIT_REASON_RDPMC: return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING); case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP: return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING); case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR: case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD: case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID: /* * VMX instructions trap unconditionally. This allows L1 to * emulate them for its L2 guest, i.e., allows 3-level nesting! */ return true; case EXIT_REASON_CR_ACCESS: return nested_vmx_exit_handled_cr(vcpu, vmcs12); case EXIT_REASON_DR_ACCESS: return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING); case EXIT_REASON_IO_INSTRUCTION: return nested_vmx_exit_handled_io(vcpu, vmcs12); case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC); case EXIT_REASON_MSR_READ: case EXIT_REASON_MSR_WRITE: return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason); case EXIT_REASON_INVALID_STATE: return true; case EXIT_REASON_MWAIT_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING); case EXIT_REASON_MONITOR_TRAP_FLAG: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG); case EXIT_REASON_MONITOR_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING); case EXIT_REASON_PAUSE_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) || nested_cpu_has2(vmcs12, SECONDARY_EXEC_PAUSE_LOOP_EXITING); case EXIT_REASON_MCE_DURING_VMENTRY: return false; case EXIT_REASON_TPR_BELOW_THRESHOLD: return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW); case EXIT_REASON_APIC_ACCESS: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES); case EXIT_REASON_APIC_WRITE: case EXIT_REASON_EOI_INDUCED: /* apic_write and eoi_induced should exit unconditionally. */ return true; case EXIT_REASON_EPT_VIOLATION: /* * L0 always deals with the EPT violation. If nested EPT is * used, and the nested mmu code discovers that the address is * missing in the guest EPT table (EPT12), the EPT violation * will be injected with nested_ept_inject_page_fault() */ return false; case EXIT_REASON_EPT_MISCONFIG: /* * L2 never uses directly L1's EPT, but rather L0's own EPT * table (shadow on EPT) or a merged EPT table that L0 built * (EPT on EPT). So any problems with the structure of the * table is L0's fault. */ return false; case EXIT_REASON_WBINVD: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING); case EXIT_REASON_XSETBV: return true; case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS: /* * This should never happen, since it is not possible to * set XSS to a non-zero value---neither in L1 nor in L2. * If if it were, XSS would have to be checked against * the XSS exit bitmap in vmcs12. */ return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES); case EXIT_REASON_PREEMPTION_TIMER: return false; default: return true; } } Commit Message: kvm: nVMX: Allow L1 to intercept software exceptions (#BP and #OF) When L2 exits to L0 due to "exception or NMI", software exceptions (#BP and #OF) for which L1 has requested an intercept should be handled by L1 rather than L0. Previously, only hardware exceptions were forwarded to L1. Signed-off-by: Jim Mattson <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-388
static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) { u32 intr_info = vmcs_read32(VM_EXIT_INTR_INFO); struct vcpu_vmx *vmx = to_vmx(vcpu); struct vmcs12 *vmcs12 = get_vmcs12(vcpu); u32 exit_reason = vmx->exit_reason; trace_kvm_nested_vmexit(kvm_rip_read(vcpu), exit_reason, vmcs_readl(EXIT_QUALIFICATION), vmx->idt_vectoring_info, intr_info, vmcs_read32(VM_EXIT_INTR_ERROR_CODE), KVM_ISA_VMX); if (vmx->nested.nested_run_pending) return false; if (unlikely(vmx->fail)) { pr_info_ratelimited("%s failed vm entry %x\n", __func__, vmcs_read32(VM_INSTRUCTION_ERROR)); return true; } switch (exit_reason) { case EXIT_REASON_EXCEPTION_NMI: if (is_nmi(intr_info)) return false; else if (is_page_fault(intr_info)) return enable_ept; else if (is_no_device(intr_info) && !(vmcs12->guest_cr0 & X86_CR0_TS)) return false; else if (is_debug(intr_info) && vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) return false; else if (is_breakpoint(intr_info) && vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP) return false; return vmcs12->exception_bitmap & (1u << (intr_info & INTR_INFO_VECTOR_MASK)); case EXIT_REASON_EXTERNAL_INTERRUPT: return false; case EXIT_REASON_TRIPLE_FAULT: return true; case EXIT_REASON_PENDING_INTERRUPT: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_INTR_PENDING); case EXIT_REASON_NMI_WINDOW: return nested_cpu_has(vmcs12, CPU_BASED_VIRTUAL_NMI_PENDING); case EXIT_REASON_TASK_SWITCH: return true; case EXIT_REASON_CPUID: if (kvm_register_read(vcpu, VCPU_REGS_RAX) == 0xa) return false; return true; case EXIT_REASON_HLT: return nested_cpu_has(vmcs12, CPU_BASED_HLT_EXITING); case EXIT_REASON_INVD: return true; case EXIT_REASON_INVLPG: return nested_cpu_has(vmcs12, CPU_BASED_INVLPG_EXITING); case EXIT_REASON_RDPMC: return nested_cpu_has(vmcs12, CPU_BASED_RDPMC_EXITING); case EXIT_REASON_RDTSC: case EXIT_REASON_RDTSCP: return nested_cpu_has(vmcs12, CPU_BASED_RDTSC_EXITING); case EXIT_REASON_VMCALL: case EXIT_REASON_VMCLEAR: case EXIT_REASON_VMLAUNCH: case EXIT_REASON_VMPTRLD: case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: case EXIT_REASON_INVEPT: case EXIT_REASON_INVVPID: /* * VMX instructions trap unconditionally. This allows L1 to * emulate them for its L2 guest, i.e., allows 3-level nesting! */ return true; case EXIT_REASON_CR_ACCESS: return nested_vmx_exit_handled_cr(vcpu, vmcs12); case EXIT_REASON_DR_ACCESS: return nested_cpu_has(vmcs12, CPU_BASED_MOV_DR_EXITING); case EXIT_REASON_IO_INSTRUCTION: return nested_vmx_exit_handled_io(vcpu, vmcs12); case EXIT_REASON_GDTR_IDTR: case EXIT_REASON_LDTR_TR: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_DESC); case EXIT_REASON_MSR_READ: case EXIT_REASON_MSR_WRITE: return nested_vmx_exit_handled_msr(vcpu, vmcs12, exit_reason); case EXIT_REASON_INVALID_STATE: return true; case EXIT_REASON_MWAIT_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MWAIT_EXITING); case EXIT_REASON_MONITOR_TRAP_FLAG: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_TRAP_FLAG); case EXIT_REASON_MONITOR_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_MONITOR_EXITING); case EXIT_REASON_PAUSE_INSTRUCTION: return nested_cpu_has(vmcs12, CPU_BASED_PAUSE_EXITING) || nested_cpu_has2(vmcs12, SECONDARY_EXEC_PAUSE_LOOP_EXITING); case EXIT_REASON_MCE_DURING_VMENTRY: return false; case EXIT_REASON_TPR_BELOW_THRESHOLD: return nested_cpu_has(vmcs12, CPU_BASED_TPR_SHADOW); case EXIT_REASON_APIC_ACCESS: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES); case EXIT_REASON_APIC_WRITE: case EXIT_REASON_EOI_INDUCED: /* apic_write and eoi_induced should exit unconditionally. */ return true; case EXIT_REASON_EPT_VIOLATION: /* * L0 always deals with the EPT violation. If nested EPT is * used, and the nested mmu code discovers that the address is * missing in the guest EPT table (EPT12), the EPT violation * will be injected with nested_ept_inject_page_fault() */ return false; case EXIT_REASON_EPT_MISCONFIG: /* * L2 never uses directly L1's EPT, but rather L0's own EPT * table (shadow on EPT) or a merged EPT table that L0 built * (EPT on EPT). So any problems with the structure of the * table is L0's fault. */ return false; case EXIT_REASON_WBINVD: return nested_cpu_has2(vmcs12, SECONDARY_EXEC_WBINVD_EXITING); case EXIT_REASON_XSETBV: return true; case EXIT_REASON_XSAVES: case EXIT_REASON_XRSTORS: /* * This should never happen, since it is not possible to * set XSS to a non-zero value---neither in L1 nor in L2. * If if it were, XSS would have to be checked against * the XSS exit bitmap in vmcs12. */ return nested_cpu_has2(vmcs12, SECONDARY_EXEC_XSAVES); case EXIT_REASON_PREEMPTION_TIMER: return false; default: return true; } }
166,856
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: return ((iova < mem->iova) || ((iova + length) > (mem->iova + mem->length))) ? -EFAULT : 0; default: return -EFAULT; } } Commit Message: IB/rxe: Fix mem_check_range integer overflow Update the range check to avoid integer-overflow in edge case. Resolves CVE 2016-8636. Signed-off-by: Eyal Itkin <[email protected]> Signed-off-by: Dan Carpenter <[email protected]> Reviewed-by: Leon Romanovsky <[email protected]> Signed-off-by: Doug Ledford <[email protected]> CWE ID: CWE-190
int mem_check_range(struct rxe_mem *mem, u64 iova, size_t length) { switch (mem->type) { case RXE_MEM_TYPE_DMA: return 0; case RXE_MEM_TYPE_MR: case RXE_MEM_TYPE_FMR: if (iova < mem->iova || length > mem->length || iova > mem->iova + mem->length - length) return -EFAULT; return 0; default: return -EFAULT; } }
168,773
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 parse_content_range(URLContext *h, const char *p) { HTTPContext *s = h->priv_data; const char *slash; if (!strncmp(p, "bytes ", 6)) { p += 6; s->off = strtoll(p, NULL, 10); if ((slash = strchr(p, '/')) && strlen(slash) > 0) s->filesize = strtoll(slash + 1, NULL, 10); } if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647)) h->is_streamed = 0; /* we _can_ in fact seek */ } Commit Message: http: make length/offset-related variables unsigned. Fixes #5992, reported and found by Paul Cher <[email protected]>. CWE ID: CWE-119
static void parse_content_range(URLContext *h, const char *p) { HTTPContext *s = h->priv_data; const char *slash; if (!strncmp(p, "bytes ", 6)) { p += 6; s->off = strtoull(p, NULL, 10); if ((slash = strchr(p, '/')) && strlen(slash) > 0) s->filesize = strtoull(slash + 1, NULL, 10); } if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647)) h->is_streamed = 0; /* we _can_ in fact seek */ }
168,503
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_data(void *opaque, uint8_t *buf, int buf_size) { struct playlist *v = opaque; HLSContext *c = v->parent->priv_data; int ret, i; int just_opened = 0; restart: if (!v->needed) return AVERROR_EOF; if (!v->input) { int64_t reload_interval; struct segment *seg; /* Check that the playlist is still needed before opening a new * segment. */ if (v->ctx && v->ctx->nb_streams) { v->needed = 0; for (i = 0; i < v->n_main_streams; i++) { if (v->main_streams[i]->discard < AVDISCARD_ALL) { v->needed = 1; break; } } } if (!v->needed) { av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n", v->index); return AVERROR_EOF; } /* If this is a live stream and the reload interval has elapsed since * the last playlist reload, reload the playlists now. */ reload_interval = default_reload_interval(v); reload: if (!v->finished && av_gettime_relative() - v->last_load_time >= reload_interval) { if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) { av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n", v->index); return ret; } /* If we need to reload the playlist again below (if * there's still no more segments), switch to a reload * interval of half the target duration. */ reload_interval = v->target_duration / 2; } if (v->cur_seq_no < v->start_seq_no) { av_log(NULL, AV_LOG_WARNING, "skipping %d segments ahead, expired from playlists\n", v->start_seq_no - v->cur_seq_no); v->cur_seq_no = v->start_seq_no; } if (v->cur_seq_no >= v->start_seq_no + v->n_segments) { if (v->finished) return AVERROR_EOF; while (av_gettime_relative() - v->last_load_time < reload_interval) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_usleep(100*1000); } /* Enough time has elapsed since the last reload */ goto reload; } seg = current_segment(v); /* load/update Media Initialization Section, if any */ ret = update_init_section(v, seg); if (ret) return ret; ret = open_input(c, v, seg); if (ret < 0) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n", v->index); v->cur_seq_no += 1; goto reload; } just_opened = 1; } if (v->init_sec_buf_read_offset < v->init_sec_data_len) { /* Push init section out first before first actual segment */ int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size); memcpy(buf, v->init_sec_buf, copy_size); v->init_sec_buf_read_offset += copy_size; return copy_size; } ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL); if (ret > 0) { if (just_opened && v->is_id3_timestamped != 0) { /* Intercept ID3 tags here, elementary audio streams are required * to convey timestamps using them in the beginning of each segment. */ intercept_id3(v, buf, buf_size, &ret); } return ret; } ff_format_io_close(v->parent, &v->input); v->cur_seq_no++; c->cur_seq_no = v->cur_seq_no; goto restart; } Commit Message: avformat/hls: Fix DoS due to infinite loop Fixes: loop.m3u The default max iteration count of 1000 is arbitrary and ideas for a better solution are welcome Found-by: Xiaohei and Wangchu from Alibaba Security Team Previous version reviewed-by: Steven Liu <[email protected]> Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-835
static int read_data(void *opaque, uint8_t *buf, int buf_size) { struct playlist *v = opaque; HLSContext *c = v->parent->priv_data; int ret, i; int just_opened = 0; int reload_count = 0; restart: if (!v->needed) return AVERROR_EOF; if (!v->input) { int64_t reload_interval; struct segment *seg; /* Check that the playlist is still needed before opening a new * segment. */ if (v->ctx && v->ctx->nb_streams) { v->needed = 0; for (i = 0; i < v->n_main_streams; i++) { if (v->main_streams[i]->discard < AVDISCARD_ALL) { v->needed = 1; break; } } } if (!v->needed) { av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n", v->index); return AVERROR_EOF; } /* If this is a live stream and the reload interval has elapsed since * the last playlist reload, reload the playlists now. */ reload_interval = default_reload_interval(v); reload: reload_count++; if (reload_count > c->max_reload) return AVERROR_EOF; if (!v->finished && av_gettime_relative() - v->last_load_time >= reload_interval) { if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) { av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n", v->index); return ret; } /* If we need to reload the playlist again below (if * there's still no more segments), switch to a reload * interval of half the target duration. */ reload_interval = v->target_duration / 2; } if (v->cur_seq_no < v->start_seq_no) { av_log(NULL, AV_LOG_WARNING, "skipping %d segments ahead, expired from playlists\n", v->start_seq_no - v->cur_seq_no); v->cur_seq_no = v->start_seq_no; } if (v->cur_seq_no >= v->start_seq_no + v->n_segments) { if (v->finished) return AVERROR_EOF; while (av_gettime_relative() - v->last_load_time < reload_interval) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_usleep(100*1000); } /* Enough time has elapsed since the last reload */ goto reload; } seg = current_segment(v); /* load/update Media Initialization Section, if any */ ret = update_init_section(v, seg); if (ret) return ret; ret = open_input(c, v, seg); if (ret < 0) { if (ff_check_interrupt(c->interrupt_callback)) return AVERROR_EXIT; av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n", v->index); v->cur_seq_no += 1; goto reload; } just_opened = 1; } if (v->init_sec_buf_read_offset < v->init_sec_data_len) { /* Push init section out first before first actual segment */ int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size); memcpy(buf, v->init_sec_buf, copy_size); v->init_sec_buf_read_offset += copy_size; return copy_size; } ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL); if (ret > 0) { if (just_opened && v->is_id3_timestamped != 0) { /* Intercept ID3 tags here, elementary audio streams are required * to convey timestamps using them in the beginning of each segment. */ intercept_id3(v, buf, buf_size, &ret); } return ret; } ff_format_io_close(v->parent, &v->input); v->cur_seq_no++; c->cur_seq_no = v->cur_seq_no; goto restart; }
167,774
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (CheckMemoryOverflow(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); } Commit Message: Suspend exception processing if there are too many exceptions CWE ID: CWE-119
MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; if (HeapOverflowSanityCheck(count,quantum) != MagickFalse) return((void *) NULL); memory=NULL; alignment=CACHE_LINE_SIZE; size=count*quantum; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); }
168,542
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TokenExitsSVG(const CompactHTMLToken& token) { return DeprecatedEqualIgnoringCase(token.Data(), SVGNames::foreignObjectTag.LocalName()); } Commit Message: HTML parser: Fix "HTML integration point" implementation in HTMLTreeBuilderSimulator. HTMLTreeBuilderSimulator assumed only <foreignObject> as an HTML integration point. This CL adds <annotation-xml>, <desc>, and SVG <title>. Bug: 805924 Change-Id: I6793d9163d4c6bc8bf0790415baedddaac7a1fc2 Reviewed-on: https://chromium-review.googlesource.com/964038 Commit-Queue: Kent Tamura <[email protected]> Reviewed-by: Kouhei Ueno <[email protected]> Cr-Commit-Position: refs/heads/master@{#543634} CWE ID: CWE-79
static bool TokenExitsSVG(const CompactHTMLToken& token) {
173,255
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { LOG(WARNING) << "IBus connection is recovered."; g_return_if_fail(user_data); InputMethodStatusConnection* self = static_cast<InputMethodStatusConnection*>(user_data); self->MaybeRestoreConnections(); } Commit Message: Remove use of libcros from InputMethodLibrary. BUG=chromium-os:16238 TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before. Review URL: http://codereview.chromium.org/7003086 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) { void IBusBusConnected(IBusBus* bus) { LOG(WARNING) << "IBus connection is recovered."; MaybeRestoreConnections(); }
170,536
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } pid_t child = fork(); if (child < 0) errExit("fork"); if (child == 0) { drop_privs(0); int rv = copy_file(src, dest); if (rv) fprintf(stderr, "Warning: cannot transfer .Xauthority in private home directory\n"); else { fs_logger2("clone", dest); } _exit(0); } waitpid(child, NULL, 0); if (chown(dest, getuid(), getgid()) < 0) errExit("chown"); if (chmod(dest, S_IRUSR | S_IWUSR) < 0) errExit("chmod"); unlink(src); } Commit Message: security fix CWE ID: CWE-269
static void copy_xauthority(void) { char *src = RUN_XAUTHORITY_FILE ; char *dest; if (asprintf(&dest, "%s/.Xauthority", cfg.homedir) == -1) errExit("asprintf"); if (is_link(dest)) { fprintf(stderr, "Error: %s is a symbolic link\n", dest); exit(1); } copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user fs_logger2("clone", dest); unlink(src); }
170,097
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: v8::MaybeLocal<v8::Array> V8Debugger::internalProperties(v8::Local<v8::Context> context, v8::Local<v8::Value> value) { v8::Local<v8::Array> properties; if (!v8::Debug::GetInternalProperties(m_isolate, value).ToLocal(&properties)) return v8::MaybeLocal<v8::Array>(); if (value->IsFunction()) { v8::Local<v8::Function> function = value.As<v8::Function>(); v8::Local<v8::Value> location = functionLocation(context, function); if (location->IsObject()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[FunctionLocation]]")); properties->Set(properties->Length(), location); } if (function->IsGeneratorFunction()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[IsGenerator]]")); properties->Set(properties->Length(), v8::True(m_isolate)); } } if (!enabled()) return properties; if (value->IsMap() || value->IsWeakMap() || value->IsSet() || value->IsWeakSet() || value->IsSetIterator() || value->IsMapIterator()) { v8::Local<v8::Value> entries = collectionEntries(context, v8::Local<v8::Object>::Cast(value)); if (entries->IsArray()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Entries]]")); properties->Set(properties->Length(), entries); } } if (value->IsGeneratorObject()) { v8::Local<v8::Value> location = generatorObjectLocation(v8::Local<v8::Object>::Cast(value)); if (location->IsObject()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[GeneratorLocation]]")); properties->Set(properties->Length(), location); } } if (value->IsFunction()) { v8::Local<v8::Function> function = value.As<v8::Function>(); v8::Local<v8::Value> boundFunction = function->GetBoundFunction(); v8::Local<v8::Value> scopes; if (boundFunction->IsUndefined() && functionScopes(function).ToLocal(&scopes)) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Scopes]]")); properties->Set(properties->Length(), scopes); } } return properties; } Commit Message: [DevTools] Copy objects from debugger context to inspected context properly. BUG=637594 Review-Url: https://codereview.chromium.org/2253643002 Cr-Commit-Position: refs/heads/master@{#412436} CWE ID: CWE-79
v8::MaybeLocal<v8::Array> V8Debugger::internalProperties(v8::Local<v8::Context> context, v8::Local<v8::Value> value) { v8::Local<v8::Array> properties; if (!v8::Debug::GetInternalProperties(m_isolate, value).ToLocal(&properties)) return v8::MaybeLocal<v8::Array>(); if (value->IsFunction()) { v8::Local<v8::Function> function = value.As<v8::Function>(); v8::Local<v8::Value> location = functionLocation(context, function); if (location->IsObject()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[FunctionLocation]]")); properties->Set(properties->Length(), location); } if (function->IsGeneratorFunction()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[IsGenerator]]")); properties->Set(properties->Length(), v8::True(m_isolate)); } } if (!enabled()) return properties; if (value->IsMap() || value->IsWeakMap() || value->IsSet() || value->IsWeakSet() || value->IsSetIterator() || value->IsMapIterator()) { v8::Local<v8::Value> entries = collectionEntries(context, v8::Local<v8::Object>::Cast(value)); if (entries->IsArray()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Entries]]")); properties->Set(properties->Length(), entries); } } if (value->IsGeneratorObject()) { v8::Local<v8::Value> location = generatorObjectLocation(context, v8::Local<v8::Object>::Cast(value)); if (location->IsObject()) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[GeneratorLocation]]")); properties->Set(properties->Length(), location); } } if (value->IsFunction()) { v8::Local<v8::Function> function = value.As<v8::Function>(); v8::Local<v8::Value> boundFunction = function->GetBoundFunction(); v8::Local<v8::Value> scopes; if (boundFunction->IsUndefined() && functionScopes(context, function).ToLocal(&scopes)) { properties->Set(properties->Length(), toV8StringInternalized(m_isolate, "[[Scopes]]")); properties->Set(properties->Length(), scopes); } } return properties; }
172,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: l2tp_q931_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { print_16bits_val(ndo, (const uint16_t *)dat); ND_PRINT((ndo, ", %02x", dat[2])); if (length > 3) { ND_PRINT((ndo, " ")); print_string(ndo, dat+3, length-3); } } 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_q931_cc_print(netdissect_options *ndo, const u_char *dat, u_int length) { if (length < 3) { ND_PRINT((ndo, "AVP too short")); return; } print_16bits_val(ndo, (const uint16_t *)dat); ND_PRINT((ndo, ", %02x", dat[2])); dat += 3; length -= 3; if (length != 0) { ND_PRINT((ndo, " ")); print_string(ndo, dat, length); } }
167,901
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FileBrowserHandlerCustomBindings::GetEntryURL( const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK(args.Length() == 1); CHECK(args[0]->IsObject()); const blink::WebURL& url = blink::WebDOMFileSystem::createFileSystemURL(args[0]); args.GetReturnValue().Set(v8_helpers::ToV8StringUnsafe( args.GetIsolate(), url.string().utf8().c_str())); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
void FileBrowserHandlerCustomBindings::GetEntryURL( void FileBrowserHandlerCustomBindings::GetExternalFileEntryCallback( const v8::FunctionCallbackInfo<v8::Value>& args) { GetExternalFileEntry(args, context()); }
173,272
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE SoftVideoDecoderOMXComponent::getConfig( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexConfigCommonOutputCrop: { OMX_CONFIG_RECTTYPE *rectParams = (OMX_CONFIG_RECTTYPE *)params; if (rectParams->nPortIndex != kOutputPortIndex) { return OMX_ErrorUndefined; } rectParams->nLeft = mCropLeft; rectParams->nTop = mCropTop; rectParams->nWidth = mCropWidth; rectParams->nHeight = mCropHeight; return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } } Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access Bug: 27207275 Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d CWE ID: CWE-119
OMX_ERRORTYPE SoftVideoDecoderOMXComponent::getConfig( OMX_INDEXTYPE index, OMX_PTR params) { switch (index) { case OMX_IndexConfigCommonOutputCrop: { OMX_CONFIG_RECTTYPE *rectParams = (OMX_CONFIG_RECTTYPE *)params; if (!isValidOMXParam(rectParams)) { return OMX_ErrorBadParameter; } if (rectParams->nPortIndex != kOutputPortIndex) { return OMX_ErrorUndefined; } rectParams->nLeft = mCropLeft; rectParams->nTop = mCropTop; rectParams->nWidth = mCropWidth; rectParams->nHeight = mCropHeight; return OMX_ErrorNone; } default: return OMX_ErrorUnsupportedIndex; } }
174,224
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: const Block* BlockGroup::GetBlock() const { return &m_block; } Commit Message: libwebm: Pull from upstream Rolling mkvparser from upstream. Primarily for fixing a bug on parsing failures with certain Opus WebM files. Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae The diff is so huge because there were some style clean ups upstream. But it was ensured that there were no breaking changes when the style clean ups was done upstream. Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039 CWE ID: CWE-119
const Block* BlockGroup::GetBlock() const
174,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: void ProcessHeap::Init() { total_allocated_space_ = 0; total_allocated_object_size_ = 0; total_marked_object_size_ = 0; GCInfoTable::Init(); base::SamplingHeapProfiler::SetHooksInstallCallback([]() { HeapAllocHooks::SetAllocationHook(&BlinkGCAllocHook); HeapAllocHooks::SetFreeHook(&BlinkGCFreeHook); }); } Commit Message: [oilpan] Fix GCInfoTable for multiple threads Previously, grow and access from different threads could lead to a race on the table backing; see bug. - Rework the table to work on an existing reservation. - Commit upon growing, avoiding any copies. Drive-by: Fix over-allocation of table. Bug: chromium:841280 Change-Id: I329cb6f40091e14e8c05334ba1104a9440c31d43 Reviewed-on: https://chromium-review.googlesource.com/1061525 Commit-Queue: Michael Lippautz <[email protected]> Reviewed-by: Kentaro Hara <[email protected]> Cr-Commit-Position: refs/heads/master@{#560434} CWE ID: CWE-362
void ProcessHeap::Init() { total_allocated_space_ = 0; total_allocated_object_size_ = 0; total_marked_object_size_ = 0; base::SamplingHeapProfiler::SetHooksInstallCallback([]() { HeapAllocHooks::SetAllocationHook(&BlinkGCAllocHook); HeapAllocHooks::SetFreeHook(&BlinkGCFreeHook); }); }
173,142
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t SampleIterator::seekTo(uint32_t sampleIndex) { ALOGV("seekTo(%d)", sampleIndex); if (sampleIndex >= mTable->mNumSampleSizes) { return ERROR_END_OF_STREAM; } if (mTable->mSampleToChunkOffset < 0 || mTable->mChunkOffsetOffset < 0 || mTable->mSampleSizeOffset < 0 || mTable->mTimeToSampleCount == 0) { return ERROR_MALFORMED; } if (mInitialized && mCurrentSampleIndex == sampleIndex) { return OK; } if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) { reset(); } if (sampleIndex >= mStopChunkSampleIndex) { status_t err; if ((err = findChunkRange(sampleIndex)) != OK) { ALOGE("findChunkRange failed"); return err; } } CHECK(sampleIndex < mStopChunkSampleIndex); if (mSamplesPerChunk == 0) { ALOGE("b/22802344"); return ERROR_MALFORMED; } uint32_t chunk = (sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk + mFirstChunk; if (!mInitialized || chunk != mCurrentChunkIndex) { mCurrentChunkIndex = chunk; status_t err; if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) { ALOGE("getChunkOffset return error"); return err; } mCurrentChunkSampleSizes.clear(); uint32_t firstChunkSampleIndex = mFirstChunkSampleIndex + mSamplesPerChunk * (mCurrentChunkIndex - mFirstChunk); for (uint32_t i = 0; i < mSamplesPerChunk; ++i) { size_t sampleSize; if ((err = getSampleSizeDirect( firstChunkSampleIndex + i, &sampleSize)) != OK) { ALOGE("getSampleSizeDirect return error"); return err; } mCurrentChunkSampleSizes.push(sampleSize); } } uint32_t chunkRelativeSampleIndex = (sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk; mCurrentSampleOffset = mCurrentChunkOffset; for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) { mCurrentSampleOffset += mCurrentChunkSampleSizes[i]; } mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex]; if (sampleIndex < mTTSSampleIndex) { mTimeToSampleIndex = 0; mTTSSampleIndex = 0; mTTSSampleTime = 0; mTTSCount = 0; mTTSDuration = 0; } status_t err; if ((err = findSampleTimeAndDuration( sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) { ALOGE("findSampleTime return error"); return err; } mCurrentSampleIndex = sampleIndex; mInitialized = true; return OK; } Commit Message: SampleIterator: clear members on seekTo error Bug: 31091777 Change-Id: Iddf99d0011961d0fd3d755e57db4365b6a6a1193 (cherry picked from commit 03237ce0f9584c98ccda76c2474a4ae84c763f5b) CWE ID: CWE-200
status_t SampleIterator::seekTo(uint32_t sampleIndex) { ALOGV("seekTo(%d)", sampleIndex); if (sampleIndex >= mTable->mNumSampleSizes) { return ERROR_END_OF_STREAM; } if (mTable->mSampleToChunkOffset < 0 || mTable->mChunkOffsetOffset < 0 || mTable->mSampleSizeOffset < 0 || mTable->mTimeToSampleCount == 0) { return ERROR_MALFORMED; } if (mInitialized && mCurrentSampleIndex == sampleIndex) { return OK; } if (!mInitialized || sampleIndex < mFirstChunkSampleIndex) { reset(); } if (sampleIndex >= mStopChunkSampleIndex) { status_t err; if ((err = findChunkRange(sampleIndex)) != OK) { ALOGE("findChunkRange failed"); return err; } } CHECK(sampleIndex < mStopChunkSampleIndex); if (mSamplesPerChunk == 0) { ALOGE("b/22802344"); return ERROR_MALFORMED; } uint32_t chunk = (sampleIndex - mFirstChunkSampleIndex) / mSamplesPerChunk + mFirstChunk; if (!mInitialized || chunk != mCurrentChunkIndex) { status_t err; if ((err = getChunkOffset(chunk, &mCurrentChunkOffset)) != OK) { ALOGE("getChunkOffset return error"); return err; } mCurrentChunkSampleSizes.clear(); uint32_t firstChunkSampleIndex = mFirstChunkSampleIndex + mSamplesPerChunk * (chunk - mFirstChunk); for (uint32_t i = 0; i < mSamplesPerChunk; ++i) { size_t sampleSize; if ((err = getSampleSizeDirect( firstChunkSampleIndex + i, &sampleSize)) != OK) { ALOGE("getSampleSizeDirect return error"); mCurrentChunkSampleSizes.clear(); return err; } mCurrentChunkSampleSizes.push(sampleSize); } mCurrentChunkIndex = chunk; } uint32_t chunkRelativeSampleIndex = (sampleIndex - mFirstChunkSampleIndex) % mSamplesPerChunk; mCurrentSampleOffset = mCurrentChunkOffset; for (uint32_t i = 0; i < chunkRelativeSampleIndex; ++i) { mCurrentSampleOffset += mCurrentChunkSampleSizes[i]; } mCurrentSampleSize = mCurrentChunkSampleSizes[chunkRelativeSampleIndex]; if (sampleIndex < mTTSSampleIndex) { mTimeToSampleIndex = 0; mTTSSampleIndex = 0; mTTSSampleTime = 0; mTTSCount = 0; mTTSDuration = 0; } status_t err; if ((err = findSampleTimeAndDuration( sampleIndex, &mCurrentSampleTime, &mCurrentSampleDuration)) != OK) { ALOGE("findSampleTime return error"); return err; } mCurrentSampleIndex = sampleIndex; mInitialized = true; return OK; }
173,378
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: M_bool M_fs_path_ishidden(const char *path, M_fs_info_t *info) { M_list_str_t *path_parts; size_t len; M_bool ret = M_FALSE; (void)info; if (path == NULL || *path == '\0') { return M_FALSE; } /* Hidden. Check if the first character of the last part of the path. Either the file or directory name itself * starts with a '.'. */ path_parts = M_fs_path_componentize_path(path, M_FS_SYSTEM_UNIX); len = M_list_str_len(path_parts); if (len > 0) { if (*M_list_str_at(path_parts, len-1) == '.') { ret = M_TRUE; } } M_list_str_destroy(path_parts); return ret; } Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data. CWE ID: CWE-732
M_bool M_fs_path_ishidden(const char *path, M_fs_info_t *info) { M_list_str_t *path_parts; size_t len; M_bool ret = M_FALSE; (void)info; if (path == NULL || *path == '\0') { return M_FALSE; } /* Hidden. Check if the first character of the last part of the path. Either the file or directory name itself * starts with a '.'. */ path_parts = M_fs_path_componentize_path(path, M_FS_SYSTEM_UNIX); len = M_list_str_len(path_parts); if (len > 0) { if (*M_list_str_at(path_parts, len-1) == '.') { ret = M_TRUE; } } M_list_str_destroy(path_parts); return ret; }
169,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: static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx); } } Commit Message: xen/netback: don't leak pages on failure in xen_netbk_tx_check_gop. Signed-off-by: Matthew Daley <[email protected]> Reviewed-by: Konrad Rzeszutek Wilk <[email protected]> Acked-by: Ian Campbell <[email protected]> Acked-by: Jan Beulich <[email protected]> Signed-off-by: David S. Miller <[email protected]> CWE ID: CWE-399
static void xen_netbk_fill_frags(struct xen_netbk *netbk, struct sk_buff *skb) { struct skb_shared_info *shinfo = skb_shinfo(skb); int nr_frags = shinfo->nr_frags; int i; for (i = 0; i < nr_frags; i++) { skb_frag_t *frag = shinfo->frags + i; struct xen_netif_tx_request *txp; struct page *page; u16 pending_idx; pending_idx = frag_get_pending_idx(frag); txp = &netbk->pending_tx_info[pending_idx].req; page = virt_to_page(idx_to_kaddr(netbk, pending_idx)); __skb_fill_page_desc(skb, i, page, txp->offset, txp->size); skb->len += txp->size; skb->data_len += txp->size; skb->truesize += txp->size; /* Take an extra reference to offset xen_netbk_idx_release */ get_page(netbk->mmap_pages[pending_idx]); xen_netbk_idx_release(netbk, pending_idx, XEN_NETIF_RSP_OKAY); } }
166,167
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr) { /* This function is copied verbatim from plfont.c */ int table_length; int table_offset; ulong format; uint numGlyphs; uint glyph_name_index; const byte *postp; /* post table pointer */ /* guess if the font type is not truetype */ if ( pfont->FontType != ft_TrueType ) { pstr->size = strlen((char*)pstr->data); return 0; } else { return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph); } } Commit Message: CWE ID: CWE-119
xps_true_callback_glyph_name(gs_font *pfont, gs_glyph glyph, gs_const_string *pstr) { /* This function is copied verbatim from plfont.c */ int table_length; int table_offset; ulong format; int numGlyphs; uint glyph_name_index; const byte *postp; /* post table pointer */ if (glyph >= GS_MIN_GLYPH_INDEX) { glyph -= GS_MIN_GLYPH_INDEX; } /* guess if the font type is not truetype */ if ( pfont->FontType != ft_TrueType ) { pstr->size = strlen((char*)pstr->data); return 0; } else { return gs_throw1(-1, "glyph index %lu out of range", (ulong)glyph); } }
164,784
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: std::unique_ptr<HistogramBase> PersistentHistogramAllocator::CreateHistogram( PersistentHistogramData* histogram_data_ptr) { if (!histogram_data_ptr) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_METADATA_POINTER); NOTREACHED(); return nullptr; } if (histogram_data_ptr->histogram_type == SPARSE_HISTOGRAM) { std::unique_ptr<HistogramBase> histogram = SparseHistogram::PersistentCreate(this, histogram_data_ptr->name, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); histogram->SetFlags(histogram_data_ptr->flags); RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS); return histogram; } int32_t histogram_type = histogram_data_ptr->histogram_type; int32_t histogram_flags = histogram_data_ptr->flags; int32_t histogram_minimum = histogram_data_ptr->minimum; int32_t histogram_maximum = histogram_data_ptr->maximum; uint32_t histogram_bucket_count = histogram_data_ptr->bucket_count; uint32_t histogram_ranges_ref = histogram_data_ptr->ranges_ref; uint32_t histogram_ranges_checksum = histogram_data_ptr->ranges_checksum; HistogramBase::Sample* ranges_data = memory_allocator_->GetAsArray<HistogramBase::Sample>( histogram_ranges_ref, kTypeIdRangesArray, PersistentMemoryAllocator::kSizeAny); const uint32_t max_buckets = std::numeric_limits<uint32_t>::max() / sizeof(HistogramBase::Sample); size_t required_bytes = (histogram_bucket_count + 1) * sizeof(HistogramBase::Sample); size_t allocated_bytes = memory_allocator_->GetAllocSize(histogram_ranges_ref); if (!ranges_data || histogram_bucket_count < 2 || histogram_bucket_count >= max_buckets || allocated_bytes < required_bytes) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY); NOTREACHED(); return nullptr; } std::unique_ptr<const BucketRanges> created_ranges = CreateRangesFromData( ranges_data, histogram_ranges_checksum, histogram_bucket_count + 1); if (!created_ranges) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_RANGES_ARRAY); NOTREACHED(); return nullptr; } const BucketRanges* ranges = StatisticsRecorder::RegisterOrDeleteDuplicateRanges( created_ranges.release()); size_t counts_bytes = CalculateRequiredCountsBytes(histogram_bucket_count); PersistentMemoryAllocator::Reference counts_ref = subtle::Acquire_Load(&histogram_data_ptr->counts_ref); if (counts_bytes == 0 || (counts_ref != 0 && memory_allocator_->GetAllocSize(counts_ref) < counts_bytes)) { RecordCreateHistogramResult(CREATE_HISTOGRAM_INVALID_COUNTS_ARRAY); NOTREACHED(); return nullptr; } DelayedPersistentAllocation counts_data(memory_allocator_.get(), &histogram_data_ptr->counts_ref, kTypeIdCountsArray, counts_bytes, 0); DelayedPersistentAllocation logged_data( memory_allocator_.get(), &histogram_data_ptr->counts_ref, kTypeIdCountsArray, counts_bytes, counts_bytes / 2, /*make_iterable=*/false); const char* name = histogram_data_ptr->name; std::unique_ptr<HistogramBase> histogram; switch (histogram_type) { case HISTOGRAM: histogram = Histogram::PersistentCreate( name, histogram_minimum, histogram_maximum, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case LINEAR_HISTOGRAM: histogram = LinearHistogram::PersistentCreate( name, histogram_minimum, histogram_maximum, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case BOOLEAN_HISTOGRAM: histogram = BooleanHistogram::PersistentCreate( name, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case CUSTOM_HISTOGRAM: histogram = CustomHistogram::PersistentCreate( name, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; default: NOTREACHED(); } if (histogram) { DCHECK_EQ(histogram_type, histogram->GetHistogramType()); histogram->SetFlags(histogram_flags); RecordCreateHistogramResult(CREATE_HISTOGRAM_SUCCESS); } else { RecordCreateHistogramResult(CREATE_HISTOGRAM_UNKNOWN_TYPE); } return histogram; } 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
std::unique_ptr<HistogramBase> PersistentHistogramAllocator::CreateHistogram( PersistentHistogramData* histogram_data_ptr) { if (!histogram_data_ptr) { NOTREACHED(); return nullptr; } if (histogram_data_ptr->histogram_type == SPARSE_HISTOGRAM) { std::unique_ptr<HistogramBase> histogram = SparseHistogram::PersistentCreate(this, histogram_data_ptr->name, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); histogram->SetFlags(histogram_data_ptr->flags); return histogram; } int32_t histogram_type = histogram_data_ptr->histogram_type; int32_t histogram_flags = histogram_data_ptr->flags; int32_t histogram_minimum = histogram_data_ptr->minimum; int32_t histogram_maximum = histogram_data_ptr->maximum; uint32_t histogram_bucket_count = histogram_data_ptr->bucket_count; uint32_t histogram_ranges_ref = histogram_data_ptr->ranges_ref; uint32_t histogram_ranges_checksum = histogram_data_ptr->ranges_checksum; HistogramBase::Sample* ranges_data = memory_allocator_->GetAsArray<HistogramBase::Sample>( histogram_ranges_ref, kTypeIdRangesArray, PersistentMemoryAllocator::kSizeAny); const uint32_t max_buckets = std::numeric_limits<uint32_t>::max() / sizeof(HistogramBase::Sample); size_t required_bytes = (histogram_bucket_count + 1) * sizeof(HistogramBase::Sample); size_t allocated_bytes = memory_allocator_->GetAllocSize(histogram_ranges_ref); if (!ranges_data || histogram_bucket_count < 2 || histogram_bucket_count >= max_buckets || allocated_bytes < required_bytes) { NOTREACHED(); return nullptr; } std::unique_ptr<const BucketRanges> created_ranges = CreateRangesFromData( ranges_data, histogram_ranges_checksum, histogram_bucket_count + 1); if (!created_ranges) { NOTREACHED(); return nullptr; } const BucketRanges* ranges = StatisticsRecorder::RegisterOrDeleteDuplicateRanges( created_ranges.release()); size_t counts_bytes = CalculateRequiredCountsBytes(histogram_bucket_count); PersistentMemoryAllocator::Reference counts_ref = subtle::Acquire_Load(&histogram_data_ptr->counts_ref); if (counts_bytes == 0 || (counts_ref != 0 && memory_allocator_->GetAllocSize(counts_ref) < counts_bytes)) { NOTREACHED(); return nullptr; } DelayedPersistentAllocation counts_data(memory_allocator_.get(), &histogram_data_ptr->counts_ref, kTypeIdCountsArray, counts_bytes, 0); DelayedPersistentAllocation logged_data( memory_allocator_.get(), &histogram_data_ptr->counts_ref, kTypeIdCountsArray, counts_bytes, counts_bytes / 2, /*make_iterable=*/false); const char* name = histogram_data_ptr->name; std::unique_ptr<HistogramBase> histogram; switch (histogram_type) { case HISTOGRAM: histogram = Histogram::PersistentCreate( name, histogram_minimum, histogram_maximum, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case LINEAR_HISTOGRAM: histogram = LinearHistogram::PersistentCreate( name, histogram_minimum, histogram_maximum, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case BOOLEAN_HISTOGRAM: histogram = BooleanHistogram::PersistentCreate( name, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; case CUSTOM_HISTOGRAM: histogram = CustomHistogram::PersistentCreate( name, ranges, counts_data, logged_data, &histogram_data_ptr->samples_metadata, &histogram_data_ptr->logged_metadata); DCHECK(histogram); break; default: NOTREACHED(); } if (histogram) { DCHECK_EQ(histogram_type, histogram->GetHistogramType()); histogram->SetFlags(histogram_flags); } return histogram; }
172,132
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count, int preview_request_id) { VLOG(1) << "Print preview request finished with " << expected_pages_count << " pages"; if (!initial_preview_start_time_.is_null()) { UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime", base::TimeTicks::Now() - initial_preview_start_time_); UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial", expected_pages_count); initial_preview_start_time_ = base::TimeTicks(); } base::StringValue ui_identifier(preview_ui_addr_str_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier, ui_preview_request_id); } Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI. BUG=144051 Review URL: https://chromiumcodereview.appspot.com/10870003 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-200
void PrintPreviewUI::OnPreviewDataIsAvailable(int expected_pages_count, int preview_request_id) { VLOG(1) << "Print preview request finished with " << expected_pages_count << " pages"; if (!initial_preview_start_time_.is_null()) { UMA_HISTOGRAM_TIMES("PrintPreview.InitialDisplayTime", base::TimeTicks::Now() - initial_preview_start_time_); UMA_HISTOGRAM_COUNTS("PrintPreview.PageCount.Initial", expected_pages_count); initial_preview_start_time_ = base::TimeTicks(); } base::FundamentalValue ui_identifier(id_); base::FundamentalValue ui_preview_request_id(preview_request_id); web_ui()->CallJavascriptFunction("updatePrintPreview", ui_identifier, ui_preview_request_id); }
170,838
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, rs_ctx ); #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); } Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/556' into mbedtls-2.16-restricted CWE ID: CWE-200
static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else if( f_rng_blind != NULL ) ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, f_rng_blind, p_rng_blind, rs_ctx ); else { mbedtls_hmac_drbg_context *p_rng_blind_det; #if !defined(MBEDTLS_ECP_RESTARTABLE) /* * To avoid reusing rng_ctx and risking incorrect behavior we seed a * second HMAC-DRBG with the same seed. We also apply a label to avoid * reusing the bits of the ephemeral key for blinding and eliminate the * risk that they leak this way. */ const char* blind_label = "BLINDING CONTEXT"; mbedtls_hmac_drbg_context rng_ctx_blind; mbedtls_hmac_drbg_init( &rng_ctx_blind ); p_rng_blind_det = &rng_ctx_blind; mbedtls_hmac_drbg_seed_buf( p_rng_blind_det, md_info, data, 2 * grp_len ); ret = mbedtls_hmac_drbg_update_ret( p_rng_blind_det, (const unsigned char*) blind_label, strlen( blind_label ) ); if( ret != 0 ) { mbedtls_hmac_drbg_free( &rng_ctx_blind ); goto cleanup; } #else /* * In the case of restartable computations we would either need to store * the second RNG in the restart context too or set it up at every * restart. The first option would penalize the correct application of * the function and the second would defeat the purpose of the * restartable feature. * * Therefore in this case we reuse the original RNG. This comes with the * price that the resulting signature might not be a valid deterministic * ECDSA signature with a very low probability (same magnitude as * successfully guessing the private key). However even then it is still * a valid ECDSA signature. */ p_rng_blind_det = p_rng; #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Since the output of the RNGs is always the same for the same key and * message, this limits the efficiency of blinding and leaks information * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL * won't be a valid value for f_rng_blind anymore. Therefore it should * be checked by the caller and this branch and check can be removed. */ ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, mbedtls_hmac_drbg_random, p_rng_blind_det, rs_ctx ); #if !defined(MBEDTLS_ECP_RESTARTABLE) mbedtls_hmac_drbg_free( &rng_ctx_blind ); #endif } #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); }
169,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: void uwbd_start(struct uwb_rc *rc) { rc->uwbd.task = kthread_run(uwbd, rc, "uwbd"); if (rc->uwbd.task == NULL) printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); else rc->uwbd.pid = rc->uwbd.task->pid; } Commit Message: uwb: properly check kthread_run return value uwbd_start() calls kthread_run() and checks that the return value is not NULL. But the return value is not NULL in case kthread_run() fails, it takes the form of ERR_PTR(-EINTR). Use IS_ERR() instead. Also add a check to uwbd_stop(). Signed-off-by: Andrey Konovalov <[email protected]> Cc: stable <[email protected]> Signed-off-by: Greg Kroah-Hartman <[email protected]> CWE ID: CWE-119
void uwbd_start(struct uwb_rc *rc) { struct task_struct *task = kthread_run(uwbd, rc, "uwbd"); if (IS_ERR(task)) { rc->uwbd.task = NULL; printk(KERN_ERR "UWB: Cannot start management daemon; " "UWB won't work\n"); } else { rc->uwbd.task = task; rc->uwbd.pid = rc->uwbd.task->pid; } }
167,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); } 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 ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { bool ServiceWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { if (state_ == WORKER_READY) { if (sessions().size() == 1) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&SetDevToolsAttachedOnIO, context_weak_, version_id_, true)); } session->SetRenderer(worker_process_id_, nullptr); session->AttachToAgent(agent_ptr_); } session->AddHandler(base::WrapUnique(new protocol::InspectorHandler())); session->AddHandler(base::WrapUnique(new protocol::NetworkHandler(GetId()))); session->AddHandler(base::WrapUnique(new protocol::SchemaHandler())); return true; }
173,251
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: int Downmix_Reset(downmix_object_t *pDownmixer, bool init) { return 0; } Commit Message: audio effects: fix heap overflow Check consistency of effect command reply sizes before copying to reply address. Also add null pointer check on reply size. Also remove unused parameter warning. Bug: 21953516. Change-Id: I4cf00c12eaed696af28f3b7613f7e36f47a160c4 (cherry picked from commit 0f714a464d2425afe00d6450535e763131b40844) CWE ID: CWE-119
int Downmix_Reset(downmix_object_t *pDownmixer, bool init) { int Downmix_Reset(downmix_object_t *pDownmixer __unused, bool init __unused) { return 0; }
173,345
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create(); m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<FileEntrySync*>(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
FileEntrySync* DirectoryEntrySync::getFile(const String& path, const Dictionary& options, ExceptionState& exceptionState) { FileSystemFlags flags(options); EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create(); m_fileSystem->getFile(this, path, flags, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous); return static_cast<FileEntrySync*>(helper->getResult(exceptionState)); }
171,418
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size) { static iconv_t icv_utf16_to_local; size_t ibl, obl; char *pin, *pout; if (!icv_utf16_to_local) { icv_utf16_to_local = iconv_open(g_codepage, WINDOWS_CODEPAGE); if (icv_utf16_to_local == (iconv_t) - 1) { logger(Protocol, Error, "rdp_in_unistr(), iconv_open[%s -> %s] fail %p", WINDOWS_CODEPAGE, g_codepage, icv_utf16_to_local); abort(); } } /* Dynamic allocate of destination string if not provided */ if (*string == NULL) { *string = xmalloc(in_len * 2); *str_size = in_len * 2; } ibl = in_len; obl = *str_size - 1; pin = (char *) s->p; pout = *string; if (iconv(icv_utf16_to_local, (char **) &pin, &ibl, &pout, &obl) == (size_t) - 1) { if (errno == E2BIG) { logger(Protocol, Warning, "rdp_in_unistr(), server sent an unexpectedly long string, truncating"); } else { logger(Protocol, Warning, "rdp_in_unistr(), iconv fail, errno %d", errno); free(*string); *string = NULL; *str_size = 0; } abort(); } /* we must update the location of the current STREAM for future reads of s->p */ s->p += in_len; *pout = 0; if (*string) *str_size = pout - *string; } Commit Message: Malicious RDP server security fixes This commit includes fixes for a set of 21 vulnerabilities in rdesktop when a malicious RDP server is used. All vulnerabilities was identified and reported by Eyal Itkin. * Add rdp_protocol_error function that is used in several fixes * Refactor of process_bitmap_updates * Fix possible integer overflow in s_check_rem() on 32bit arch * Fix memory corruption in process_bitmap_data - CVE-2018-8794 * Fix remote code execution in process_bitmap_data - CVE-2018-8795 * Fix remote code execution in process_plane - CVE-2018-8797 * Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175 * Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175 * Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176 * Fix Denial of Service in sec_recv - CVE-2018-20176 * Fix minor information leak in rdpdr_process - CVE-2018-8791 * Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792 * Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793 * Fix Denial of Service in process_bitmap_data - CVE-2018-8796 * Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798 * Fix Denial of Service in process_secondary_order - CVE-2018-8799 * Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800 * Fix major information leak in ui_clip_handle_data - CVE-2018-20174 * Fix memory corruption in rdp_in_unistr - CVE-2018-20177 * Fix Denial of Service in process_demand_active - CVE-2018-20178 * Fix remote code execution in lspci_process - CVE-2018-20179 * Fix remote code execution in rdpsnddbg_process - CVE-2018-20180 * Fix remote code execution in seamless_process - CVE-2018-20181 * Fix remote code execution in seamless_process_line - CVE-2018-20182 CWE ID: CWE-119
rdp_in_unistr(STREAM s, int in_len, char **string, uint32 * str_size) { static iconv_t icv_utf16_to_local; size_t ibl, obl; char *pin, *pout; struct stream packet = *s; if ((in_len < 0) || ((uint32)in_len >= (RD_UINT32_MAX / 2))) { logger(Protocol, Error, "rdp_in_unistr(), length of unicode data is out of bounds."); abort(); } if (!s_check_rem(s, in_len)) { rdp_protocol_error("rdp_in_unistr(), consume of unicode data from stream would overrun", &packet); } if (!icv_utf16_to_local) { icv_utf16_to_local = iconv_open(g_codepage, WINDOWS_CODEPAGE); if (icv_utf16_to_local == (iconv_t) - 1) { logger(Protocol, Error, "rdp_in_unistr(), iconv_open[%s -> %s] fail %p", WINDOWS_CODEPAGE, g_codepage, icv_utf16_to_local); abort(); } } /* Dynamic allocate of destination string if not provided */ if (*string == NULL) { *string = xmalloc(in_len * 2); *str_size = in_len * 2; } ibl = in_len; obl = *str_size - 1; pin = (char *) s->p; pout = *string; if (iconv(icv_utf16_to_local, (char **) &pin, &ibl, &pout, &obl) == (size_t) - 1) { if (errno == E2BIG) { logger(Protocol, Warning, "rdp_in_unistr(), server sent an unexpectedly long string, truncating"); } else { logger(Protocol, Warning, "rdp_in_unistr(), iconv fail, errno %d", errno); free(*string); *string = NULL; *str_size = 0; } abort(); } /* we must update the location of the current STREAM for future reads of s->p */ s->p += in_len; *pout = 0; if (*string) *str_size = pout - *string; }
169,804
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: long mkvparser::UnserializeString(IMkvReader* pReader, long long pos, long long size_, char*& str) { delete[] str; str = NULL; if (size_ >= LONG_MAX) // we need (size+1) chars return E_FILE_FORMAT_INVALID; const long size = static_cast<long>(size_); str = new (std::nothrow) char[size + 1]; if (str == NULL) return -1; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[size] = '\0'; return 0; // success } Commit Message: external/libvpx/libwebm: Update snapshot Update libwebm snapshot. This update contains security fixes from upstream. Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b BUG=23167726 Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207 (cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a) CWE ID: CWE-20
long mkvparser::UnserializeString(IMkvReader* pReader, long long pos, long UnserializeString(IMkvReader* pReader, long long pos, long long size, char*& str) { delete[] str; str = NULL; if (size >= LONG_MAX || size < 0) return E_FILE_FORMAT_INVALID; // +1 for '\0' terminator const long required_size = static_cast<long>(size) + 1; str = SafeArrayAlloc<char>(1, required_size); if (str == NULL) return E_FILE_FORMAT_INVALID; unsigned char* const buf = reinterpret_cast<unsigned char*>(str); const long status = pReader->Read(pos, size, buf); if (status) { delete[] str; str = NULL; return status; } str[required_size - 1] = '\0'; return 0; }
173,867
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 local_socket_close_locked(asocket* s) { D("entered local_socket_close_locked. LS(%d) fd=%d", s->id, s->fd); if (s->peer) { D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd); /* Note: it's important to call shutdown before disconnecting from * the peer, this ensures that remote sockets can still get the id * of the local socket they're connected to, to send a CLOSE() * protocol event. */ if (s->peer->shutdown) { s->peer->shutdown(s->peer); } s->peer->peer = 0; if (s->peer->close == local_socket_close) { local_socket_close_locked(s->peer); } else { s->peer->close(s->peer); } s->peer = 0; } /* If we are already closing, or if there are no ** pending packets, destroy immediately */ if (s->closing || s->has_write_error || s->pkt_first == NULL) { int id = s->id; local_socket_destroy(s); D("LS(%d): closed", id); return; } /* otherwise, put on the closing list */ D("LS(%d): closing", s->id); s->closing = 1; fdevent_del(&s->fde, FDE_READ); remove_socket(s); D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd); insert_local_socket(s, &local_socket_closing_list); CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE); } Commit Message: adb: switch the socket list mutex to a recursive_mutex. sockets.cpp was branching on whether a socket close function was local_socket_close in order to avoid a potential deadlock if the socket list lock was held while closing a peer socket. Bug: http://b/28347842 Change-Id: I5e56f17fa54275284787f0f1dc150d1960256ab3 (cherry picked from commit 9b587dec6d0a57c8fe1083c1c543fbeb163d65fa) CWE ID: CWE-264
static void local_socket_close_locked(asocket* s) { static void local_socket_close(asocket* s) { D("entered local_socket_close. LS(%d) fd=%d", s->id, s->fd); std::lock_guard<std::recursive_mutex> lock(local_socket_list_lock); if (s->peer) { D("LS(%d): closing peer. peer->id=%d peer->fd=%d", s->id, s->peer->id, s->peer->fd); /* Note: it's important to call shutdown before disconnecting from * the peer, this ensures that remote sockets can still get the id * of the local socket they're connected to, to send a CLOSE() * protocol event. */ if (s->peer->shutdown) { s->peer->shutdown(s->peer); } s->peer->peer = nullptr; s->peer->close(s->peer); s->peer = nullptr; } /* If we are already closing, or if there are no ** pending packets, destroy immediately */ if (s->closing || s->has_write_error || s->pkt_first == NULL) { int id = s->id; local_socket_destroy(s); D("LS(%d): closed", id); return; } /* otherwise, put on the closing list */ D("LS(%d): closing", s->id); s->closing = 1; fdevent_del(&s->fde, FDE_READ); remove_socket(s); D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd); insert_local_socket(s, &local_socket_closing_list); CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE); }
174,154
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BlockEntry::GetIndex() const { return m_index; } 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 BlockEntry::GetIndex() const
174,329
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetExternalFileEntry", base::Bind(&FileBrowserHandlerCustomBindings::GetExternalFileEntry, base::Unretained(this))); RouteFunction("GetEntryURL", base::Bind(&FileBrowserHandlerCustomBindings::GetEntryURL, base::Unretained(this))); } Commit Message: [Extensions] Add more bindings access checks BUG=598165 Review URL: https://codereview.chromium.org/1854983002 Cr-Commit-Position: refs/heads/master@{#385282} CWE ID:
FileBrowserHandlerCustomBindings::FileBrowserHandlerCustomBindings( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "GetExternalFileEntry", "fileBrowserHandler", base::Bind( &FileBrowserHandlerCustomBindings::GetExternalFileEntryCallback, base::Unretained(this))); }
173,271
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_tls_close(cib_t * cib) { cib_remote_opaque_t *private = cib->variant_opaque; shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */ shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */ close(private->command.socket); close(private->callback.socket); #ifdef HAVE_GNUTLS_GNUTLS_H if (private->command.encrypted) { gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->command.session)); gnutls_free(private->command.session); gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->callback.session)); gnutls_free(private->callback.session); gnutls_anon_free_client_credentials(anon_cred_c); gnutls_global_deinit(); } #endif return 0; } Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend. CWE ID: CWE-399
cib_tls_close(cib_t * cib) { cib_remote_opaque_t *private = cib->variant_opaque; #ifdef HAVE_GNUTLS_GNUTLS_H if (private->command.encrypted) { if (private->command.session) { gnutls_bye(*(private->command.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->command.session)); gnutls_free(private->command.session); } if (private->callback.session) { gnutls_bye(*(private->callback.session), GNUTLS_SHUT_RDWR); gnutls_deinit(*(private->callback.session)); gnutls_free(private->callback.session); } private->command.session = NULL; private->callback.session = NULL; if (remote_gnutls_credentials_init) { gnutls_anon_free_client_credentials(anon_cred_c); gnutls_global_deinit(); remote_gnutls_credentials_init = FALSE; } } #endif if (private->command.socket) { shutdown(private->command.socket, SHUT_RDWR); /* no more receptions */ close(private->command.socket); } if (private->callback.socket) { shutdown(private->callback.socket, SHUT_RDWR); /* no more receptions */ close(private->callback.socket); } private->command.socket = 0; private->callback.socket = 0; free(private->command.recv_buf); free(private->callback.recv_buf); private->command.recv_buf = NULL; private->callback.recv_buf = NULL; return 0; }
166,155
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); int32_t len; uint8_t command; uint8_t *outbuf; int rc; command = buf[0]; outbuf = (uint8_t *)r->iov.iov_base; DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]); #ifdef DEBUG_SCSI { int i; for (i = 1; i < r->req.cmd.len; i++) { printf(" 0x%02x", buf[i]); } printf("\n"); } #endif switch (command) { case TEST_UNIT_READY: case INQUIRY: case MODE_SENSE: case MODE_SENSE_10: case RESERVE: case RESERVE_10: case RELEASE: case RELEASE_10: case START_STOP: case ALLOW_MEDIUM_REMOVAL: case READ_CAPACITY_10: case READ_TOC: case GET_CONFIGURATION: case SERVICE_ACTION_IN_16: case VERIFY_10: rc = scsi_disk_emulate_command(r, outbuf); if (rc < 0) { return 0; } r->iov.iov_len = rc; break; case SYNCHRONIZE_CACHE: bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH); r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r); if (r->req.aiocb == NULL) { scsi_flush_complete(r, -EIO); } return 0; case READ_6: case READ_10: case READ_12: case READ_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) goto illegal_lba; r->sector = r->req.cmd.lba * s->cluster_size; r->sector_count = len * s->cluster_size; break; case WRITE_6: case WRITE_10: case WRITE_12: case WRITE_16: case WRITE_VERIFY_10: case WRITE_VERIFY_12: case WRITE_VERIFY_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("Write %s(sector %" PRId64 ", count %d)\n", (command & 0xe) == 0xe ? "And Verify " : "", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) goto illegal_lba; r->sector = r->req.cmd.lba * s->cluster_size; r->sector_count = len * s->cluster_size; break; case MODE_SELECT: DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer); /* We don't support mode parameter changes. Allow the mode parameter header + block descriptors only. */ if (r->req.cmd.xfer > 12) { goto fail; } break; case MODE_SELECT_10: DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer); /* We don't support mode parameter changes. Allow the mode parameter header + block descriptors only. */ if (r->req.cmd.xfer > 16) { goto fail; } break; case SEEK_6: case SEEK_10: DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10, r->req.cmd.lba); if (r->req.cmd.lba > s->max_lba) { goto illegal_lba; } break; case WRITE_SAME_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) { goto illegal_lba; } /* * We only support WRITE SAME with the unmap bit set for now. */ if (!(buf[1] & 0x8)) { goto fail; } rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size, len * s->cluster_size); if (rc < 0) { /* XXX: better error code ?*/ goto fail; } break; case REQUEST_SENSE: abort(); default: DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]); scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return 0; fail: scsi_check_condition(r, SENSE_CODE(INVALID_FIELD)); return 0; illegal_lba: scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE)); return 0; } if (r->sector_count == 0 && r->iov.iov_len == 0) { scsi_req_complete(&r->req, GOOD); } len = r->sector_count * 512 + r->iov.iov_len; if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { return -len; } else { if (!r->sector_count) r->sector_count = -1; return len; } } Commit Message: scsi-disk: lazily allocate bounce buffer It will not be needed for reads and writes if the HBA provides a sglist. In addition, this lets scsi-disk refuse commands with an excessive allocation length, as well as limit memory on usual well-behaved guests. Signed-off-by: Paolo Bonzini <[email protected]> Signed-off-by: Kevin Wolf <[email protected]> CWE ID: CWE-119
static int32_t scsi_send_command(SCSIRequest *req, uint8_t *buf) { SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req); SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev); int32_t len; uint8_t command; int rc; command = buf[0]; DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", req->lun, req->tag, buf[0]); #ifdef DEBUG_SCSI { int i; for (i = 1; i < r->req.cmd.len; i++) { printf(" 0x%02x", buf[i]); } printf("\n"); } #endif switch (command) { case TEST_UNIT_READY: case INQUIRY: case MODE_SENSE: case MODE_SENSE_10: case RESERVE: case RESERVE_10: case RELEASE: case RELEASE_10: case START_STOP: case ALLOW_MEDIUM_REMOVAL: case READ_CAPACITY_10: case READ_TOC: case GET_CONFIGURATION: case SERVICE_ACTION_IN_16: case VERIFY_10: rc = scsi_disk_emulate_command(r); if (rc < 0) { return 0; } r->iov.iov_len = rc; break; case SYNCHRONIZE_CACHE: bdrv_acct_start(s->bs, &r->acct, 0, BDRV_ACCT_FLUSH); r->req.aiocb = bdrv_aio_flush(s->bs, scsi_flush_complete, r); if (r->req.aiocb == NULL) { scsi_flush_complete(r, -EIO); } return 0; case READ_6: case READ_10: case READ_12: case READ_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("Read (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) goto illegal_lba; r->sector = r->req.cmd.lba * s->cluster_size; r->sector_count = len * s->cluster_size; break; case WRITE_6: case WRITE_10: case WRITE_12: case WRITE_16: case WRITE_VERIFY_10: case WRITE_VERIFY_12: case WRITE_VERIFY_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("Write %s(sector %" PRId64 ", count %d)\n", (command & 0xe) == 0xe ? "And Verify " : "", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) goto illegal_lba; r->sector = r->req.cmd.lba * s->cluster_size; r->sector_count = len * s->cluster_size; break; case MODE_SELECT: DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer); /* We don't support mode parameter changes. Allow the mode parameter header + block descriptors only. */ if (r->req.cmd.xfer > 12) { goto fail; } break; case MODE_SELECT_10: DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer); /* We don't support mode parameter changes. Allow the mode parameter header + block descriptors only. */ if (r->req.cmd.xfer > 16) { goto fail; } break; case SEEK_6: case SEEK_10: DPRINTF("Seek(%d) (sector %" PRId64 ")\n", command == SEEK_6 ? 6 : 10, r->req.cmd.lba); if (r->req.cmd.lba > s->max_lba) { goto illegal_lba; } break; case WRITE_SAME_16: len = r->req.cmd.xfer / s->qdev.blocksize; DPRINTF("WRITE SAME(16) (sector %" PRId64 ", count %d)\n", r->req.cmd.lba, len); if (r->req.cmd.lba > s->max_lba) { goto illegal_lba; } /* * We only support WRITE SAME with the unmap bit set for now. */ if (!(buf[1] & 0x8)) { goto fail; } rc = bdrv_discard(s->bs, r->req.cmd.lba * s->cluster_size, len * s->cluster_size); if (rc < 0) { /* XXX: better error code ?*/ goto fail; } break; case REQUEST_SENSE: abort(); default: DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]); scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE)); return 0; fail: scsi_check_condition(r, SENSE_CODE(INVALID_FIELD)); return 0; illegal_lba: scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE)); return 0; } if (r->sector_count == 0 && r->iov.iov_len == 0) { scsi_req_complete(&r->req, GOOD); } len = r->sector_count * 512 + r->iov.iov_len; if (r->req.cmd.mode == SCSI_XFER_TO_DEV) { return -len; } else { if (!r->sector_count) r->sector_count = -1; return len; } }
166,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: sf_open_fd (int fd, int mode, SF_INFO *sfinfo, int close_desc) { SF_PRIVATE *psf ; if ((SF_CONTAINER (sfinfo->format)) == SF_FORMAT_SD2) { sf_errno = SFE_SD2_FD_DISALLOWED ; return NULL ; } ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; copy_filename (psf, "") ; psf->file.mode = mode ; psf_set_file (psf, fd) ; psf->is_pipe = psf_is_pipe (psf) ; psf->fileoffset = psf_ftell (psf) ; if (! close_desc) psf->file.do_not_close_descriptor = SF_TRUE ; return psf_open_file (psf, sfinfo) ; } /* sf_open_fd */ Commit Message: src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k. CWE ID: CWE-119
sf_open_fd (int fd, int mode, SF_INFO *sfinfo, int close_desc) { SF_PRIVATE *psf ; if ((SF_CONTAINER (sfinfo->format)) == SF_FORMAT_SD2) { sf_errno = SFE_SD2_FD_DISALLOWED ; return NULL ; } ; if ((psf = psf_allocate ()) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; copy_filename (psf, "") ; psf->file.mode = mode ; psf_set_file (psf, fd) ; psf->is_pipe = psf_is_pipe (psf) ; psf->fileoffset = psf_ftell (psf) ; if (! close_desc) psf->file.do_not_close_descriptor = SF_TRUE ; return psf_open_file (psf, sfinfo) ; } /* sf_open_fd */
170,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: void SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->AddHandler(std::make_unique<protocol::InspectorHandler>()); session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId())); session->AddHandler(std::make_unique<protocol::SchemaHandler>()); session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr); if (state_ == WORKER_READY) session->AttachToAgent(EnsureAgent()); } 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 SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { bool SharedWorkerDevToolsAgentHost::AttachSession(DevToolsSession* session) { session->AddHandler(std::make_unique<protocol::InspectorHandler>()); session->AddHandler(std::make_unique<protocol::NetworkHandler>(GetId())); session->AddHandler(std::make_unique<protocol::SchemaHandler>()); session->SetRenderer(worker_host_ ? worker_host_->process_id() : -1, nullptr); if (state_ == WORKER_READY) session->AttachToAgent(EnsureAgent()); return true; }
173,252
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); } Commit Message: CVE-2017-13005/NFS: Add two bounds checks before fetching data This fixes a buffer over-read discovered by Kamil Frankowicz. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
xid_map_enter(netdissect_options *ndo, const struct sunrpc_msg *rp, const u_char *bp) { const struct ip *ip = NULL; const struct ip6_hdr *ip6 = NULL; struct xid_map_entry *xmep; if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); switch (IP_V((const struct ip *)bp)) { case 4: ip = (const struct ip *)bp; break; case 6: ip6 = (const struct ip6_hdr *)bp; break; default: return (1); } xmep = &xid_map[xid_map_next]; if (++xid_map_next >= XIDMAPSIZE) xid_map_next = 0; UNALIGNED_MEMCPY(&xmep->xid, &rp->rm_xid, sizeof(xmep->xid)); if (ip) { xmep->ipver = 4; UNALIGNED_MEMCPY(&xmep->client, &ip->ip_src, sizeof(ip->ip_src)); UNALIGNED_MEMCPY(&xmep->server, &ip->ip_dst, sizeof(ip->ip_dst)); } else if (ip6) { xmep->ipver = 6; UNALIGNED_MEMCPY(&xmep->client, &ip6->ip6_src, sizeof(ip6->ip6_src)); UNALIGNED_MEMCPY(&xmep->server, &ip6->ip6_dst, sizeof(ip6->ip6_dst)); } if (!ND_TTEST(rp->rm_call.cb_proc)) return (0); xmep->proc = EXTRACT_32BITS(&rp->rm_call.cb_proc); if (!ND_TTEST(rp->rm_call.cb_vers)) return (0); xmep->vers = EXTRACT_32BITS(&rp->rm_call.cb_vers); return (1); }
167,903
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: static inline void VectorClamp3(DDSVector3 *value) { value->x = MinF(1.0f,MaxF(0.0f,value->x)); value->y = MinF(1.0f,MaxF(0.0f,value->y)); value->z = MinF(1.0f,MaxF(0.0f,value->z)); } Commit Message: Added extra EOF check and some minor refactoring. CWE ID: CWE-20
static inline void VectorClamp3(DDSVector3 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); }
168,907
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ static char base_address; xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; xmlDocPtr doc; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } /* * Okay this is ugly but should work, use the NodePtr address * to forge the ID */ if (cur->type != XML_NAMESPACE_DECL) doc = cur->doc; else { xmlNsPtr ns = (xmlNsPtr) cur; if (ns->context != NULL) doc = ns->context; else doc = ctxt->context->doc; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)&base_address); if (val >= 0) { sprintf((char *)str, "idp%ld", val); } else { sprintf((char *)str, "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); } 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
xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ static char base_address; xmlNodePtr cur = NULL; xmlXPathObjectPtr obj = NULL; long val; xmlChar str[30]; if (nargs == 0) { cur = ctxt->context->node; } else if (nargs == 1) { xmlNodeSetPtr nodelist; int i, ret; if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_NODESET)) { ctxt->error = XPATH_INVALID_TYPE; xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid arg expecting a node-set\n"); return; } obj = valuePop(ctxt); nodelist = obj->nodesetval; if ((nodelist == NULL) || (nodelist->nodeNr <= 0)) { xmlXPathFreeObject(obj); valuePush(ctxt, xmlXPathNewCString("")); return; } cur = nodelist->nodeTab[0]; for (i = 1;i < nodelist->nodeNr;i++) { ret = xmlXPathCmpNodes(cur, nodelist->nodeTab[i]); if (ret == -1) cur = nodelist->nodeTab[i]; } } else { xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, "generate-id() : invalid number of args %d\n", nargs); ctxt->error = XPATH_INVALID_ARITY; return; } if (obj) xmlXPathFreeObject(obj); val = (long)((char *)cur - (char *)&base_address); if (val >= 0) { snprintf((char *)str, sizeof(str), "idp%ld", val); } else { snprintf((char *)str, sizeof(str), "idm%ld", -val); } valuePush(ctxt, xmlXPathNewString(str)); }
173,302
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: sp<ABuffer> decodeBase64(const AString &s) { size_t n = s.size(); if ((n % 4) != 0) { return NULL; } size_t padding = 0; if (n >= 1 && s.c_str()[n - 1] == '=') { padding = 1; if (n >= 2 && s.c_str()[n - 2] == '=') { padding = 2; if (n >= 3 && s.c_str()[n - 3] == '=') { padding = 3; } } } size_t outLen = (n / 4) * 3 - padding; sp<ABuffer> buffer = new ABuffer(outLen); uint8_t *out = buffer->data(); if (out == NULL || buffer->size() < outLen) { return NULL; } size_t j = 0; uint32_t accum = 0; for (size_t i = 0; i < n; ++i) { char c = s.c_str()[i]; unsigned value; if (c >= 'A' && c <= 'Z') { value = c - 'A'; } else if (c >= 'a' && c <= 'z') { value = 26 + c - 'a'; } else if (c >= '0' && c <= '9') { value = 52 + c - '0'; } else if (c == '+') { value = 62; } else if (c == '/') { value = 63; } else if (c != '=') { return NULL; } else { if (i < n - padding) { return NULL; } value = 0; } accum = (accum << 6) | value; if (((i + 1) % 4) == 0) { out[j++] = (accum >> 16); if (j < outLen) { out[j++] = (accum >> 8) & 0xff; } if (j < outLen) { out[j++] = accum & 0xff; } accum = 0; } } return buffer; } Commit Message: stagefright: avoid buffer overflow in base64 decoder Bug: 62673128 Change-Id: Id5f04b772aaca3184879bd5bca453ad9e82c7f94 (cherry picked from commit 5e96386ab7a5391185f6b3ed9ea06f3e23ed253b) CWE ID: CWE-119
sp<ABuffer> decodeBase64(const AString &s) { size_t n = s.size(); if ((n % 4) != 0) { return NULL; } size_t padding = 0; if (n >= 1 && s.c_str()[n - 1] == '=') { padding = 1; if (n >= 2 && s.c_str()[n - 2] == '=') { padding = 2; if (n >= 3 && s.c_str()[n - 3] == '=') { padding = 3; } } } size_t outLen = (n / 4) * 3 - padding; sp<ABuffer> buffer = new ABuffer(outLen); uint8_t *out = buffer->data(); if (out == NULL || buffer->size() < outLen) { return NULL; } size_t j = 0; uint32_t accum = 0; for (size_t i = 0; i < n; ++i) { char c = s.c_str()[i]; unsigned value; if (c >= 'A' && c <= 'Z') { value = c - 'A'; } else if (c >= 'a' && c <= 'z') { value = 26 + c - 'a'; } else if (c >= '0' && c <= '9') { value = 52 + c - '0'; } else if (c == '+') { value = 62; } else if (c == '/') { value = 63; } else if (c != '=') { return NULL; } else { if (i < n - padding) { return NULL; } value = 0; } accum = (accum << 6) | value; if (((i + 1) % 4) == 0) { if (j < outLen) { out[j++] = (accum >> 16); } if (j < outLen) { out[j++] = (accum >> 8) & 0xff; } if (j < outLen) { out[j++] = accum & 0xff; } accum = 0; } } return buffer; }
173,996
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 *btif_hh_poll_event_thread(void *arg) { btif_hh_device_t *p_dev = arg; APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd); struct pollfd pfds[1]; int ret; pfds[0].fd = p_dev->fd; pfds[0].events = POLLIN; uhid_set_non_blocking(p_dev->fd); while(p_dev->hh_keep_polling){ ret = poll(pfds, 1, 50); if (ret < 0) { APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno)); break; } if (pfds[0].revents & POLLIN) { APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN"); ret = uhid_event(p_dev); if (ret){ break; } } } p_dev->hh_poll_thread_id = -1; return 0; } Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process Bug: 28885210 Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360 Conflicts: btif/co/bta_hh_co.c btif/src/btif_core.c Merge conflict resolution of ag/1161415 (referencing ag/1164670) - Directly into mnc-mr2-release CWE ID: CWE-284
static void *btif_hh_poll_event_thread(void *arg) { btif_hh_device_t *p_dev = arg; APPL_TRACE_DEBUG("%s: Thread created fd = %d", __FUNCTION__, p_dev->fd); struct pollfd pfds[1]; int ret; pfds[0].fd = p_dev->fd; pfds[0].events = POLLIN; uhid_set_non_blocking(p_dev->fd); while(p_dev->hh_keep_polling){ ret = TEMP_FAILURE_RETRY(poll(pfds, 1, 50)); if (ret < 0) { APPL_TRACE_ERROR("%s: Cannot poll for fds: %s\n", __FUNCTION__, strerror(errno)); break; } if (pfds[0].revents & POLLIN) { APPL_TRACE_DEBUG("btif_hh_poll_event_thread: POLLIN"); ret = uhid_event(p_dev); if (ret){ break; } } } p_dev->hh_poll_thread_id = -1; return 0; }
173,431
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 CoordinatorImpl::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind( &CoordinatorImpl::OnChromeMemoryDumpResponse, base::Unretained(this)); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, base::Unretained(this), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, base::Unretained(this), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, base::Unretained(this), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, base::Unretained(this), request->dump_guid), kHeapDumpTimeout); } FinalizeGlobalMemoryDumpIfAllManagersReplied(); } Commit Message: Fix heap-use-after-free by using weak factory instead of Unretained Bug: 856578 Change-Id: Ifb2a1b7e6c22e1af36e12eedba72427f51d925b9 Reviewed-on: https://chromium-review.googlesource.com/1114617 Reviewed-by: Hector Dearman <[email protected]> Commit-Queue: Hector Dearman <[email protected]> Cr-Commit-Position: refs/heads/master@{#571528} CWE ID: CWE-416
void CoordinatorImpl::PerformNextQueuedGlobalMemoryDump() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); QueuedRequest* request = GetCurrentRequest(); if (request == nullptr) return; std::vector<QueuedRequestDispatcher::ClientInfo> clients; for (const auto& kv : clients_) { auto client_identity = kv.second->identity; const base::ProcessId pid = GetProcessIdForClientIdentity(client_identity); if (pid == base::kNullProcessId) { VLOG(1) << "Couldn't find a PID for client \"" << client_identity.name() << "." << client_identity.instance() << "\""; continue; } clients.emplace_back(kv.second->client.get(), pid, kv.second->process_type); } auto chrome_callback = base::Bind(&CoordinatorImpl::OnChromeMemoryDumpResponse, weak_ptr_factory_.GetWeakPtr()); auto os_callback = base::Bind(&CoordinatorImpl::OnOSMemoryDumpResponse, weak_ptr_factory_.GetWeakPtr(), request->dump_guid); QueuedRequestDispatcher::SetUpAndDispatch(request, clients, chrome_callback, os_callback); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnQueuedRequestTimedOut, weak_ptr_factory_.GetWeakPtr(), request->dump_guid), client_process_timeout_); if (request->args.add_to_trace && heap_profiler_) { request->heap_dump_in_progress = true; bool strip_path_from_mapped_files = base::trace_event::TraceLog::GetInstance() ->GetCurrentTraceConfig() .IsArgumentFilterEnabled(); heap_profiler_->DumpProcessesForTracing( strip_path_from_mapped_files, base::BindRepeating(&CoordinatorImpl::OnDumpProcessesForTracing, weak_ptr_factory_.GetWeakPtr(), request->dump_guid)); base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&CoordinatorImpl::OnHeapDumpTimeOut, weak_ptr_factory_.GetWeakPtr(), request->dump_guid), kHeapDumpTimeout); } FinalizeGlobalMemoryDumpIfAllManagersReplied(); }
173,214
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: LazyBackgroundPageNativeHandler::LazyBackgroundPageNativeHandler( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "IncrementKeepaliveCount", base::Bind(&LazyBackgroundPageNativeHandler::IncrementKeepaliveCount, base::Unretained(this))); RouteFunction( "DecrementKeepaliveCount", base::Bind(&LazyBackgroundPageNativeHandler::DecrementKeepaliveCount, base::Unretained(this))); } Commit Message: [Extensions] Expand bindings access checks BUG=601149 BUG=601073 Review URL: https://codereview.chromium.org/1866103002 Cr-Commit-Position: refs/heads/master@{#387710} CWE ID: CWE-284
LazyBackgroundPageNativeHandler::LazyBackgroundPageNativeHandler( ScriptContext* context) : ObjectBackedNativeHandler(context) { RouteFunction( "IncrementKeepaliveCount", "tts", base::Bind(&LazyBackgroundPageNativeHandler::IncrementKeepaliveCount, base::Unretained(this))); RouteFunction( "DecrementKeepaliveCount", "tts", base::Bind(&LazyBackgroundPageNativeHandler::DecrementKeepaliveCount, base::Unretained(this))); }
172,250
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(base::MakeUnique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); } Commit Message: Replace base::MakeUnique with std::make_unique in net/. base/memory/ptr_util.h includes will be cleaned up later. Bug: 755727 Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434 Reviewed-on: https://chromium-review.googlesource.com/627300 Commit-Queue: Jeremy Roman <[email protected]> Reviewed-by: Daniel Cheng <[email protected]> Reviewed-by: Bence Béky <[email protected]> Cr-Commit-Position: refs/heads/master@{#498123} CWE ID: CWE-311
void ElementsUploadDataStreamTest::FileChangedHelper( const base::FilePath& file_path, const base::Time& time, bool error_expected) { std::vector<std::unique_ptr<UploadElementReader>> element_readers; element_readers.push_back(std::make_unique<UploadFileElementReader>( base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time)); TestCompletionCallback init_callback; std::unique_ptr<UploadDataStream> stream( new ElementsUploadDataStream(std::move(element_readers), 0)); ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()), IsError(ERR_IO_PENDING)); int error_code = init_callback.WaitForResult(); if (error_expected) ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED)); else ASSERT_THAT(error_code, IsOk()); }
173,261
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: nfsd_dispatch(struct svc_rqst *rqstp, __be32 *statp) { struct svc_procedure *proc; kxdrproc_t xdr; __be32 nfserr; __be32 *nfserrp; dprintk("nfsd_dispatch: vers %d proc %d\n", rqstp->rq_vers, rqstp->rq_proc); proc = rqstp->rq_procinfo; /* * Give the xdr decoder a chance to change this if it wants * (necessary in the NFSv4.0 compound case) */ rqstp->rq_cachetype = proc->pc_cachetype; /* Decode arguments */ xdr = proc->pc_decode; if (xdr && !xdr(rqstp, (__be32*)rqstp->rq_arg.head[0].iov_base, rqstp->rq_argp)) { dprintk("nfsd: failed to decode arguments!\n"); *statp = rpc_garbage_args; return 1; } /* Check whether we have this call in the cache. */ switch (nfsd_cache_lookup(rqstp)) { case RC_DROPIT: return 0; case RC_REPLY: return 1; case RC_DOIT:; /* do it */ } /* need to grab the location to store the status, as * nfsv4 does some encoding while processing */ nfserrp = rqstp->rq_res.head[0].iov_base + rqstp->rq_res.head[0].iov_len; rqstp->rq_res.head[0].iov_len += sizeof(__be32); /* Now call the procedure handler, and encode NFS status. */ nfserr = proc->pc_func(rqstp, rqstp->rq_argp, rqstp->rq_resp); nfserr = map_new_errors(rqstp->rq_vers, nfserr); if (nfserr == nfserr_dropit || test_bit(RQ_DROPME, &rqstp->rq_flags)) { dprintk("nfsd: Dropping request; may be revisited later\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); return 0; } if (rqstp->rq_proc != 0) *nfserrp++ = nfserr; /* Encode result. * For NFSv2, additional info is never returned in case of an error. */ if (!(nfserr && rqstp->rq_vers == 2)) { xdr = proc->pc_encode; if (xdr && !xdr(rqstp, nfserrp, rqstp->rq_resp)) { /* Failed to encode result. Release cache entry */ dprintk("nfsd: failed to encode result!\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); *statp = rpc_system_err; return 1; } } /* Store reply in cache. */ nfsd_cache_update(rqstp, rqstp->rq_cachetype, statp + 1); return 1; } Commit Message: nfsd: check for oversized NFSv2/v3 arguments A client can append random data to the end of an NFSv2 or NFSv3 RPC call without our complaining; we'll just stop parsing at the end of the expected data and ignore the rest. Encoded arguments and replies are stored together in an array of pages, and if a call is too large it could leave inadequate space for the reply. This is normally OK because NFS RPC's typically have either short arguments and long replies (like READ) or long arguments and short replies (like WRITE). But a client that sends an incorrectly long reply can violate those assumptions. This was observed to cause crashes. Also, several operations increment rq_next_page in the decode routine before checking the argument size, which can leave rq_next_page pointing well past the end of the page array, causing trouble later in svc_free_pages. So, following a suggestion from Neil Brown, add a central check to enforce our expectation that no NFSv2/v3 call has both a large call and a large reply. As followup we may also want to rewrite the encoding routines to check more carefully that they aren't running off the end of the page array. We may also consider rejecting calls that have any extra garbage appended. That would be safer, and within our rights by spec, but given the age of our server and the NFS protocol, and the fact that we've never enforced this before, we may need to balance that against the possibility of breaking some oddball client. Reported-by: Tuomas Haanpää <[email protected]> Reported-by: Ari Kauppi <[email protected]> Cc: [email protected] Reviewed-by: NeilBrown <[email protected]> Signed-off-by: J. Bruce Fields <[email protected]> CWE ID: CWE-20
nfsd_dispatch(struct svc_rqst *rqstp, __be32 *statp) { struct svc_procedure *proc; kxdrproc_t xdr; __be32 nfserr; __be32 *nfserrp; dprintk("nfsd_dispatch: vers %d proc %d\n", rqstp->rq_vers, rqstp->rq_proc); proc = rqstp->rq_procinfo; if (nfs_request_too_big(rqstp, proc)) { dprintk("nfsd: NFSv%d argument too large\n", rqstp->rq_vers); *statp = rpc_garbage_args; return 1; } /* * Give the xdr decoder a chance to change this if it wants * (necessary in the NFSv4.0 compound case) */ rqstp->rq_cachetype = proc->pc_cachetype; /* Decode arguments */ xdr = proc->pc_decode; if (xdr && !xdr(rqstp, (__be32*)rqstp->rq_arg.head[0].iov_base, rqstp->rq_argp)) { dprintk("nfsd: failed to decode arguments!\n"); *statp = rpc_garbage_args; return 1; } /* Check whether we have this call in the cache. */ switch (nfsd_cache_lookup(rqstp)) { case RC_DROPIT: return 0; case RC_REPLY: return 1; case RC_DOIT:; /* do it */ } /* need to grab the location to store the status, as * nfsv4 does some encoding while processing */ nfserrp = rqstp->rq_res.head[0].iov_base + rqstp->rq_res.head[0].iov_len; rqstp->rq_res.head[0].iov_len += sizeof(__be32); /* Now call the procedure handler, and encode NFS status. */ nfserr = proc->pc_func(rqstp, rqstp->rq_argp, rqstp->rq_resp); nfserr = map_new_errors(rqstp->rq_vers, nfserr); if (nfserr == nfserr_dropit || test_bit(RQ_DROPME, &rqstp->rq_flags)) { dprintk("nfsd: Dropping request; may be revisited later\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); return 0; } if (rqstp->rq_proc != 0) *nfserrp++ = nfserr; /* Encode result. * For NFSv2, additional info is never returned in case of an error. */ if (!(nfserr && rqstp->rq_vers == 2)) { xdr = proc->pc_encode; if (xdr && !xdr(rqstp, nfserrp, rqstp->rq_resp)) { /* Failed to encode result. Release cache entry */ dprintk("nfsd: failed to encode result!\n"); nfsd_cache_update(rqstp, RC_NOCACHE, NULL); *statp = rpc_system_err; return 1; } } /* Store reply in cache. */ nfsd_cache_update(rqstp, rqstp->rq_cachetype, statp + 1); return 1; }
168,256
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: XSLStyleSheet::XSLStyleSheet(Node* parentNode, const String& originalURL, const KURL& finalURL, bool embedded) : m_ownerNode(parentNode) , m_originalURL(originalURL) , m_finalURL(finalURL) , m_isDisabled(false) , m_embedded(embedded) , m_processed(true) // The root sheet starts off processed. , m_stylesheetDoc(0) , m_stylesheetDocTaken(false) , m_parentStyleSheet(0) { } Commit Message: Avoid reparsing an XSLT stylesheet after the first failure. Certain libxslt versions appear to leave the doc in an invalid state when parsing fails. We should cache this result and avoid re-parsing. (The test cannot be converted to text-only due to its invalid stylesheet). [email protected],[email protected],[email protected] BUG=271939 Review URL: https://chromiumcodereview.appspot.com/23103007 git-svn-id: svn://svn.chromium.org/blink/trunk@156248 bbb929c8-8fbe-4397-9dbb-9b2b20218538 CWE ID: CWE-399
XSLStyleSheet::XSLStyleSheet(Node* parentNode, const String& originalURL, const KURL& finalURL, bool embedded) : m_ownerNode(parentNode) , m_originalURL(originalURL) , m_finalURL(finalURL) , m_isDisabled(false) , m_embedded(embedded) , m_processed(true) // The root sheet starts off processed. , m_stylesheetDoc(0) , m_stylesheetDocTaken(false) , m_compilationFailed(false) , m_parentStyleSheet(0) { }
171,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: cJSON *cJSON_CreateFloatArray( double *numbers, int count ) { int i; cJSON *n = 0, *p = 0, *a = cJSON_CreateArray(); for ( i = 0; a && i < count; ++i ) { n = cJSON_CreateFloat( numbers[i] ); if ( ! i ) a->child = n; else suffix_object( p, n ); p = n; } return a; } 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_CreateFloatArray( double *numbers, int count )
167,273
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_tfra(MOVContext *mov, AVIOContext *f) { MOVFragmentIndex* index = NULL; int version, fieldlength, i, j; int64_t pos = avio_tell(f); uint32_t size = avio_rb32(f); void *tmp; if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) { return 1; } av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n"); index = av_mallocz(sizeof(MOVFragmentIndex)); if (!index) { return AVERROR(ENOMEM); } tmp = av_realloc_array(mov->fragment_index_data, mov->fragment_index_count + 1, sizeof(MOVFragmentIndex*)); if (!tmp) { av_freep(&index); return AVERROR(ENOMEM); } mov->fragment_index_data = tmp; mov->fragment_index_data[mov->fragment_index_count++] = index; version = avio_r8(f); avio_rb24(f); index->track_id = avio_rb32(f); fieldlength = avio_rb32(f); index->item_count = avio_rb32(f); index->items = av_mallocz_array( index->item_count, sizeof(MOVFragmentIndexItem)); if (!index->items) { index->item_count = 0; return AVERROR(ENOMEM); } for (i = 0; i < index->item_count; i++) { int64_t time, offset; if (version == 1) { time = avio_rb64(f); offset = avio_rb64(f); } else { time = avio_rb32(f); offset = avio_rb32(f); } index->items[i].time = time; index->items[i].moof_offset = offset; for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++) avio_r8(f); } avio_seek(f, pos + size, SEEK_SET); return 0; } Commit Message: avformat/mov: Fix DoS in read_tfra() Fixes: Missing EOF check in loop No testcase Found-by: Xiaohei and Wangchu from Alibaba Security Team Signed-off-by: Michael Niedermayer <[email protected]> CWE ID: CWE-834
static int read_tfra(MOVContext *mov, AVIOContext *f) { MOVFragmentIndex* index = NULL; int version, fieldlength, i, j; int64_t pos = avio_tell(f); uint32_t size = avio_rb32(f); void *tmp; if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) { return 1; } av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n"); index = av_mallocz(sizeof(MOVFragmentIndex)); if (!index) { return AVERROR(ENOMEM); } tmp = av_realloc_array(mov->fragment_index_data, mov->fragment_index_count + 1, sizeof(MOVFragmentIndex*)); if (!tmp) { av_freep(&index); return AVERROR(ENOMEM); } mov->fragment_index_data = tmp; mov->fragment_index_data[mov->fragment_index_count++] = index; version = avio_r8(f); avio_rb24(f); index->track_id = avio_rb32(f); fieldlength = avio_rb32(f); index->item_count = avio_rb32(f); index->items = av_mallocz_array( index->item_count, sizeof(MOVFragmentIndexItem)); if (!index->items) { index->item_count = 0; return AVERROR(ENOMEM); } for (i = 0; i < index->item_count; i++) { int64_t time, offset; if (avio_feof(f)) { index->item_count = 0; av_freep(&index->items); return AVERROR_INVALIDDATA; } if (version == 1) { time = avio_rb64(f); offset = avio_rb64(f); } else { time = avio_rb32(f); offset = avio_rb32(f); } index->items[i].time = time; index->items[i].moof_offset = offset; for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++) avio_r8(f); } avio_seek(f, pos + size, SEEK_SET); return 0; }
167,759
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t BnGraphicBufferConsumer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case ACQUIRE_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); BufferItem item; int64_t presentWhen = data.readInt64(); uint64_t maxFrameNumber = data.readUint64(); status_t result = acquireBuffer(&item, presentWhen, maxFrameNumber); status_t err = reply->write(item); if (err) return err; reply->writeInt32(result); return NO_ERROR; } case DETACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int slot = data.readInt32(); int result = detachBuffer(slot); reply->writeInt32(result); return NO_ERROR; } case ATTACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<GraphicBuffer> buffer = new GraphicBuffer(); data.read(*buffer.get()); int slot = -1; int result = attachBuffer(&slot, buffer); reply->writeInt32(slot); reply->writeInt32(result); return NO_ERROR; } case RELEASE_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int buf = data.readInt32(); uint64_t frameNumber = static_cast<uint64_t>(data.readInt64()); sp<Fence> releaseFence = new Fence(); status_t err = data.read(*releaseFence); if (err) return err; status_t result = releaseBuffer(buf, frameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence); reply->writeInt32(result); return NO_ERROR; } case CONSUMER_CONNECT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() ); bool controlledByApp = data.readInt32(); status_t result = consumerConnect(consumer, controlledByApp); reply->writeInt32(result); return NO_ERROR; } case CONSUMER_DISCONNECT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); status_t result = consumerDisconnect(); reply->writeInt32(result); return NO_ERROR; } case GET_RELEASED_BUFFERS: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint64_t slotMask; status_t result = getReleasedBuffers(&slotMask); reply->writeInt64(static_cast<int64_t>(slotMask)); reply->writeInt32(result); return NO_ERROR; } case SET_DEFAULT_BUFFER_SIZE: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); status_t result = setDefaultBufferSize(width, height); reply->writeInt32(result); return NO_ERROR; } case SET_DEFAULT_MAX_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int bufferCount = data.readInt32(); status_t result = setDefaultMaxBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } case DISABLE_ASYNC_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); status_t result = disableAsyncBuffer(); reply->writeInt32(result); return NO_ERROR; } case SET_MAX_ACQUIRED_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int maxAcquiredBuffers = data.readInt32(); status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers); reply->writeInt32(result); return NO_ERROR; } case SET_CONSUMER_NAME: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); setConsumerName( data.readString8() ); return NO_ERROR; } case SET_DEFAULT_BUFFER_FORMAT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); PixelFormat defaultFormat = static_cast<PixelFormat>(data.readInt32()); status_t result = setDefaultBufferFormat(defaultFormat); reply->writeInt32(result); return NO_ERROR; } case SET_DEFAULT_BUFFER_DATA_SPACE: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); android_dataspace defaultDataSpace = static_cast<android_dataspace>(data.readInt32()); status_t result = setDefaultBufferDataSpace(defaultDataSpace); reply->writeInt32(result); return NO_ERROR; } case SET_CONSUMER_USAGE_BITS: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t usage = data.readUint32(); status_t result = setConsumerUsageBits(usage); reply->writeInt32(result); return NO_ERROR; } case SET_TRANSFORM_HINT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t hint = data.readUint32(); status_t result = setTransformHint(hint); reply->writeInt32(result); return NO_ERROR; } case GET_SIDEBAND_STREAM: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<NativeHandle> stream = getSidebandStream(); reply->writeInt32(static_cast<int32_t>(stream != NULL)); if (stream != NULL) { reply->writeNativeHandle(stream->handle()); } return NO_ERROR; } case DUMP: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); String8 result = data.readString8(); String8 prefix = data.readString8(); static_cast<IGraphicBufferConsumer*>(this)->dump(result, prefix); reply->writeString8(result); return NO_ERROR; } } return BBinder::onTransact(code, data, reply, flags); } Commit Message: BQ: fix some uninitialized variables Bug 27555981 Bug 27556038 Change-Id: I436b6fec589677d7e36c0e980f6e59808415dc0e CWE ID: CWE-200
status_t BnGraphicBufferConsumer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { switch(code) { case ACQUIRE_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); BufferItem item; int64_t presentWhen = data.readInt64(); uint64_t maxFrameNumber = data.readUint64(); status_t result = acquireBuffer(&item, presentWhen, maxFrameNumber); status_t err = reply->write(item); if (err) return err; reply->writeInt32(result); return NO_ERROR; } case DETACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int slot = data.readInt32(); int result = detachBuffer(slot); reply->writeInt32(result); return NO_ERROR; } case ATTACH_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<GraphicBuffer> buffer = new GraphicBuffer(); data.read(*buffer.get()); int slot = -1; int result = attachBuffer(&slot, buffer); reply->writeInt32(slot); reply->writeInt32(result); return NO_ERROR; } case RELEASE_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int buf = data.readInt32(); uint64_t frameNumber = static_cast<uint64_t>(data.readInt64()); sp<Fence> releaseFence = new Fence(); status_t err = data.read(*releaseFence); if (err) return err; status_t result = releaseBuffer(buf, frameNumber, EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence); reply->writeInt32(result); return NO_ERROR; } case CONSUMER_CONNECT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<IConsumerListener> consumer = IConsumerListener::asInterface( data.readStrongBinder() ); bool controlledByApp = data.readInt32(); status_t result = consumerConnect(consumer, controlledByApp); reply->writeInt32(result); return NO_ERROR; } case CONSUMER_DISCONNECT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); status_t result = consumerDisconnect(); reply->writeInt32(result); return NO_ERROR; } case GET_RELEASED_BUFFERS: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint64_t slotMask = 0; status_t result = getReleasedBuffers(&slotMask); reply->writeInt64(static_cast<int64_t>(slotMask)); reply->writeInt32(result); return NO_ERROR; } case SET_DEFAULT_BUFFER_SIZE: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t width = data.readUint32(); uint32_t height = data.readUint32(); status_t result = setDefaultBufferSize(width, height); reply->writeInt32(result); return NO_ERROR; } case SET_DEFAULT_MAX_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int bufferCount = data.readInt32(); status_t result = setDefaultMaxBufferCount(bufferCount); reply->writeInt32(result); return NO_ERROR; } case DISABLE_ASYNC_BUFFER: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); status_t result = disableAsyncBuffer(); reply->writeInt32(result); return NO_ERROR; } case SET_MAX_ACQUIRED_BUFFER_COUNT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); int maxAcquiredBuffers = data.readInt32(); status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers); reply->writeInt32(result); return NO_ERROR; } case SET_CONSUMER_NAME: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); setConsumerName( data.readString8() ); return NO_ERROR; } case SET_DEFAULT_BUFFER_FORMAT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); PixelFormat defaultFormat = static_cast<PixelFormat>(data.readInt32()); status_t result = setDefaultBufferFormat(defaultFormat); reply->writeInt32(result); return NO_ERROR; } case SET_DEFAULT_BUFFER_DATA_SPACE: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); android_dataspace defaultDataSpace = static_cast<android_dataspace>(data.readInt32()); status_t result = setDefaultBufferDataSpace(defaultDataSpace); reply->writeInt32(result); return NO_ERROR; } case SET_CONSUMER_USAGE_BITS: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t usage = data.readUint32(); status_t result = setConsumerUsageBits(usage); reply->writeInt32(result); return NO_ERROR; } case SET_TRANSFORM_HINT: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); uint32_t hint = data.readUint32(); status_t result = setTransformHint(hint); reply->writeInt32(result); return NO_ERROR; } case GET_SIDEBAND_STREAM: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); sp<NativeHandle> stream = getSidebandStream(); reply->writeInt32(static_cast<int32_t>(stream != NULL)); if (stream != NULL) { reply->writeNativeHandle(stream->handle()); } return NO_ERROR; } case DUMP: { CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); String8 result = data.readString8(); String8 prefix = data.readString8(); static_cast<IGraphicBufferConsumer*>(this)->dump(result, prefix); reply->writeString8(result); return NO_ERROR; } } return BBinder::onTransact(code, data, reply, flags); }
173,877
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: name_len(netdissect_options *ndo, const unsigned char *s, const unsigned char *maxbuf) { const unsigned char *s0 = s; unsigned char c; if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); c = *s; if ((c & 0xC0) == 0xC0) return(2); while (*s) { if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); s += (*s) + 1; } return(PTR_DIFF(s, s0) + 1); trunc: return(-1); /* name goes past the end of the buffer */ } Commit Message: CVE-2017-12893/SMB/CIFS: Add a bounds check in name_len(). After we advance the pointer by the length value in the buffer, make sure it points to something in the captured data. This fixes a buffer over-read discovered by Forcepoint's security researchers Otto Airamo & Antti Levomäki. Add a test using the capture file supplied by the reporter(s). CWE ID: CWE-125
name_len(netdissect_options *ndo, const unsigned char *s, const unsigned char *maxbuf) { const unsigned char *s0 = s; unsigned char c; if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); c = *s; if ((c & 0xC0) == 0xC0) return(2); while (*s) { if (s >= maxbuf) return(-1); /* name goes past the end of the buffer */ ND_TCHECK2(*s, 1); s += (*s) + 1; ND_TCHECK2(*s, 1); } return(PTR_DIFF(s, s0) + 1); trunc: return(-1); /* name goes past the end of the buffer */ }
167,961
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ffs_user_copy_worker(struct work_struct *work) { struct ffs_io_data *io_data = container_of(work, struct ffs_io_data, work); int ret = io_data->req->status ? io_data->req->status : io_data->req->actual; if (io_data->read && ret > 0) { use_mm(io_data->mm); ret = copy_to_iter(io_data->buf, ret, &io_data->data); if (iov_iter_count(&io_data->data)) ret = -EFAULT; unuse_mm(io_data->mm); } io_data->kiocb->ki_complete(io_data->kiocb, ret, ret); if (io_data->ffs->ffs_eventfd && !(io_data->kiocb->ki_flags & IOCB_EVENTFD)) eventfd_signal(io_data->ffs->ffs_eventfd, 1); usb_ep_free_request(io_data->ep, io_data->req); io_data->kiocb->private = NULL; if (io_data->read) kfree(io_data->to_free); kfree(io_data->buf); kfree(io_data); } Commit Message: usb: gadget: f_fs: Fix use-after-free When using asynchronous read or write operations on the USB endpoints the issuer of the IO request is notified by calling the ki_complete() callback of the submitted kiocb when the URB has been completed. Calling this ki_complete() callback will free kiocb. Make sure that the structure is no longer accessed beyond that point, otherwise undefined behaviour might occur. Fixes: 2e4c7553cd6f ("usb: gadget: f_fs: add aio support") Cc: <[email protected]> # v3.15+ Signed-off-by: Lars-Peter Clausen <[email protected]> Signed-off-by: Felipe Balbi <[email protected]> CWE ID: CWE-416
static void ffs_user_copy_worker(struct work_struct *work) { struct ffs_io_data *io_data = container_of(work, struct ffs_io_data, work); int ret = io_data->req->status ? io_data->req->status : io_data->req->actual; bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD; if (io_data->read && ret > 0) { use_mm(io_data->mm); ret = copy_to_iter(io_data->buf, ret, &io_data->data); if (iov_iter_count(&io_data->data)) ret = -EFAULT; unuse_mm(io_data->mm); } io_data->kiocb->ki_complete(io_data->kiocb, ret, ret); if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd) eventfd_signal(io_data->ffs->ffs_eventfd, 1); usb_ep_free_request(io_data->ep, io_data->req); if (io_data->read) kfree(io_data->to_free); kfree(io_data->buf); kfree(io_data); }
166,924
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AppCache::AddEntry(const GURL& url, const AppCacheEntry& entry) { DCHECK(entries_.find(url) == entries_.end()); entries_.insert(EntryMap::value_type(url, entry)); cache_size_ += entry.response_size(); } Commit Message: Reland "AppCache: Add padding to cross-origin responses." This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7 Initialized CacheRecord::padding_size to 0. Original change's description: > AppCache: Add padding to cross-origin responses. > > Bug: 918293 > Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c > Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059 > Commit-Queue: Staphany Park <[email protected]> > Reviewed-by: Victor Costan <[email protected]> > Reviewed-by: Marijn Kruisselbrink <[email protected]> > Cr-Commit-Position: refs/heads/master@{#644624} Bug: 918293 Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906 Reviewed-by: Victor Costan <[email protected]> Commit-Queue: Staphany Park <[email protected]> Cr-Commit-Position: refs/heads/master@{#644719} CWE ID: CWE-200
void AppCache::AddEntry(const GURL& url, const AppCacheEntry& entry) { DCHECK(entries_.find(url) == entries_.end()); entries_.insert(EntryMap::value_type(url, entry)); cache_size_ += entry.response_size(); padding_size_ += entry.padding_size(); }
172,967
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: gfx::Vector2d LayerTreeHost::DistributeScrollOffsetToViewports( const gfx::Vector2d offset, Layer* layer) { DCHECK(layer); if (layer != outer_viewport_scroll_layer_.get()) return offset; gfx::Vector2d inner_viewport_offset = inner_viewport_scroll_layer_->scroll_offset(); gfx::Vector2d outer_viewport_offset = outer_viewport_scroll_layer_->scroll_offset(); if (offset == inner_viewport_offset + outer_viewport_offset) { return outer_viewport_offset; } gfx::Vector2d max_outer_viewport_scroll_offset = outer_viewport_scroll_layer_->MaxScrollOffset(); gfx::Vector2d max_inner_viewport_scroll_offset = inner_viewport_scroll_layer_->MaxScrollOffset(); outer_viewport_offset = offset - inner_viewport_offset; outer_viewport_offset.SetToMin(max_outer_viewport_scroll_offset); outer_viewport_offset.SetToMax(gfx::Vector2d()); inner_viewport_offset = offset - outer_viewport_offset; inner_viewport_offset.SetToMin(max_inner_viewport_scroll_offset); inner_viewport_offset.SetToMax(gfx::Vector2d()); inner_viewport_scroll_layer_->SetScrollOffset(inner_viewport_offset); return outer_viewport_offset; } Commit Message: Removed pinch viewport scroll offset distribution The associated change in Blink makes the pinch viewport a proper ScrollableArea meaning the normal path for synchronizing layer scroll offsets is used. This is a 2 sided patch, the other CL: https://codereview.chromium.org/199253002/ BUG=349941 Review URL: https://codereview.chromium.org/210543002 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@260105 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
gfx::Vector2d LayerTreeHost::DistributeScrollOffsetToViewports(
171,199
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: OMX_ERRORTYPE omx_video::use_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes, OMX_IN OMX_U8* buffer) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; unsigned char *buf_addr = NULL; DEBUG_PRINT_HIGH("use_input_buffer: port = %u appData = %p bytes = %u buffer = %p",(unsigned int)port,appData,(unsigned int)bytes,buffer); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: use_input_buffer: Size Mismatch!! " "bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { input_use_buffer = true; m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); BITMASK_SET(&m_inp_bm_count,i); (*bufferHdr)->pBuffer = (OMX_U8 *)buffer; (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; if (!m_use_input_pmem) { #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i] .fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap( NULL,m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap() Failed"); close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } } else { OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *>((*bufferHdr)->pAppPrivate); DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (unsigned)pParam->offset); if (pParam) { m_pInput_pmem[i].fd = pParam->pmem_fd; m_pInput_pmem[i].offset = pParam->offset; m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].buffer = (unsigned char *)buffer; DEBUG_PRINT_LOW("DBG:: pParam->pmem_fd = %u, pParam->offset = %u", (unsigned int)pParam->pmem_fd, (unsigned int)pParam->offset); } else { DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM i/p UseBuffer case"); return OMX_ErrorBadParameter; } } DEBUG_PRINT_LOW("use_inp:: bufhdr = %p, pBuffer = %p, m_pInput_pmem[i].buffer = %p", (*bufferHdr), (*bufferHdr)->pBuffer, m_pInput_pmem[i].buffer); if ( dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf() Failed for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All buffers are already used, invalid use_buf call for " "index = %u", i); eRet = OMX_ErrorInsufficientResources; } return eRet; } Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers Heap pointers do not point to user virtual addresses in case of secure session. Set them to NULL and add checks to avoid accesing them Bug: 28815329 Bug: 28920116 Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26 CWE ID: CWE-200
OMX_ERRORTYPE omx_video::use_input_buffer( OMX_IN OMX_HANDLETYPE hComp, OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr, OMX_IN OMX_U32 port, OMX_IN OMX_PTR appData, OMX_IN OMX_U32 bytes, OMX_IN OMX_U8* buffer) { (void) hComp; OMX_ERRORTYPE eRet = OMX_ErrorNone; unsigned i = 0; unsigned char *buf_addr = NULL; DEBUG_PRINT_HIGH("use_input_buffer: port = %u appData = %p bytes = %u buffer = %p",(unsigned int)port,appData,(unsigned int)bytes,buffer); if (bytes != m_sInPortDef.nBufferSize) { DEBUG_PRINT_ERROR("ERROR: use_input_buffer: Size Mismatch!! " "bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sInPortDef.nBufferSize); return OMX_ErrorBadParameter; } if (!m_inp_mem_ptr) { input_use_buffer = true; m_inp_mem_ptr = (OMX_BUFFERHEADERTYPE*) \ calloc( (sizeof(OMX_BUFFERHEADERTYPE)), m_sInPortDef.nBufferCountActual); if (m_inp_mem_ptr == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_inp_mem_ptr"); return OMX_ErrorInsufficientResources; } DEBUG_PRINT_LOW("Successfully allocated m_inp_mem_ptr = %p", m_inp_mem_ptr); m_pInput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sInPortDef.nBufferCountActual); if (m_pInput_pmem == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_pmem"); return OMX_ErrorInsufficientResources; } #ifdef USE_ION m_pInput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sInPortDef.nBufferCountActual); if (m_pInput_ion == NULL) { DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pInput_ion"); return OMX_ErrorInsufficientResources; } #endif for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { m_pInput_pmem[i].fd = -1; #ifdef USE_ION m_pInput_ion[i].ion_device_fd =-1; m_pInput_ion[i].fd_ion_data.fd =-1; m_pInput_ion[i].ion_alloc_data.handle = 0; #endif } } for (i=0; i< m_sInPortDef.nBufferCountActual; i++) { if (BITMASK_ABSENT(&m_inp_bm_count,i)) { break; } } if (i < m_sInPortDef.nBufferCountActual) { *bufferHdr = (m_inp_mem_ptr + i); BITMASK_SET(&m_inp_bm_count,i); (*bufferHdr)->pBuffer = (OMX_U8 *)buffer; (*bufferHdr)->nSize = sizeof(OMX_BUFFERHEADERTYPE); (*bufferHdr)->nVersion.nVersion = OMX_SPEC_VERSION; (*bufferHdr)->nAllocLen = m_sInPortDef.nBufferSize; (*bufferHdr)->pAppPrivate = appData; (*bufferHdr)->nInputPortIndex = PORT_INDEX_IN; if (!m_use_input_pmem) { #ifdef USE_ION #ifdef _MSM8974_ m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,0); #else m_pInput_ion[i].ion_device_fd = alloc_map_ion_memory(m_sInPortDef.nBufferSize, &m_pInput_ion[i].ion_alloc_data, &m_pInput_ion[i].fd_ion_data,ION_FLAG_CACHED); #endif if (m_pInput_ion[i].ion_device_fd < 0) { DEBUG_PRINT_ERROR("ERROR:ION device open() Failed"); return OMX_ErrorInsufficientResources; } m_pInput_pmem[i].fd = m_pInput_ion[i].fd_ion_data.fd; #else m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); if (m_pInput_pmem[i].fd == 0) { m_pInput_pmem[i].fd = open (MEM_DEVICE,O_RDWR); } if (m_pInput_pmem[i] .fd < 0) { DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed"); return OMX_ErrorInsufficientResources; } #endif m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].offset = 0; m_pInput_pmem[i].buffer = NULL; if(!secure_session) { m_pInput_pmem[i].buffer = (unsigned char *)mmap( NULL,m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, MAP_SHARED,m_pInput_pmem[i].fd,0); if (m_pInput_pmem[i].buffer == MAP_FAILED) { DEBUG_PRINT_ERROR("ERROR: mmap() Failed"); m_pInput_pmem[i].buffer = NULL; close(m_pInput_pmem[i].fd); #ifdef USE_ION free_ion_memory(&m_pInput_ion[i]); #endif return OMX_ErrorInsufficientResources; } } } else { OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *>((*bufferHdr)->pAppPrivate); DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (unsigned)pParam->offset); if (pParam) { m_pInput_pmem[i].fd = pParam->pmem_fd; m_pInput_pmem[i].offset = pParam->offset; m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; m_pInput_pmem[i].buffer = (unsigned char *)buffer; DEBUG_PRINT_LOW("DBG:: pParam->pmem_fd = %u, pParam->offset = %u", (unsigned int)pParam->pmem_fd, (unsigned int)pParam->offset); } else { DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM i/p UseBuffer case"); return OMX_ErrorBadParameter; } } DEBUG_PRINT_LOW("use_inp:: bufhdr = %p, pBuffer = %p, m_pInput_pmem[i].buffer = %p", (*bufferHdr), (*bufferHdr)->pBuffer, m_pInput_pmem[i].buffer); if ( dev_use_buf(&m_pInput_pmem[i],PORT_INDEX_IN,i) != true) { DEBUG_PRINT_ERROR("ERROR: dev_use_buf() Failed for i/p buf"); return OMX_ErrorInsufficientResources; } } else { DEBUG_PRINT_ERROR("ERROR: All buffers are already used, invalid use_buf call for " "index = %u", i); eRet = OMX_ErrorInsufficientResources; } return eRet; }
173,503
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: image_size_of_type(int color_type, int bit_depth, unsigned int *colors) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
image_size_of_type(int color_type, int bit_depth, unsigned int *colors) image_size_of_type(int color_type, int bit_depth, unsigned int *colors, int small) { if (*colors) return 16; else { int pixel_depth = pixel_depth_of_type(color_type, bit_depth); if (small) { if (pixel_depth <= 8) /* there will be one row */ return 1 << pixel_depth; else return 256; } else if (pixel_depth < 8) return 64; else if (pixel_depth > 16) return 1024; else return 256; } }
173,581
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void DownloadManagerImpl::DownloadUrl( std::unique_ptr<download::DownloadUrlParameters> params, std::unique_ptr<storage::BlobDataHandle> blob_data_handle, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) { if (params->post_id() >= 0) { DCHECK(params->prefer_cache()); DCHECK_EQ("POST", params->method()); } download::RecordDownloadCountWithSource( download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT, params->download_source()); auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(), params->render_frame_host_routing_id()); BeginDownloadInternal(std::move(params), std::move(blob_data_handle), std::move(blob_url_loader_factory), true, rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL()); } Commit Message: When turning a download into a navigation, navigate the right frame Code changes from Nate Chapin <[email protected]> Bug: 926105 Change-Id: I098599394e6ebe7d2fce5af838014297a337d294 Reviewed-on: https://chromium-review.googlesource.com/c/1454962 Reviewed-by: Camille Lamy <[email protected]> Commit-Queue: Jochen Eisinger <[email protected]> Cr-Commit-Position: refs/heads/master@{#629547} CWE ID: CWE-284
void DownloadManagerImpl::DownloadUrl( std::unique_ptr<download::DownloadUrlParameters> params, std::unique_ptr<storage::BlobDataHandle> blob_data_handle, scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) { if (params->post_id() >= 0) { DCHECK(params->prefer_cache()); DCHECK_EQ("POST", params->method()); } download::RecordDownloadCountWithSource( download::DownloadCountTypes::DOWNLOAD_TRIGGERED_COUNT, params->download_source()); auto* rfh = RenderFrameHost::FromID(params->render_process_host_id(), params->render_frame_host_routing_id()); if (rfh) params->set_frame_tree_node_id(rfh->GetFrameTreeNodeId()); BeginDownloadInternal(std::move(params), std::move(blob_data_handle), std::move(blob_url_loader_factory), true, rfh ? rfh->GetSiteInstance()->GetSiteURL() : GURL()); }
173,022
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RenderWidgetHostImpl::AcknowledgeBufferPresent( int32 route_id, int gpu_host_id, bool presented, uint32 sync_point) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id, presented, sync_point)); } 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 RenderWidgetHostImpl::AcknowledgeBufferPresent( int32 route_id, int gpu_host_id, uint64 surface_handle, uint32 sync_point) { GpuProcessHostUIShim* ui_shim = GpuProcessHostUIShim::FromID(gpu_host_id); if (ui_shim) ui_shim->Send(new AcceleratedSurfaceMsg_BufferPresented(route_id, surface_handle, sync_point)); }
171,366
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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(linkinfo) { char *link; size_t link_len; zend_stat_t sb; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } ret = VCWD_STAT(link, &sb); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); RETURN_LONG(Z_L(-1)); } RETURN_LONG((zend_long) sb.st_dev); } Commit Message: Fixed bug #76459 windows linkinfo lacks openbasedir check CWE ID: CWE-200
PHP_FUNCTION(linkinfo) { char *link; char *dirname; size_t link_len; zend_stat_t sb; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "p", &link, &link_len) == FAILURE) { return; } dirname = estrndup(link, link_len); php_dirname(dirname, link_len); if (php_check_open_basedir(dirname)) { efree(dirname); RETURN_FALSE; } ret = VCWD_STAT(link, &sb); if (ret == -1) { php_error_docref(NULL, E_WARNING, "%s", strerror(errno)); efree(dirname); RETURN_LONG(Z_L(-1)); } efree(dirname); RETURN_LONG((zend_long) sb.st_dev); }
169,107
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SocketStream::DoBeforeConnect() { next_state_ = STATE_BEFORE_CONNECT_COMPLETE; if (!context_.get() || !context_->network_delegate()) { return OK; } int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect( this, io_callback_); if (result != OK && result != ERR_IO_PENDING) next_state_ = STATE_CLOSE; return result; } Commit Message: Revert a workaround commit for a Use-After-Free crash. Revert a workaround commit r20158 for a Use-After-Free issue (http://crbug.com/244746) because a cleaner CL r207218 is landed. URLRequestContext does not inherit SupportsWeakPtr now. R=mmenke BUG=244746 Review URL: https://chromiumcodereview.appspot.com/16870008 git-svn-id: svn://svn.chromium.org/chrome/trunk/src@207811 0039d316-1c4b-4281-b951-d872f2087c98 CWE ID: CWE-399
int SocketStream::DoBeforeConnect() { next_state_ = STATE_BEFORE_CONNECT_COMPLETE; if (!context_ || !context_->network_delegate()) return OK; int result = context_->network_delegate()->NotifyBeforeSocketStreamConnect( this, io_callback_); if (result != OK && result != ERR_IO_PENDING) next_state_ = STATE_CLOSE; return result; }
171,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: static int handle_exception(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_run *kvm_run = vcpu->run; u32 intr_info, ex_no, error_code; unsigned long cr2, rip, dr6; u32 vect_info; enum emulation_result er; vect_info = vmx->idt_vectoring_info; intr_info = vmx->exit_intr_info; if (is_machine_check(intr_info)) return handle_machine_check(vcpu); if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) return 1; /* already handled by vmx_vcpu_run() */ if (is_no_device(intr_info)) { vmx_fpu_activate(vcpu); return 1; } if (is_invalid_opcode(intr_info)) { if (is_guest_mode(vcpu)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD); if (er != EMULATE_DONE) kvm_queue_exception(vcpu, UD_VECTOR); return 1; } error_code = 0; if (intr_info & INTR_INFO_DELIVER_CODE_MASK) error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); /* * The #PF with PFEC.RSVD = 1 indicates the guest is accessing * MMIO, it is better to report an internal error. * See the comments in vmx_handle_exit. */ if ((vect_info & VECTORING_INFO_VALID_MASK) && !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; vcpu->run->internal.ndata = 3; vcpu->run->internal.data[0] = vect_info; vcpu->run->internal.data[1] = intr_info; vcpu->run->internal.data[2] = error_code; return 0; } if (is_page_fault(intr_info)) { /* EPT won't cause page fault directly */ BUG_ON(enable_ept); cr2 = vmcs_readl(EXIT_QUALIFICATION); trace_kvm_page_fault(cr2, error_code); if (kvm_event_needs_reinjection(vcpu)) kvm_mmu_unprotect_page_virt(vcpu, cr2); return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0); } ex_no = intr_info & INTR_INFO_VECTOR_MASK; if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) return handle_rmode_exception(vcpu, ex_no, error_code); switch (ex_no) { case DB_VECTOR: dr6 = vmcs_readl(EXIT_QUALIFICATION); if (!(vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { vcpu->arch.dr6 &= ~15; vcpu->arch.dr6 |= dr6 | DR6_RTM; if (!(dr6 & ~DR6_RESERVED)) /* icebp */ skip_emulated_instruction(vcpu); kvm_queue_exception(vcpu, DB_VECTOR); return 1; } kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1; kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); /* fall through */ case BP_VECTOR: /* * Update instruction length as we may reinject #BP from * user space while in guest debugging mode. Reading it for * #DB as well causes no harm, it is not used in that case. */ vmx->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_run->exit_reason = KVM_EXIT_DEBUG; rip = kvm_rip_read(vcpu); kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip; kvm_run->debug.arch.exception = ex_no; break; default: kvm_run->exit_reason = KVM_EXIT_EXCEPTION; kvm_run->ex.exception = ex_no; kvm_run->ex.error_code = error_code; break; } return 0; } Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered It was found that a guest can DoS a host by triggering an infinite stream of "alignment check" (#AC) exceptions. This causes the microcode to enter an infinite loop where the core never receives another interrupt. The host kernel panics pretty quickly due to the effects (CVE-2015-5307). Signed-off-by: Eric Northup <[email protected]> Cc: [email protected] Signed-off-by: Paolo Bonzini <[email protected]> CWE ID: CWE-399
static int handle_exception(struct kvm_vcpu *vcpu) { struct vcpu_vmx *vmx = to_vmx(vcpu); struct kvm_run *kvm_run = vcpu->run; u32 intr_info, ex_no, error_code; unsigned long cr2, rip, dr6; u32 vect_info; enum emulation_result er; vect_info = vmx->idt_vectoring_info; intr_info = vmx->exit_intr_info; if (is_machine_check(intr_info)) return handle_machine_check(vcpu); if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) return 1; /* already handled by vmx_vcpu_run() */ if (is_no_device(intr_info)) { vmx_fpu_activate(vcpu); return 1; } if (is_invalid_opcode(intr_info)) { if (is_guest_mode(vcpu)) { kvm_queue_exception(vcpu, UD_VECTOR); return 1; } er = emulate_instruction(vcpu, EMULTYPE_TRAP_UD); if (er != EMULATE_DONE) kvm_queue_exception(vcpu, UD_VECTOR); return 1; } error_code = 0; if (intr_info & INTR_INFO_DELIVER_CODE_MASK) error_code = vmcs_read32(VM_EXIT_INTR_ERROR_CODE); /* * The #PF with PFEC.RSVD = 1 indicates the guest is accessing * MMIO, it is better to report an internal error. * See the comments in vmx_handle_exit. */ if ((vect_info & VECTORING_INFO_VALID_MASK) && !(is_page_fault(intr_info) && !(error_code & PFERR_RSVD_MASK))) { vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR; vcpu->run->internal.suberror = KVM_INTERNAL_ERROR_SIMUL_EX; vcpu->run->internal.ndata = 3; vcpu->run->internal.data[0] = vect_info; vcpu->run->internal.data[1] = intr_info; vcpu->run->internal.data[2] = error_code; return 0; } if (is_page_fault(intr_info)) { /* EPT won't cause page fault directly */ BUG_ON(enable_ept); cr2 = vmcs_readl(EXIT_QUALIFICATION); trace_kvm_page_fault(cr2, error_code); if (kvm_event_needs_reinjection(vcpu)) kvm_mmu_unprotect_page_virt(vcpu, cr2); return kvm_mmu_page_fault(vcpu, cr2, error_code, NULL, 0); } ex_no = intr_info & INTR_INFO_VECTOR_MASK; if (vmx->rmode.vm86_active && rmode_exception(vcpu, ex_no)) return handle_rmode_exception(vcpu, ex_no, error_code); switch (ex_no) { case AC_VECTOR: kvm_queue_exception_e(vcpu, AC_VECTOR, error_code); return 1; case DB_VECTOR: dr6 = vmcs_readl(EXIT_QUALIFICATION); if (!(vcpu->guest_debug & (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP))) { vcpu->arch.dr6 &= ~15; vcpu->arch.dr6 |= dr6 | DR6_RTM; if (!(dr6 & ~DR6_RESERVED)) /* icebp */ skip_emulated_instruction(vcpu); kvm_queue_exception(vcpu, DB_VECTOR); return 1; } kvm_run->debug.arch.dr6 = dr6 | DR6_FIXED_1; kvm_run->debug.arch.dr7 = vmcs_readl(GUEST_DR7); /* fall through */ case BP_VECTOR: /* * Update instruction length as we may reinject #BP from * user space while in guest debugging mode. Reading it for * #DB as well causes no harm, it is not used in that case. */ vmx->vcpu.arch.event_exit_inst_len = vmcs_read32(VM_EXIT_INSTRUCTION_LEN); kvm_run->exit_reason = KVM_EXIT_DEBUG; rip = kvm_rip_read(vcpu); kvm_run->debug.arch.pc = vmcs_readl(GUEST_CS_BASE) + rip; kvm_run->debug.arch.exception = ex_no; break; default: kvm_run->exit_reason = KVM_EXIT_EXCEPTION; kvm_run->ex.exception = ex_no; kvm_run->ex.error_code = error_code; break; } return 0; }
166,599
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { if (settings.verbose > 0) fprintf(stderr, "Couldn't realloc input buffer\n"); c->rbytes = 0; /* ignore what we read */ out_string(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } Commit Message: Issue 102: Piping null to the server will crash it CWE ID: CWE-20
static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { if (settings.verbose > 0) fprintf(stderr, "Couldn't realloc input buffer\n"); c->rbytes = 0; /* ignore what we read */ out_string(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; }
169,876
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsSecure && !audio) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; } Commit Message: MPEG4Extractor: ensure kKeyTrackID exists before creating an MPEG4Source as track. GenericSource: return error when no track exists. SampleIterator: make sure mSamplesPerChunk is not zero before using it as divisor. Bug: 21657957 Bug: 23705695 Bug: 22802344 Bug: 28799341 Change-Id: I7664992ade90b935d3f255dcd43ecc2898f30b04 (cherry picked from commit 0386c91b8a910a134e5898ffa924c1b6c7560b13) CWE ID: CWE-119
status_t NuPlayer::GenericSource::setBuffers( bool audio, Vector<MediaBuffer *> &buffers) { if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) { return mVideoTrack.mSource->setBuffers(buffers); } return INVALID_OPERATION; }
173,763
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: pixel_copy(png_bytep toBuffer, png_uint_32 toIndex, png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize) { /* Assume we can multiply by 'size' without overflow because we are * just working in a single buffer. */ toIndex *= pixelSize; fromIndex *= pixelSize; if (pixelSize < 8) /* Sub-byte */ { /* Mask to select the location of the copied pixel: */ unsigned int destMask = ((1U<<pixelSize)-1) << (8-pixelSize-(toIndex&7)); /* The following read the entire pixels and clears the extra: */ unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask; unsigned int sourceByte = fromBuffer[fromIndex >> 3]; /* Don't rely on << or >> supporting '0' here, just in case: */ fromIndex &= 7; if (fromIndex > 0) sourceByte <<= fromIndex; if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7; toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask)); } else /* One or more bytes */ memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3); } Commit Message: DO NOT MERGE Update libpng to 1.6.20 BUG:23265085 Change-Id: I85199805636d771f3597b691b63bc0bf46084833 (cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82) CWE ID:
pixel_copy(png_bytep toBuffer, png_uint_32 toIndex, png_const_bytep fromBuffer, png_uint_32 fromIndex, unsigned int pixelSize, int littleendian) { /* Assume we can multiply by 'size' without overflow because we are * just working in a single buffer. */ toIndex *= pixelSize; fromIndex *= pixelSize; if (pixelSize < 8) /* Sub-byte */ { /* Mask to select the location of the copied pixel: */ unsigned int destMask = ((1U<<pixelSize)-1) << (littleendian ? toIndex&7 : 8-pixelSize-(toIndex&7)); /* The following read the entire pixels and clears the extra: */ unsigned int destByte = toBuffer[toIndex >> 3] & ~destMask; unsigned int sourceByte = fromBuffer[fromIndex >> 3]; /* Don't rely on << or >> supporting '0' here, just in case: */ fromIndex &= 7; if (littleendian) { if (fromIndex > 0) sourceByte >>= fromIndex; if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7; } else { if (fromIndex > 0) sourceByte <<= fromIndex; if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7; } toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask)); } else /* One or more bytes */ memmove(toBuffer+(toIndex>>3), fromBuffer+(fromIndex>>3), pixelSize>>3); }
173,685
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; struct user_struct *user; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; user = get_current_user(); if (unlikely(atomic_read(&user->inotify_devs) >= inotify_max_user_instances)) { ret = -EMFILE; goto out_free_uid; } /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(user, inotify_max_queued_events); if (IS_ERR(group)) { ret = PTR_ERR(group); goto out_free_uid; } atomic_inc(&user->inotify_devs); ret = anon_inode_getfd("inotify", &inotify_fops, group, O_RDONLY | flags); if (ret >= 0) return ret; fsnotify_put_group(group); atomic_dec(&user->inotify_devs); out_free_uid: free_uid(user); return ret; } Commit Message: inotify: fix double free/corruption of stuct user On an error path in inotify_init1 a normal user can trigger a double free of struct user. This is a regression introduced by a2ae4cc9a16e ("inotify: stop kernel memory leak on file creation failure"). We fix this by making sure that if a group exists the user reference is dropped when the group is cleaned up. We should not explictly drop the reference on error and also drop the reference when the group is cleaned up. The new lifetime rules are that an inotify group lives from inotify_new_group to the last fsnotify_put_group. Since the struct user and inotify_devs are directly tied to this lifetime they are only changed/updated in those two locations. We get rid of all special casing of struct user or user->inotify_devs. Signed-off-by: Eric Paris <[email protected]> Cc: [email protected] (2.6.37 and up) Signed-off-by: Linus Torvalds <[email protected]> CWE ID: CWE-399
SYSCALL_DEFINE1(inotify_init1, int, flags) { struct fsnotify_group *group; int ret; /* Check the IN_* constants for consistency. */ BUILD_BUG_ON(IN_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(IN_NONBLOCK != O_NONBLOCK); if (flags & ~(IN_CLOEXEC | IN_NONBLOCK)) return -EINVAL; /* fsnotify_obtain_group took a reference to group, we put this when we kill the file in the end */ group = inotify_new_group(inotify_max_queued_events); if (IS_ERR(group)) return PTR_ERR(group); ret = anon_inode_getfd("inotify", &inotify_fops, group, O_RDONLY | flags); if (ret < 0) fsnotify_put_group(group); return ret; }
165,887
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation.
Code: void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } } Commit Message: Check outbuf length in mutt_to_base64() The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c. Thanks to Jeriko One for the bug report. CWE ID: CWE-119
void test_base64_decode(void) { char buffer[16]; int len = mutt_b64_decode(buffer, encoded, sizeof(buffer)); if (!TEST_CHECK(len == sizeof(clear) - 1)) { TEST_MSG("Expected: %zu", sizeof(clear) - 1); TEST_MSG("Actual : %zu", len); } buffer[len] = '\0'; if (!TEST_CHECK(strcmp(buffer, clear) == 0)) { TEST_MSG("Expected: %s", clear); TEST_MSG("Actual : %s", buffer); } }
169,130