instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MaybeStartInputMethodDaemon(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == ImeConfigValue::kValueTypeStringList &&
!value.string_list_value.empty()) {
if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) {
return;
}
const bool just_started = StartInputMethodDaemon();
if (!just_started) {
return;
}
if (tentative_current_input_method_id_.empty()) {
tentative_current_input_method_id_ = current_input_method_.id;
}
if (std::find(value.string_list_value.begin(),
value.string_list_value.end(),
tentative_current_input_method_id_)
== value.string_list_value.end()) {
tentative_current_input_method_id_.clear();
}
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void MaybeStartInputMethodDaemon(const std::string& section,
const std::string& config_name,
const input_method::ImeConfigValue& value) {
if (section == language_prefs::kGeneralSectionName &&
config_name == language_prefs::kPreloadEnginesConfigName &&
value.type == input_method::ImeConfigValue::kValueTypeStringList &&
!value.string_list_value.empty()) {
if (ContainOnlyOneKeyboardLayout(value) || defer_ime_startup_) {
return;
}
const bool just_started = StartInputMethodDaemon();
if (!just_started) {
return;
}
if (tentative_current_input_method_id_.empty()) {
tentative_current_input_method_id_ = current_input_method_.id;
}
if (std::find(value.string_list_value.begin(),
value.string_list_value.end(),
tentative_current_input_method_id_)
== value.string_list_value.end()) {
tentative_current_input_method_id_.clear();
}
}
}
| 170,499 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SplashBitmap::SplashBitmap(int widthA, int heightA, int rowPad,
SplashColorMode modeA, GBool alphaA,
GBool topDown) {
width = widthA;
height = heightA;
mode = modeA;
switch (mode) {
case splashModeMono1:
rowSize = (width + 7) >> 3;
break;
case splashModeMono8:
rowSize = width;
break;
case splashModeRGB8:
case splashModeBGR8:
rowSize = width * 3;
break;
case splashModeXBGR8:
rowSize = width * 4;
break;
#if SPLASH_CMYK
case splashModeCMYK8:
rowSize = width * 4;
break;
#endif
}
rowSize += rowPad - 1;
rowSize -= rowSize % rowPad;
data = (SplashColorPtr)gmalloc(rowSize * height);
if (!topDown) {
data += (height - 1) * rowSize;
rowSize = -rowSize;
}
if (alphaA) {
alpha = (Guchar *)gmalloc(width * height);
} else {
alpha = NULL;
}
}
Commit Message:
CWE ID: CWE-189 | SplashBitmap::SplashBitmap(int widthA, int heightA, int rowPad,
SplashColorMode modeA, GBool alphaA,
GBool topDown) {
width = widthA;
height = heightA;
mode = modeA;
switch (mode) {
case splashModeMono1:
rowSize = (width + 7) >> 3;
break;
case splashModeMono8:
rowSize = width;
break;
case splashModeRGB8:
case splashModeBGR8:
rowSize = width * 3;
break;
case splashModeXBGR8:
rowSize = width * 4;
break;
#if SPLASH_CMYK
case splashModeCMYK8:
rowSize = width * 4;
break;
#endif
}
rowSize += rowPad - 1;
rowSize -= rowSize % rowPad;
data = (SplashColorPtr)gmallocn(rowSize, height);
if (!topDown) {
data += (height - 1) * rowSize;
rowSize = -rowSize;
}
if (alphaA) {
alpha = (Guchar *)gmallocn(width, height);
} else {
alpha = NULL;
}
}
| 164,620 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool DataReductionProxySettings::IsDataReductionProxyManaged() {
return spdy_proxy_auth_enabled_.IsManaged();
}
Commit Message: Move IsDataSaverEnabledByUser to be a static method and use it
This method now officially becomes the source of truth that
everything in the code base eventually calls into to determine whether
or not DataSaver is enabled.
Bug: 934399
Change-Id: Iae837b710ace8cc3101188f79d02cbc2d4f0fd93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1537242
Reviewed-by: Joshua Pawlicki <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Commit-Queue: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#643948}
CWE ID: CWE-119 | bool DataReductionProxySettings::IsDataReductionProxyManaged() {
const PrefService::Preference* pref =
GetOriginalProfilePrefs()->FindPreference(prefs::kDataSaverEnabled);
return pref && pref->IsManaged();
}
| 172,555 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 su3000_power_ctrl(struct dvb_usb_device *d, int i)
{
struct dw2102_state *state = (struct dw2102_state *)d->priv;
u8 obuf[] = {0xde, 0};
info("%s: %d, initialized %d", __func__, i, state->initialized);
if (i && !state->initialized) {
state->initialized = 1;
/* reset board */
return dvb_usb_generic_rw(d, obuf, 2, NULL, 0, 0);
}
return 0;
}
Commit Message: [media] dw2102: don't do DMA on stack
On Kernel 4.9, WARNINGs about doing DMA on stack are hit at
the dw2102 driver: one in su3000_power_ctrl() and the other in tt_s2_4600_frontend_attach().
Both were due to the use of buffers on the stack as parameters to
dvb_usb_generic_rw() and the resulting attempt to do DMA with them.
The device was non-functional as a result.
So, switch this driver over to use a buffer within the device state
structure, as has been done with other DVB-USB drivers.
Tested with TechnoTrend TT-connect S2-4600.
[[email protected]: fixed a warning at su3000_i2c_transfer() that
state var were dereferenced before check 'd']
Signed-off-by: Jonathan McDowell <[email protected]>
Cc: <[email protected]>
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-119 | static int su3000_power_ctrl(struct dvb_usb_device *d, int i)
{
struct dw2102_state *state = (struct dw2102_state *)d->priv;
int ret = 0;
info("%s: %d, initialized %d", __func__, i, state->initialized);
if (i && !state->initialized) {
mutex_lock(&d->data_mutex);
state->data[0] = 0xde;
state->data[1] = 0;
state->initialized = 1;
/* reset board */
ret = dvb_usb_generic_rw(d, state->data, 2, NULL, 0, 0);
mutex_unlock(&d->data_mutex);
}
return ret;
}
| 168,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
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 | I18NCustomBindings::I18NCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction(
"GetL10nMessage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nMessage, base::Unretained(this)));
RouteFunction("GetL10nUILanguage", "i18n",
base::Bind(&I18NCustomBindings::GetL10nUILanguage,
base::Unretained(this)));
RouteFunction("DetectTextLanguage", "i18n",
base::Bind(&I18NCustomBindings::DetectTextLanguage,
base::Unretained(this)));
}
| 172,249 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int do_video_set_spu_palette(unsigned int fd, unsigned int cmd,
struct compat_video_spu_palette __user *up)
{
struct video_spu_palette __user *up_native;
compat_uptr_t palp;
int length, err;
err = get_user(palp, &up->palette);
err |= get_user(length, &up->length);
up_native = compat_alloc_user_space(sizeof(struct video_spu_palette));
err = put_user(compat_ptr(palp), &up_native->palette);
err |= put_user(length, &up_native->length);
if (err)
return -EFAULT;
err = sys_ioctl(fd, cmd, (unsigned long) up_native);
return err;
}
Commit Message: fs/compat_ioctl.c: VIDEO_SET_SPU_PALETTE missing error check
The compat ioctl for VIDEO_SET_SPU_PALETTE was missing an error check
while converting ioctl arguments. This could lead to leaking kernel
stack contents into userspace.
Patch extracted from existing fix in grsecurity.
Signed-off-by: Kees Cook <[email protected]>
Cc: David Miller <[email protected]>
Cc: Brad Spengler <[email protected]>
Cc: PaX Team <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static int do_video_set_spu_palette(unsigned int fd, unsigned int cmd,
struct compat_video_spu_palette __user *up)
{
struct video_spu_palette __user *up_native;
compat_uptr_t palp;
int length, err;
err = get_user(palp, &up->palette);
err |= get_user(length, &up->length);
if (err)
return -EFAULT;
up_native = compat_alloc_user_space(sizeof(struct video_spu_palette));
err = put_user(compat_ptr(palp), &up_native->palette);
err |= put_user(length, &up_native->length);
if (err)
return -EFAULT;
err = sys_ioctl(fd, cmd, (unsigned long) up_native);
return err;
}
| 166,102 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: EntrySync* EntrySync::moveTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
RefPtr<EntrySyncCallbackHelper> helper = EntrySyncCallbackHelper::create();
m_fileSystem->move(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
Commit Message: Oilpan: Ship Oilpan for SyncCallbackHelper, CreateFileResult and CallbackWrapper in filesystem/
These are leftovers when we shipped Oilpan for filesystem/ once.
BUG=340522
Review URL: https://codereview.chromium.org/501263003
git-svn-id: svn://svn.chromium.org/blink/trunk@180909 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | EntrySync* EntrySync::moveTo(DirectoryEntrySync* parent, const String& name, ExceptionState& exceptionState) const
{
EntrySyncCallbackHelper* helper = EntrySyncCallbackHelper::create();
m_fileSystem->move(this, parent, name, helper->successCallback(), helper->errorCallback(), DOMFileSystemBase::Synchronous);
return helper->getResult(exceptionState);
}
| 171,422 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct sock *dccp_v6_request_recv_sock(struct sock *sk,
struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
struct inet6_request_sock *ireq6 = inet6_rsk(req);
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct inet_sock *newinet;
struct dccp6_sock *newdp6;
struct sock *newsk;
struct ipv6_txoptions *opt;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = dccp_v4_request_recv_sock(sk, skb, req, dst);
if (newsk == NULL)
return NULL;
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
ipv6_addr_set_v4mapped(newinet->inet_daddr, &newnp->daddr);
ipv6_addr_set_v4mapped(newinet->inet_saddr, &newnp->saddr);
ipv6_addr_copy(&newnp->rcv_saddr, &newnp->saddr);
inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;
newsk->sk_backlog_rcv = dccp_v4_do_rcv;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, dccp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
opt = np->opt;
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (dst == NULL) {
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_DCCP;
ipv6_addr_copy(&fl6.daddr, &ireq6->rmt_addr);
final_p = fl6_update_dst(&fl6, opt, &final);
ipv6_addr_copy(&fl6.saddr, &ireq6->loc_addr);
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.fl6_dport = inet_rsk(req)->rmt_port;
fl6.fl6_sport = inet_rsk(req)->loc_port;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p, false);
if (IS_ERR(dst))
goto out;
}
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, dccp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
__ip6_dst_store(newsk, dst, NULL, NULL);
newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |
NETIF_F_TSO);
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
ipv6_addr_copy(&newnp->daddr, &ireq6->rmt_addr);
ipv6_addr_copy(&newnp->saddr, &ireq6->loc_addr);
ipv6_addr_copy(&newnp->rcv_saddr, &ireq6->loc_addr);
newsk->sk_bound_dev_if = ireq6->iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->opt = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
/* Clone pktoptions received with SYN */
newnp->pktoptions = NULL;
if (ireq6->pktopts != NULL) {
newnp->pktoptions = skb_clone(ireq6->pktopts, GFP_ATOMIC);
kfree_skb(ireq6->pktopts);
ireq6->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* Clone native IPv6 options from listening socket (if any)
*
* Yes, keeping reference count would be much more clever, but we make
* one more one thing there: reattach optmem to newsk.
*/
if (opt != NULL) {
newnp->opt = ipv6_dup_options(newsk, opt);
if (opt != np->opt)
sock_kfree_s(sk, opt, opt->tot_len);
}
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (newnp->opt != NULL)
inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen +
newnp->opt->opt_flen);
dccp_sync_mss(newsk, dst_mtu(dst));
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (__inet_inherit_port(sk, newsk) < 0) {
sock_put(newsk);
goto out;
}
__inet6_hash(newsk, NULL);
return newsk;
out_overflow:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
if (opt != NULL && opt != np->opt)
sock_kfree_s(sk, opt, opt->tot_len);
return NULL;
}
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 | static struct sock *dccp_v6_request_recv_sock(struct sock *sk,
struct sk_buff *skb,
struct request_sock *req,
struct dst_entry *dst)
{
struct inet6_request_sock *ireq6 = inet6_rsk(req);
struct ipv6_pinfo *newnp, *np = inet6_sk(sk);
struct inet_sock *newinet;
struct dccp6_sock *newdp6;
struct sock *newsk;
struct ipv6_txoptions *opt;
if (skb->protocol == htons(ETH_P_IP)) {
/*
* v6 mapped
*/
newsk = dccp_v4_request_recv_sock(sk, skb, req, dst);
if (newsk == NULL)
return NULL;
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
ipv6_addr_set_v4mapped(newinet->inet_daddr, &newnp->daddr);
ipv6_addr_set_v4mapped(newinet->inet_saddr, &newnp->saddr);
ipv6_addr_copy(&newnp->rcv_saddr, &newnp->saddr);
inet_csk(newsk)->icsk_af_ops = &dccp_ipv6_mapped;
newsk->sk_backlog_rcv = dccp_v4_do_rcv;
newnp->pktoptions = NULL;
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks count
* here, dccp_create_openreq_child now does this for us, see the comment in
* that function for the gory details. -acme
*/
/* It is tricky place. Until this moment IPv4 tcp
worked with IPv6 icsk.icsk_af_ops.
Sync it now.
*/
dccp_sync_mss(newsk, inet_csk(newsk)->icsk_pmtu_cookie);
return newsk;
}
opt = np->opt;
if (sk_acceptq_is_full(sk))
goto out_overflow;
if (dst == NULL) {
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = IPPROTO_DCCP;
ipv6_addr_copy(&fl6.daddr, &ireq6->rmt_addr);
final_p = fl6_update_dst(&fl6, opt, &final);
ipv6_addr_copy(&fl6.saddr, &ireq6->loc_addr);
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.fl6_dport = inet_rsk(req)->rmt_port;
fl6.fl6_sport = inet_rsk(req)->loc_port;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p, false);
if (IS_ERR(dst))
goto out;
}
newsk = dccp_create_openreq_child(sk, req, skb);
if (newsk == NULL)
goto out_nonewsk;
/*
* No need to charge this sock to the relevant IPv6 refcnt debug socks
* count here, dccp_create_openreq_child now does this for us, see the
* comment in that function for the gory details. -acme
*/
__ip6_dst_store(newsk, dst, NULL, NULL);
newsk->sk_route_caps = dst->dev->features & ~(NETIF_F_IP_CSUM |
NETIF_F_TSO);
newdp6 = (struct dccp6_sock *)newsk;
newinet = inet_sk(newsk);
newinet->pinet6 = &newdp6->inet6;
newnp = inet6_sk(newsk);
memcpy(newnp, np, sizeof(struct ipv6_pinfo));
ipv6_addr_copy(&newnp->daddr, &ireq6->rmt_addr);
ipv6_addr_copy(&newnp->saddr, &ireq6->loc_addr);
ipv6_addr_copy(&newnp->rcv_saddr, &ireq6->loc_addr);
newsk->sk_bound_dev_if = ireq6->iif;
/* Now IPv6 options...
First: no IPv4 options.
*/
newinet->inet_opt = NULL;
/* Clone RX bits */
newnp->rxopt.all = np->rxopt.all;
/* Clone pktoptions received with SYN */
newnp->pktoptions = NULL;
if (ireq6->pktopts != NULL) {
newnp->pktoptions = skb_clone(ireq6->pktopts, GFP_ATOMIC);
kfree_skb(ireq6->pktopts);
ireq6->pktopts = NULL;
if (newnp->pktoptions)
skb_set_owner_r(newnp->pktoptions, newsk);
}
newnp->opt = NULL;
newnp->mcast_oif = inet6_iif(skb);
newnp->mcast_hops = ipv6_hdr(skb)->hop_limit;
/*
* Clone native IPv6 options from listening socket (if any)
*
* Yes, keeping reference count would be much more clever, but we make
* one more one thing there: reattach optmem to newsk.
*/
if (opt != NULL) {
newnp->opt = ipv6_dup_options(newsk, opt);
if (opt != np->opt)
sock_kfree_s(sk, opt, opt->tot_len);
}
inet_csk(newsk)->icsk_ext_hdr_len = 0;
if (newnp->opt != NULL)
inet_csk(newsk)->icsk_ext_hdr_len = (newnp->opt->opt_nflen +
newnp->opt->opt_flen);
dccp_sync_mss(newsk, dst_mtu(dst));
newinet->inet_daddr = newinet->inet_saddr = LOOPBACK4_IPV6;
newinet->inet_rcv_saddr = LOOPBACK4_IPV6;
if (__inet_inherit_port(sk, newsk) < 0) {
sock_put(newsk);
goto out;
}
__inet6_hash(newsk, NULL);
return newsk;
out_overflow:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS);
out_nonewsk:
dst_release(dst);
out:
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_LISTENDROPS);
if (opt != NULL && opt != np->opt)
sock_kfree_s(sk, opt, opt->tot_len);
return NULL;
}
| 165,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: Cluster* Cluster::Create(Segment* pSegment, long idx, long long off)
{
assert(pSegment);
assert(off >= 0);
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster = new Cluster(pSegment, idx, element_start);
assert(pCluster);
return pCluster;
}
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 | Cluster* Cluster::Create(Segment* pSegment, long idx, long long off)
Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) {
if (!pSegment || off < 0)
return NULL;
const long long element_start = pSegment->m_start + off;
Cluster* const pCluster =
new (std::nothrow) Cluster(pSegment, idx, element_start);
return pCluster;
}
| 173,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: QString IRCView::openTags(TextHtmlData* data, int from)
{
QString ret, tag;
int i = from;
for ( ; i < data->openHtmlTags.count(); ++i)
{
tag = data->openHtmlTags.at(i);
if (data->reverse)
{
ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name());
}
else
{
ret += fontColorOpenTag(data->lastFgColor);
}
}
else if (tag == QLatin1String("span"))
{
if (data->reverse)
{
ret += spanColorOpenTag(data->defaultColor);
}
else
{
ret += spanColorOpenTag(data->lastBgColor);
}
}
else
{
ret += QLatin1Char('<') + tag + QLatin1Char('>');
}
}
Commit Message:
CWE ID: | QString IRCView::openTags(TextHtmlData* data, int from)
{
QString ret, tag;
int i = from > -1 ? from : 0;
for ( ; i < data->openHtmlTags.count(); ++i)
{
tag = data->openHtmlTags.at(i);
if (data->reverse)
{
ret += fontColorOpenTag(Preferences::self()->color(Preferences::TextViewBackground).name());
}
else
{
ret += fontColorOpenTag(data->lastFgColor);
}
}
else if (tag == QLatin1String("span"))
{
if (data->reverse)
{
ret += spanColorOpenTag(data->defaultColor);
}
else
{
ret += spanColorOpenTag(data->lastBgColor);
}
}
else
{
ret += QLatin1Char('<') + tag + QLatin1Char('>');
}
}
| 164,649 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: unsigned long long Track::GetUid() const
{
return m_info.uid;
}
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 | unsigned long long Track::GetUid() const
| 174,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: AppCache::AppCache(AppCacheStorage* storage, int64_t cache_id)
: cache_id_(cache_id),
owning_group_(nullptr),
online_whitelist_all_(false),
is_complete_(false),
cache_size_(0),
storage_(storage) {
storage_->working_set()->AddCache(this);
}
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 | AppCache::AppCache(AppCacheStorage* storage, int64_t cache_id)
: cache_id_(cache_id),
owning_group_(nullptr),
online_whitelist_all_(false),
is_complete_(false),
cache_size_(0),
padding_size_(0),
storage_(storage) {
storage_->working_set()->AddCache(this);
}
| 172,969 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ExtensionService::IsDownloadFromGallery(const GURL& download_url,
const GURL& referrer_url) {
if (IsDownloadFromMiniGallery(download_url) &&
StartsWithASCII(referrer_url.spec(),
extension_urls::kMiniGalleryBrowsePrefix, false)) {
return true;
}
const Extension* download_extension = GetExtensionByWebExtent(download_url);
const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url);
const Extension* webstore_app = GetWebStoreApp();
bool referrer_valid = (referrer_extension == webstore_app);
bool download_valid = (download_extension == webstore_app);
GURL store_url =
GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kAppsGalleryURL));
if (!store_url.is_empty()) {
std::string store_tld =
net::RegistryControlledDomainService::GetDomainAndRegistry(store_url);
if (!referrer_valid) {
std::string referrer_tld =
net::RegistryControlledDomainService::GetDomainAndRegistry(
referrer_url);
referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld);
}
if (!download_valid) {
std::string download_tld =
net::RegistryControlledDomainService::GetDomainAndRegistry(
download_url);
download_valid = (download_tld == store_tld);
}
}
return (referrer_valid && download_valid);
}
Commit Message: Limit extent of webstore app to just chrome.google.com/webstore.
BUG=93497
TEST=Try installing extensions and apps from the webstore, starting both being
initially logged in, and not.
Review URL: http://codereview.chromium.org/7719003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool ExtensionService::IsDownloadFromGallery(const GURL& download_url,
const GURL& referrer_url) {
if (IsDownloadFromMiniGallery(download_url) &&
StartsWithASCII(referrer_url.spec(),
extension_urls::kMiniGalleryBrowsePrefix, false)) {
return true;
}
const Extension* download_extension = GetExtensionByWebExtent(download_url);
const Extension* referrer_extension = GetExtensionByWebExtent(referrer_url);
const Extension* webstore_app = GetWebStoreApp();
bool referrer_valid = (referrer_extension == webstore_app);
bool download_valid = (download_extension == webstore_app);
// We also allow the download to be from a small set of trusted paths.
if (!download_valid) {
for (size_t i = 0; i < arraysize(kAllowedDownloadURLPatterns); i++) {
URLPattern pattern(URLPattern::SCHEME_HTTPS,
kAllowedDownloadURLPatterns[i]);
if (pattern.MatchesURL(download_url)) {
download_valid = true;
break;
}
}
}
GURL store_url =
GURL(CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kAppsGalleryURL));
if (!store_url.is_empty()) {
std::string store_tld =
net::RegistryControlledDomainService::GetDomainAndRegistry(store_url);
if (!referrer_valid) {
std::string referrer_tld =
net::RegistryControlledDomainService::GetDomainAndRegistry(
referrer_url);
referrer_valid = referrer_url.is_empty() || (referrer_tld == store_tld);
}
if (!download_valid) {
std::string download_tld =
net::RegistryControlledDomainService::GetDomainAndRegistry(
download_url);
download_valid = (download_tld == store_tld);
}
}
return (referrer_valid && download_valid);
}
| 170,320 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BGD_DECLARE(void *) gdImageWebpPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (out == NULL) {
return NULL;
}
gdImageWebpCtx(im, out, -1);
rv = gdDPExtractData(out, size);
out->gd_free(out);
return rv;
}
Commit Message: Fix double-free in gdImageWebPtr()
The issue is that gdImageWebpCtx() (which is called by gdImageWebpPtr() and
the other WebP output functions to do the real work) does not return whether
it succeeded or failed, so this is not checked in gdImageWebpPtr() and the
function wrongly assumes everything is okay, which is not, in this case,
because there is a size limitation for WebP, namely that the width and
height must by less than 16383.
We can't change the signature of gdImageWebpCtx() for API compatibility
reasons, so we introduce the static helper _gdImageWebpCtx() which returns
success respective failure, so gdImageWebpPtr() and gdImageWebpPtrEx() can
check the return value. We leave it solely to libwebp for now to report
warnings regarding the failing write.
This issue had been reported by Ibrahim El-Sayed to [email protected].
CVE-2016-6912
CWE ID: CWE-415 | BGD_DECLARE(void *) gdImageWebpPtr (gdImagePtr im, int *size)
{
void *rv;
gdIOCtx *out = gdNewDynamicCtx(2048, NULL);
if (out == NULL) {
return NULL;
}
if (_gdImageWebpCtx(im, out, -1)) {
rv = NULL;
} else {
rv = gdDPExtractData(out, size);
}
out->gd_free(out);
return rv;
}
| 168,819 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftGSM::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nSamplingRate != 8000) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.gsm",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftGSM::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex != 0 && pcmParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nChannels != 1) {
return OMX_ErrorUndefined;
}
if (pcmParams->nSamplingRate != 8000) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.gsm",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,208 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
first = mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
next = mask->end_point;
FT_Int count;
next = mask->end_point;
count = next - first;
if ( count > 0 )
{
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
Commit Message:
CWE ID: CWE-399 | psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
/* the `endchar' op can reduce the number of points */
first = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
next = mask->end_point;
FT_Int count;
next = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
count = next - first;
if ( count > 0 )
{
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
| 165,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ExtensionTtsSpeakFunction::RunImpl() {
std::string text;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &text));
DictionaryValue* options = NULL;
if (args_->GetSize() >= 2)
EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &options));
Task* completion_task = NewRunnableMethod(
this, &ExtensionTtsSpeakFunction::SpeechFinished);
utterance_ = new Utterance(profile(), text, options, completion_task);
AddRef(); // Balanced in SpeechFinished().
ExtensionTtsController::GetInstance()->SpeakOrEnqueue(utterance_);
return true;
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | bool ExtensionTtsSpeakFunction::RunImpl() {
int src_id = -1;
EXTENSION_FUNCTION_VALIDATE(
options->GetInteger(constants::kSrcIdKey, &src_id));
// If we got this far, the arguments were all in the valid format, so
// send the success response to the callback now - this ensures that
// the callback response always arrives before events, which makes
// the behavior more predictable and easier to write unit tests for too.
SendResponse(true);
UtteranceContinuousParameters continuous_params;
continuous_params.rate = rate;
continuous_params.pitch = pitch;
continuous_params.volume = volume;
Utterance* utterance = new Utterance(profile());
utterance->set_text(text);
utterance->set_voice_name(voice_name);
utterance->set_src_extension_id(extension_id());
utterance->set_src_id(src_id);
utterance->set_src_url(source_url());
utterance->set_lang(lang);
utterance->set_gender(gender);
utterance->set_continuous_parameters(continuous_params);
utterance->set_can_enqueue(can_enqueue);
utterance->set_required_event_types(required_event_types);
utterance->set_desired_event_types(desired_event_types);
utterance->set_extension_id(voice_extension_id);
utterance->set_options(options.get());
ExtensionTtsController* controller = ExtensionTtsController::GetInstance();
controller->SpeakOrEnqueue(utterance);
return true;
}
| 170,384 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MultibufferDataSource::StartCallback() {
DCHECK(render_task_runner_->BelongsToCurrentThread());
if (!init_cb_) {
SetReader(nullptr);
return;
}
bool success = reader_ && reader_->Available() > 0 && url_data() &&
(!assume_fully_buffered() ||
url_data()->length() != kPositionNotSpecified);
if (success) {
{
base::AutoLock auto_lock(lock_);
total_bytes_ = url_data()->length();
}
streaming_ =
!assume_fully_buffered() && (total_bytes_ == kPositionNotSpecified ||
!url_data()->range_supported());
media_log_->SetDoubleProperty("total_bytes",
static_cast<double>(total_bytes_));
media_log_->SetBooleanProperty("streaming", streaming_);
} else {
SetReader(nullptr);
}
base::AutoLock auto_lock(lock_);
if (stop_signal_received_)
return;
if (success) {
if (total_bytes_ != kPositionNotSpecified) {
host_->SetTotalBytes(total_bytes_);
if (assume_fully_buffered())
host_->AddBufferedByteRange(0, total_bytes_);
}
media_log_->SetBooleanProperty("single_origin", single_origin_);
media_log_->SetBooleanProperty("passed_cors_access_check",
DidPassCORSAccessCheck());
media_log_->SetBooleanProperty("range_header_supported",
url_data()->range_supported());
}
render_task_runner_->PostTask(FROM_HERE,
base::Bind(std::move(init_cb_), success));
UpdateBufferSizes();
UpdateLoadingState_Locked(true);
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | void MultibufferDataSource::StartCallback() {
DCHECK(render_task_runner_->BelongsToCurrentThread());
if (!init_cb_) {
SetReader(nullptr);
return;
}
bool success = reader_ && reader_->Available() > 0 && url_data() &&
(!assume_fully_buffered() ||
url_data()->length() != kPositionNotSpecified);
if (success) {
{
base::AutoLock auto_lock(lock_);
total_bytes_ = url_data()->length();
}
streaming_ =
!assume_fully_buffered() && (total_bytes_ == kPositionNotSpecified ||
!url_data()->range_supported());
media_log_->SetDoubleProperty("total_bytes",
static_cast<double>(total_bytes_));
media_log_->SetBooleanProperty("streaming", streaming_);
} else {
SetReader(nullptr);
}
base::AutoLock auto_lock(lock_);
if (stop_signal_received_)
return;
if (success) {
if (total_bytes_ != kPositionNotSpecified) {
host_->SetTotalBytes(total_bytes_);
if (assume_fully_buffered())
host_->AddBufferedByteRange(0, total_bytes_);
}
media_log_->SetBooleanProperty("single_origin", single_origin_);
media_log_->SetBooleanProperty("range_header_supported",
url_data()->range_supported());
}
render_task_runner_->PostTask(FROM_HERE,
base::Bind(std::move(init_cb_), success));
UpdateBufferSizes();
UpdateLoadingState_Locked(true);
}
| 172,625 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ExtensionFunction::ResponseAction BluetoothSocketSendFunction::Run() {
DCHECK_CURRENTLY_ON(work_thread_id());
auto params = bluetooth_socket::Send::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params.get());
io_buffer_size_ = params->data.size();
io_buffer_ = new net::WrappedIOBuffer(params->data.data());
BluetoothApiSocket* socket = GetSocket(params->socket_id);
if (!socket)
return RespondNow(Error(kSocketNotFoundError));
socket->Send(io_buffer_,
io_buffer_size_,
base::Bind(&BluetoothSocketSendFunction::OnSuccess, this),
base::Bind(&BluetoothSocketSendFunction::OnError, this));
return did_respond() ? AlreadyResponded() : RespondLater();
}
Commit Message: chrome.bluetoothSocket: Fix regression in send()
In https://crrev.com/c/997098, params_ was changed to a local variable,
but it needs to last longer than that since net::WrappedIOBuffer may use
the data after the local variable goes out of scope.
This CL changed it back to be an instance variable.
Bug: 851799
Change-Id: I392f8acaef4c6473d6ea4fbee7209445aa09112e
Reviewed-on: https://chromium-review.googlesource.com/1103676
Reviewed-by: Toni Barzic <[email protected]>
Commit-Queue: Sonny Sasaka <[email protected]>
Cr-Commit-Position: refs/heads/master@{#568137}
CWE ID: CWE-416 | ExtensionFunction::ResponseAction BluetoothSocketSendFunction::Run() {
DCHECK_CURRENTLY_ON(work_thread_id());
params_ = bluetooth_socket::Send::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
io_buffer_size_ = params_->data.size();
io_buffer_ = new net::WrappedIOBuffer(params_->data.data());
BluetoothApiSocket* socket = GetSocket(params_->socket_id);
if (!socket)
return RespondNow(Error(kSocketNotFoundError));
socket->Send(io_buffer_,
io_buffer_size_,
base::Bind(&BluetoothSocketSendFunction::OnSuccess, this),
base::Bind(&BluetoothSocketSendFunction::OnError, this));
return did_respond() ? AlreadyResponded() : RespondLater();
}
| 173,160 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 re_yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; // After all that talk, this was set to 1 anyways...
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476 | static void re_yyensure_buffer_stack (yyscan_t yyscanner)
{
yy_size_t num_to_alloc;
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (!yyg->yy_buffer_stack) {
/* First allocation is just for 2 elements, since we don't know if this
* scanner will even need a stack. We use 2 instead of 1 to avoid an
* immediate realloc on the next call.
*/
num_to_alloc = 1; // After all that talk, this was set to 1 anyways...
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyalloc
(num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
yyg->yy_buffer_stack_top = 0;
return;
}
if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){
/* Increase the buffer to prepare for a possible push. */
yy_size_t grow_size = 8 /* arbitrary grow size */;
num_to_alloc = yyg->yy_buffer_stack_max + grow_size;
yyg->yy_buffer_stack = (struct yy_buffer_state**)re_yyrealloc
(yyg->yy_buffer_stack,
num_to_alloc * sizeof(struct yy_buffer_state*)
, yyscanner);
if ( ! yyg->yy_buffer_stack )
YY_FATAL_ERROR( "out of dynamic memory in re_yyensure_buffer_stack()" );
/* zero only the new slots.*/
memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*));
yyg->yy_buffer_stack_max = num_to_alloc;
}
}
| 168,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SProcXFixesCreatePointerBarrier(ClientPtr client)
{
REQUEST(xXFixesCreatePointerBarrierReq);
int i;
int i;
CARD16 *in_devices = (CARD16 *) &stuff[1];
swaps(&stuff->length);
swaps(&stuff->num_devices);
REQUEST_FIXED_SIZE(xXFixesCreatePointerBarrierReq, pad_to_int32(stuff->num_devices));
swaps(&stuff->x1);
swaps(&stuff->y1);
swaps(&stuff->x2);
swaps(&stuff->y2);
swapl(&stuff->directions);
for (i = 0; i < stuff->num_devices; i++) {
swaps(in_devices + i);
}
return ProcXFixesVector[stuff->xfixesReqType] (client);
}
Commit Message:
CWE ID: CWE-20 | SProcXFixesCreatePointerBarrier(ClientPtr client)
{
REQUEST(xXFixesCreatePointerBarrierReq);
int i;
int i;
CARD16 *in_devices = (CARD16 *) &stuff[1];
REQUEST_AT_LEAST_SIZE(xXFixesCreatePointerBarrierReq);
swaps(&stuff->length);
swaps(&stuff->num_devices);
REQUEST_FIXED_SIZE(xXFixesCreatePointerBarrierReq, pad_to_int32(stuff->num_devices));
swaps(&stuff->x1);
swaps(&stuff->y1);
swaps(&stuff->x2);
swaps(&stuff->y2);
swapl(&stuff->directions);
for (i = 0; i < stuff->num_devices; i++) {
swaps(in_devices + i);
}
return ProcXFixesVector[stuff->xfixesReqType] (client);
}
| 165,440 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 RunAccuracyCheck() {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, kNumCoeffs);
DECLARE_ALIGNED_ARRAY(16, uint8_t, src, kNumCoeffs);
for (int j = 0; j < kNumCoeffs; ++j) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
}
REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
for (int j = 0; j < kNumCoeffs; ++j) {
const uint32_t diff = dst[j] - src[j];
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(1u, max_error)
<< "Error: 4x4 FHT/IHT has an individual round trip error > 1";
EXPECT_GE(count_test_block , total_error)
<< "Error: 4x4 FHT/IHT has average round trip error > 1 per block";
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void RunAccuracyCheck() {
void RunAccuracyCheck(int limit) {
ACMRandom rnd(ACMRandom::DeterministicSeed());
uint32_t max_error = 0;
int64_t total_error = 0;
const int count_test_block = 10000;
for (int i = 0; i < count_test_block; ++i) {
DECLARE_ALIGNED(16, int16_t, test_input_block[kNumCoeffs]);
DECLARE_ALIGNED(16, tran_low_t, test_temp_block[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]);
DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]);
#if CONFIG_VP9_HIGHBITDEPTH
DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]);
DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]);
#endif
for (int j = 0; j < kNumCoeffs; ++j) {
if (bit_depth_ == VPX_BITS_8) {
src[j] = rnd.Rand8();
dst[j] = rnd.Rand8();
test_input_block[j] = src[j] - dst[j];
#if CONFIG_VP9_HIGHBITDEPTH
} else {
src16[j] = rnd.Rand16() & mask_;
dst16[j] = rnd.Rand16() & mask_;
test_input_block[j] = src16[j] - dst16[j];
#endif
}
}
ASM_REGISTER_STATE_CHECK(RunFwdTxfm(test_input_block,
test_temp_block, pitch_));
if (bit_depth_ == VPX_BITS_8) {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block, dst, pitch_));
#if CONFIG_VP9_HIGHBITDEPTH
} else {
ASM_REGISTER_STATE_CHECK(RunInvTxfm(test_temp_block,
CONVERT_TO_BYTEPTR(dst16), pitch_));
#endif
}
for (int j = 0; j < kNumCoeffs; ++j) {
#if CONFIG_VP9_HIGHBITDEPTH
const uint32_t diff =
bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j];
#else
ASSERT_EQ(VPX_BITS_8, bit_depth_);
const uint32_t diff = dst[j] - src[j];
#endif
const uint32_t error = diff * diff;
if (max_error < error)
max_error = error;
total_error += error;
}
}
EXPECT_GE(static_cast<uint32_t>(limit), max_error)
<< "Error: 4x4 FHT/IHT has an individual round trip error > "
<< limit;
EXPECT_GE(count_test_block * limit, total_error)
<< "Error: 4x4 FHT/IHT has average round trip error > " << limit
<< " per block";
}
| 174,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t split,
int split_flag,
int flags)
{
ext4_fsblk_t newblock;
ext4_lblk_t ee_block;
struct ext4_extent *ex, newex, orig_ex;
struct ext4_extent *ex2 = NULL;
unsigned int ee_len, depth;
int err = 0;
ext_debug("ext4_split_extents_at: inode %lu, logical"
"block %llu\n", inode->i_ino, (unsigned long long)split);
ext4_ext_show_leaf(inode, path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
newblock = split - ee_block + ext4_ext_pblock(ex);
BUG_ON(split < ee_block || split >= (ee_block + ee_len));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
if (split == ee_block) {
/*
* case b: block @split is the block that the extent begins with
* then we just change the state of the extent, and splitting
* is not needed.
*/
if (split_flag & EXT4_EXT_MARK_UNINIT2)
ext4_ext_mark_uninitialized(ex);
else
ext4_ext_mark_initialized(ex);
if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
goto out;
}
/* case a */
memcpy(&orig_ex, ex, sizeof(orig_ex));
ex->ee_len = cpu_to_le16(split - ee_block);
if (split_flag & EXT4_EXT_MARK_UNINIT1)
ext4_ext_mark_uninitialized(ex);
/*
* path may lead to new leaf, not to original leaf any more
* after ext4_ext_insert_extent() returns,
*/
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto fix_extent_len;
ex2 = &newex;
ex2->ee_block = cpu_to_le32(split);
ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
ext4_ext_store_pblock(ex2, newblock);
if (split_flag & EXT4_EXT_MARK_UNINIT2)
ext4_ext_mark_uninitialized(ex2);
err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_len = cpu_to_le16(ee_len);
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
goto out;
} else if (err)
goto fix_extent_len;
out:
ext4_ext_show_leaf(inode, path);
return err;
fix_extent_len:
ex->ee_len = orig_ex.ee_len;
ext4_ext_dirty(handle, inode, path + depth);
return err;
}
Commit Message: ext4: race-condition protection for ext4_convert_unwritten_extents_endio
We assumed that at the time we call ext4_convert_unwritten_extents_endio()
extent in question is fully inside [map.m_lblk, map->m_len] because
it was already split during submission. But this may not be true due to
a race between writeback vs fallocate.
If extent in question is larger than requested we will split it again.
Special precautions should being done if zeroout required because
[map.m_lblk, map->m_len] already contains valid data.
Signed-off-by: Dmitry Monakhov <[email protected]>
Signed-off-by: "Theodore Ts'o" <[email protected]>
Cc: [email protected]
CWE ID: CWE-362 | static int ext4_split_extent_at(handle_t *handle,
struct inode *inode,
struct ext4_ext_path *path,
ext4_lblk_t split,
int split_flag,
int flags)
{
ext4_fsblk_t newblock;
ext4_lblk_t ee_block;
struct ext4_extent *ex, newex, orig_ex;
struct ext4_extent *ex2 = NULL;
unsigned int ee_len, depth;
int err = 0;
BUG_ON((split_flag & (EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2)) ==
(EXT4_EXT_DATA_VALID1 | EXT4_EXT_DATA_VALID2));
ext_debug("ext4_split_extents_at: inode %lu, logical"
"block %llu\n", inode->i_ino, (unsigned long long)split);
ext4_ext_show_leaf(inode, path);
depth = ext_depth(inode);
ex = path[depth].p_ext;
ee_block = le32_to_cpu(ex->ee_block);
ee_len = ext4_ext_get_actual_len(ex);
newblock = split - ee_block + ext4_ext_pblock(ex);
BUG_ON(split < ee_block || split >= (ee_block + ee_len));
err = ext4_ext_get_access(handle, inode, path + depth);
if (err)
goto out;
if (split == ee_block) {
/*
* case b: block @split is the block that the extent begins with
* then we just change the state of the extent, and splitting
* is not needed.
*/
if (split_flag & EXT4_EXT_MARK_UNINIT2)
ext4_ext_mark_uninitialized(ex);
else
ext4_ext_mark_initialized(ex);
if (!(flags & EXT4_GET_BLOCKS_PRE_IO))
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
goto out;
}
/* case a */
memcpy(&orig_ex, ex, sizeof(orig_ex));
ex->ee_len = cpu_to_le16(split - ee_block);
if (split_flag & EXT4_EXT_MARK_UNINIT1)
ext4_ext_mark_uninitialized(ex);
/*
* path may lead to new leaf, not to original leaf any more
* after ext4_ext_insert_extent() returns,
*/
err = ext4_ext_dirty(handle, inode, path + depth);
if (err)
goto fix_extent_len;
ex2 = &newex;
ex2->ee_block = cpu_to_le32(split);
ex2->ee_len = cpu_to_le16(ee_len - (split - ee_block));
ext4_ext_store_pblock(ex2, newblock);
if (split_flag & EXT4_EXT_MARK_UNINIT2)
ext4_ext_mark_uninitialized(ex2);
err = ext4_ext_insert_extent(handle, inode, path, &newex, flags);
if (err == -ENOSPC && (EXT4_EXT_MAY_ZEROOUT & split_flag)) {
if (split_flag & (EXT4_EXT_DATA_VALID1|EXT4_EXT_DATA_VALID2)) {
if (split_flag & EXT4_EXT_DATA_VALID1)
err = ext4_ext_zeroout(inode, ex2);
else
err = ext4_ext_zeroout(inode, ex);
} else
err = ext4_ext_zeroout(inode, &orig_ex);
if (err)
goto fix_extent_len;
/* update the extent length and mark as initialized */
ex->ee_len = cpu_to_le16(ee_len);
ext4_ext_try_to_merge(handle, inode, path, ex);
err = ext4_ext_dirty(handle, inode, path + path->p_depth);
goto out;
} else if (err)
goto fix_extent_len;
out:
ext4_ext_show_leaf(inode, path);
return err;
fix_extent_len:
ex->ee_len = orig_ex.ee_len;
ext4_ext_dirty(handle, inode, path + depth);
return err;
}
| 165,534 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNCNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
(xmlIsNameChar(ctxt, c) && (c != ':'))) {
if (count++ > 100) {
count = 0;
GROW;
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) {
int len = 0, l;
int c;
int count = 0;
#ifdef DEBUG
nbParseNCNameComplex++;
#endif
/*
* Handler for more complex cases
*/
GROW;
c = CUR_CHAR(l);
if ((c == ' ') || (c == '>') || (c == '/') || /* accelerators */
(!xmlIsNameStartChar(ctxt, c) || (c == ':'))) {
return(NULL);
}
while ((c != ' ') && (c != '>') && (c != '/') && /* test bigname.xml */
(xmlIsNameChar(ctxt, c) && (c != ':'))) {
if (count++ > 100) {
count = 0;
GROW;
if (ctxt->instate == XML_PARSER_EOF)
return(NULL);
}
len += l;
NEXTL(l);
c = CUR_CHAR(l);
}
return(xmlDictLookup(ctxt->dict, ctxt->input->cur - len, len));
}
| 171,295 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bit_catenate(VarBit *arg1, VarBit *arg2)
{
VarBit *result;
int bitlen1,
bitlen2,
bytelen,
bit1pad,
bit2shift;
bits8 *pr,
*pa;
bitlen1 = VARBITLEN(arg1);
bitlen2 = VARBITLEN(arg2);
bytelen = VARBITTOTALLEN(bitlen1 + bitlen2);
result = (VarBit *) palloc(bytelen);
SET_VARSIZE(result, bytelen);
VARBITLEN(result) = bitlen1 + bitlen2;
/* Copy the first bitstring in */
memcpy(VARBITS(result), VARBITS(arg1), VARBITBYTES(arg1));
/* Copy the second bit string */
bit1pad = VARBITPAD(arg1);
if (bit1pad == 0)
{
memcpy(VARBITS(result) + VARBITBYTES(arg1), VARBITS(arg2),
VARBITBYTES(arg2));
}
else if (bitlen2 > 0)
{
/* We need to shift all the bits to fit */
bit2shift = BITS_PER_BYTE - bit1pad;
pr = VARBITS(result) + VARBITBYTES(arg1) - 1;
for (pa = VARBITS(arg2); pa < VARBITEND(arg2); pa++)
{
*pr |= ((*pa >> bit2shift) & BITMASK);
pr++;
if (pr < VARBITEND(result))
*pr = (*pa << bit1pad) & BITMASK;
}
}
return result;
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | bit_catenate(VarBit *arg1, VarBit *arg2)
{
VarBit *result;
int bitlen1,
bitlen2,
bytelen,
bit1pad,
bit2shift;
bits8 *pr,
*pa;
bitlen1 = VARBITLEN(arg1);
bitlen2 = VARBITLEN(arg2);
if (bitlen1 > VARBITMAXLEN - bitlen2)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("bit string length exceeds the maximum allowed (%d)",
VARBITMAXLEN)));
bytelen = VARBITTOTALLEN(bitlen1 + bitlen2);
result = (VarBit *) palloc(bytelen);
SET_VARSIZE(result, bytelen);
VARBITLEN(result) = bitlen1 + bitlen2;
/* Copy the first bitstring in */
memcpy(VARBITS(result), VARBITS(arg1), VARBITBYTES(arg1));
/* Copy the second bit string */
bit1pad = VARBITPAD(arg1);
if (bit1pad == 0)
{
memcpy(VARBITS(result) + VARBITBYTES(arg1), VARBITS(arg2),
VARBITBYTES(arg2));
}
else if (bitlen2 > 0)
{
/* We need to shift all the bits to fit */
bit2shift = BITS_PER_BYTE - bit1pad;
pr = VARBITS(result) + VARBITBYTES(arg1) - 1;
for (pa = VARBITS(arg2); pa < VARBITEND(arg2); pa++)
{
*pr |= ((*pa >> bit2shift) & BITMASK);
pr++;
if (pr < VARBITEND(result))
*pr = (*pa << bit1pad) & BITMASK;
}
}
return result;
}
| 166,417 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 uint8_t excluded_channels(bitfile *ld, drc_info *drc)
{
uint8_t i, n = 0;
uint8_t num_excl_chan = 7;
for (i = 0; i < 7; i++)
{
drc->exclude_mask[i] = faad_get1bit(ld
DEBUGVAR(1,103,"excluded_channels(): exclude_mask"));
}
n++;
while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld
DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1)
{
for (i = num_excl_chan; i < num_excl_chan+7; i++)
{
drc->exclude_mask[i] = faad_get1bit(ld
DEBUGVAR(1,105,"excluded_channels(): exclude_mask"));
}
n++;
num_excl_chan += 7;
}
return n;
}
Commit Message: Fix a couple buffer overflows
https://hackerone.com/reports/502816
https://hackerone.com/reports/507858
https://github.com/videolan/vlc/blob/master/contrib/src/faad2/faad2-fix-overflows.patch
CWE ID: CWE-119 | static uint8_t excluded_channels(bitfile *ld, drc_info *drc)
{
uint8_t i, n = 0;
uint8_t num_excl_chan = 7;
for (i = 0; i < 7; i++)
{
drc->exclude_mask[i] = faad_get1bit(ld
DEBUGVAR(1,103,"excluded_channels(): exclude_mask"));
}
n++;
while ((drc->additional_excluded_chns[n-1] = faad_get1bit(ld
DEBUGVAR(1,104,"excluded_channels(): additional_excluded_chns"))) == 1)
{
if (i >= MAX_CHANNELS - num_excl_chan - 7)
return n;
for (i = num_excl_chan; i < num_excl_chan+7; i++)
{
drc->exclude_mask[i] = faad_get1bit(ld
DEBUGVAR(1,105,"excluded_channels(): exclude_mask"));
}
n++;
num_excl_chan += 7;
}
return n;
}
| 169,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: status_t FLACParser::init()
{
mDecoder = FLAC__stream_decoder_new();
if (mDecoder == NULL) {
ALOGE("new failed");
return NO_INIT;
}
FLAC__stream_decoder_set_md5_checking(mDecoder, false);
FLAC__stream_decoder_set_metadata_ignore_all(mDecoder);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_STREAMINFO);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_PICTURE);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
FLAC__StreamDecoderInitStatus initStatus;
initStatus = FLAC__stream_decoder_init_stream(
mDecoder,
read_callback, seek_callback, tell_callback,
length_callback, eof_callback, write_callback,
metadata_callback, error_callback, (void *) this);
if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
ALOGE("init_stream failed %d", initStatus);
return NO_INIT;
}
if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) {
ALOGE("end_of_metadata failed");
return NO_INIT;
}
if (mStreamInfoValid) {
if (getChannels() == 0 || getChannels() > 8) {
ALOGE("unsupported channel count %u", getChannels());
return NO_INIT;
}
switch (getBitsPerSample()) {
case 8:
case 16:
case 24:
break;
default:
ALOGE("unsupported bits per sample %u", getBitsPerSample());
return NO_INIT;
}
switch (getSampleRate()) {
case 8000:
case 11025:
case 12000:
case 16000:
case 22050:
case 24000:
case 32000:
case 44100:
case 48000:
case 88200:
case 96000:
break;
default:
ALOGE("unsupported sample rate %u", getSampleRate());
return NO_INIT;
}
static const struct {
unsigned mChannels;
unsigned mBitsPerSample;
void (*mCopy)(short *dst, const int *const *src, unsigned nSamples, unsigned nChannels);
} table[] = {
{ 1, 8, copyMono8 },
{ 2, 8, copyStereo8 },
{ 8, 8, copyMultiCh8 },
{ 1, 16, copyMono16 },
{ 2, 16, copyStereo16 },
{ 8, 16, copyMultiCh16 },
{ 1, 24, copyMono24 },
{ 2, 24, copyStereo24 },
{ 8, 24, copyMultiCh24 },
};
for (unsigned i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
if (table[i].mChannels >= getChannels() &&
table[i].mBitsPerSample == getBitsPerSample()) {
mCopy = table[i].mCopy;
break;
}
}
if (mTrackMetadata != 0) {
mTrackMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
mTrackMetadata->setInt32(kKeyChannelCount, getChannels());
mTrackMetadata->setInt32(kKeySampleRate, getSampleRate());
mTrackMetadata->setInt32(kKeyPcmEncoding, kAudioEncodingPcm16bit);
mTrackMetadata->setInt64(kKeyDuration,
(getTotalSamples() * 1000000LL) / getSampleRate());
}
} else {
ALOGE("missing STREAMINFO");
return NO_INIT;
}
if (mFileMetadata != 0) {
mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
}
return OK;
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | status_t FLACParser::init()
{
mDecoder = FLAC__stream_decoder_new();
if (mDecoder == NULL) {
ALOGE("new failed");
return NO_INIT;
}
FLAC__stream_decoder_set_md5_checking(mDecoder, false);
FLAC__stream_decoder_set_metadata_ignore_all(mDecoder);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_STREAMINFO);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_PICTURE);
FLAC__stream_decoder_set_metadata_respond(
mDecoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);
FLAC__StreamDecoderInitStatus initStatus;
initStatus = FLAC__stream_decoder_init_stream(
mDecoder,
read_callback, seek_callback, tell_callback,
length_callback, eof_callback, write_callback,
metadata_callback, error_callback, (void *) this);
if (initStatus != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
ALOGE("init_stream failed %d", initStatus);
return NO_INIT;
}
if (!FLAC__stream_decoder_process_until_end_of_metadata(mDecoder)) {
ALOGE("end_of_metadata failed");
return NO_INIT;
}
if (mStreamInfoValid) {
if (getChannels() == 0 || getChannels() > kMaxChannels) {
ALOGE("unsupported channel count %u", getChannels());
return NO_INIT;
}
switch (getBitsPerSample()) {
case 8:
case 16:
case 24:
break;
default:
ALOGE("unsupported bits per sample %u", getBitsPerSample());
return NO_INIT;
}
switch (getSampleRate()) {
case 8000:
case 11025:
case 12000:
case 16000:
case 22050:
case 24000:
case 32000:
case 44100:
case 48000:
case 88200:
case 96000:
break;
default:
ALOGE("unsupported sample rate %u", getSampleRate());
return NO_INIT;
}
static const struct {
unsigned mChannels;
unsigned mBitsPerSample;
void (*mCopy)(short *dst, const int * src[kMaxChannels], unsigned nSamples, unsigned nChannels);
} table[] = {
{ 1, 8, copyMono8 },
{ 2, 8, copyStereo8 },
{ 8, 8, copyMultiCh8 },
{ 1, 16, copyMono16 },
{ 2, 16, copyStereo16 },
{ 8, 16, copyMultiCh16 },
{ 1, 24, copyMono24 },
{ 2, 24, copyStereo24 },
{ 8, 24, copyMultiCh24 },
};
for (unsigned i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
if (table[i].mChannels >= getChannels() &&
table[i].mBitsPerSample == getBitsPerSample()) {
mCopy = table[i].mCopy;
break;
}
}
if (mTrackMetadata != 0) {
mTrackMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_RAW);
mTrackMetadata->setInt32(kKeyChannelCount, getChannels());
mTrackMetadata->setInt32(kKeySampleRate, getSampleRate());
mTrackMetadata->setInt32(kKeyPcmEncoding, kAudioEncodingPcm16bit);
mTrackMetadata->setInt64(kKeyDuration,
(getTotalSamples() * 1000000LL) / getSampleRate());
}
} else {
ALOGE("missing STREAMINFO");
return NO_INIT;
}
if (mFileMetadata != 0) {
mFileMetadata->setCString(kKeyMIMEType, MEDIA_MIMETYPE_AUDIO_FLAC);
}
return OK;
}
| 174,025 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: restore_page_device(const gs_gstate * pgs_old, const gs_gstate * pgs_new)
{
gx_device *dev_old = gs_currentdevice(pgs_old);
gx_device *dev_new;
gx_device *dev_t1;
gx_device *dev_t2;
bool samepagedevice = obj_eq(dev_old->memory, &gs_int_gstate(pgs_old)->pagedevice,
&gs_int_gstate(pgs_new)->pagedevice);
if ((dev_t1 = (*dev_proc(dev_old, get_page_device)) (dev_old)) == 0)
return false;
/* If we are going to putdeviceparams in a callout, we need to */
/* unlock temporarily. The device will be re-locked as needed */
/* by putdeviceparams from the pgs_old->pagedevice dict state. */
dev_old->LockSafetyParams = false;
dev_new = gs_currentdevice(pgs_new);
dev_new = gs_currentdevice(pgs_new);
if (dev_old != dev_new) {
if ((dev_t2 = (*dev_proc(dev_new, get_page_device)) (dev_new)) == 0)
return false;
if (dev_t1 != dev_t2)
return true;
}
/*
* The current implementation of setpagedevice just sets new
* parameters in the same device object, so we have to check
* whether the page device dictionaries are the same.
*/
return !samepagedevice;
}
Commit Message:
CWE ID: | restore_page_device(const gs_gstate * pgs_old, const gs_gstate * pgs_new)
static int
restore_page_device(i_ctx_t *i_ctx_p, const gs_gstate * pgs_old, const gs_gstate * pgs_new)
{
gx_device *dev_old = gs_currentdevice(pgs_old);
gx_device *dev_new;
gx_device *dev_t1;
gx_device *dev_t2;
bool samepagedevice = obj_eq(dev_old->memory, &gs_int_gstate(pgs_old)->pagedevice,
&gs_int_gstate(pgs_new)->pagedevice);
bool LockSafetyParams = dev_old->LockSafetyParams;
if ((dev_t1 = (*dev_proc(dev_old, get_page_device)) (dev_old)) == 0)
return 0;
/* If we are going to putdeviceparams in a callout, we need to */
/* unlock temporarily. The device will be re-locked as needed */
/* by putdeviceparams from the pgs_old->pagedevice dict state. */
dev_old->LockSafetyParams = false;
dev_new = gs_currentdevice(pgs_new);
dev_new = gs_currentdevice(pgs_new);
if (dev_old != dev_new) {
if ((dev_t2 = (*dev_proc(dev_new, get_page_device)) (dev_new)) == 0)
samepagedevice = true;
else if (dev_t1 != dev_t2)
samepagedevice = false;
}
if (LockSafetyParams && !samepagedevice) {
os_ptr op = osp;
const int max_ops = 512;
/* The %grestorepagedevice must complete: the biggest danger
is operand stack overflow. As we use get/putdeviceparams
that means pushing all the device params onto the stack,
pdfwrite having by far the largest number of parameters
at (currently) 212 key/value pairs - thus needing (currently)
424 entries on the op stack. Allowing for working stack
space, and safety margin.....
*/
if (max_ops > op - osbot) {
if (max_ops >= ref_stack_count(&o_stack))
return_error(gs_error_stackoverflow);
}
}
/*
* The current implementation of setpagedevice just sets new
* parameters in the same device object, so we have to check
* whether the page device dictionaries are the same.
*/
return samepagedevice ? 0 : 1;
}
| 164,690 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BrowserDevToolsAgentHost::AttachSession(DevToolsSession* session) {
session->SetBrowserOnly(true);
session->AddHandler(
base::WrapUnique(new protocol::TargetHandler(true /* browser_only */)));
if (only_discovery_)
return;
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
session->AddHandler(base::WrapUnique(new protocol::SystemInfoHandler()));
session->AddHandler(base::WrapUnique(new protocol::TetheringHandler(
socket_callback_, tethering_task_runner_)));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Browser,
FrameTreeNode::kFrameTreeNodeInvalidId,
GetIOContext())));
}
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 BrowserDevToolsAgentHost::AttachSession(DevToolsSession* session) {
bool BrowserDevToolsAgentHost::AttachSession(DevToolsSession* session) {
if (session->restricted())
return false;
session->SetBrowserOnly(true);
session->AddHandler(
base::WrapUnique(new protocol::TargetHandler(true /* browser_only */)));
if (only_discovery_)
return true;
session->AddHandler(base::WrapUnique(new protocol::BrowserHandler()));
session->AddHandler(base::WrapUnique(new protocol::IOHandler(
GetIOContext())));
session->AddHandler(base::WrapUnique(new protocol::MemoryHandler()));
session->AddHandler(base::WrapUnique(new protocol::SecurityHandler()));
session->AddHandler(base::WrapUnique(new protocol::SystemInfoHandler()));
session->AddHandler(base::WrapUnique(new protocol::TetheringHandler(
socket_callback_, tethering_task_runner_)));
session->AddHandler(base::WrapUnique(new protocol::TracingHandler(
protocol::TracingHandler::Browser,
FrameTreeNode::kFrameTreeNodeInvalidId,
GetIOContext())));
return true;
}
| 173,241 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) {
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midibuffer == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0);
return (NULL);
}
if (size > WM_MAXFILESIZE) {
/* don't bother loading suspiciously long files */
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0);
return (NULL);
}
if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(midibuffer, size);
} else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(midibuffer, size);
} else if (memcmp(midibuffer, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(midibuffer, size);
} else if (memcmp(midibuffer, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(midibuffer, size);
} else {
ret = (void *) _WM_ParseNewMidi(midibuffer, size);
}
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
Commit Message: wildmidi_lib.c (WildMidi_Open, WildMidi_OpenBuffer): refuse to proceed if less then 18 bytes of input
Fixes bug #178.
CWE ID: CWE-119 | WM_SYMBOL midi *WildMidi_OpenBuffer(uint8_t *midibuffer, uint32_t size) {
uint8_t mus_hdr[] = { 'M', 'U', 'S', 0x1A };
uint8_t xmi_hdr[] = { 'F', 'O', 'R', 'M' };
midi * ret = NULL;
if (!WM_Initialized) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_INIT, NULL, 0);
return (NULL);
}
if (midibuffer == NULL) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_INVALID_ARG, "(NULL midi data buffer)", 0);
return (NULL);
}
if (size > WM_MAXFILESIZE) {
/* don't bother loading suspiciously long files */
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_LONGFIL, NULL, 0);
return (NULL);
}
if (size < 18) {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
return (NULL);
}
if (memcmp(midibuffer,"HMIMIDIP", 8) == 0) {
ret = (void *) _WM_ParseNewHmp(midibuffer, size);
} else if (memcmp(midibuffer, "HMI-MIDISONG061595", 18) == 0) {
ret = (void *) _WM_ParseNewHmi(midibuffer, size);
} else if (memcmp(midibuffer, mus_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewMus(midibuffer, size);
} else if (memcmp(midibuffer, xmi_hdr, 4) == 0) {
ret = (void *) _WM_ParseNewXmi(midibuffer, size);
} else {
ret = (void *) _WM_ParseNewMidi(midibuffer, size);
}
if (ret) {
if (add_handle(ret) != 0) {
WildMidi_Close(ret);
ret = NULL;
}
}
return (ret);
}
| 169,370 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
__uint128_t tmp;
void *valp = &tmp;
u64 off;
int err = 0;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (KVM_REG_SIZE(reg->id) > sizeof(tmp))
return -EINVAL;
if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) {
err = -EFAULT;
goto out;
}
if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) {
u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK;
switch (mode) {
case PSR_AA32_MODE_USR:
case PSR_AA32_MODE_FIQ:
case PSR_AA32_MODE_IRQ:
case PSR_AA32_MODE_SVC:
case PSR_AA32_MODE_ABT:
case PSR_AA32_MODE_UND:
case PSR_MODE_EL0t:
case PSR_MODE_EL1t:
case PSR_MODE_EL1h:
break;
default:
err = -EINVAL;
goto out;
}
}
memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id));
out:
return err;
}
Commit Message: arm64: KVM: Tighten guest core register access from userspace
We currently allow userspace to access the core register file
in about any possible way, including straddling multiple
registers and doing unaligned accesses.
This is not the expected use of the ABI, and nobody is actually
using it that way. Let's tighten it by explicitly checking
the size and alignment for each field of the register file.
Cc: <[email protected]>
Fixes: 2f4a07c5f9fe ("arm64: KVM: guest one-reg interface")
Reviewed-by: Christoffer Dall <[email protected]>
Reviewed-by: Mark Rutland <[email protected]>
Signed-off-by: Dave Martin <[email protected]>
[maz: rewrote Dave's initial patch to be more easily backported]
Signed-off-by: Marc Zyngier <[email protected]>
Signed-off-by: Will Deacon <[email protected]>
CWE ID: CWE-20 | static int set_core_reg(struct kvm_vcpu *vcpu, const struct kvm_one_reg *reg)
{
__u32 __user *uaddr = (__u32 __user *)(unsigned long)reg->addr;
struct kvm_regs *regs = vcpu_gp_regs(vcpu);
int nr_regs = sizeof(*regs) / sizeof(__u32);
__uint128_t tmp;
void *valp = &tmp;
u64 off;
int err = 0;
/* Our ID is an index into the kvm_regs struct. */
off = core_reg_offset_from_id(reg->id);
if (off >= nr_regs ||
(off + (KVM_REG_SIZE(reg->id) / sizeof(__u32))) >= nr_regs)
return -ENOENT;
if (validate_core_offset(reg))
return -EINVAL;
if (KVM_REG_SIZE(reg->id) > sizeof(tmp))
return -EINVAL;
if (copy_from_user(valp, uaddr, KVM_REG_SIZE(reg->id))) {
err = -EFAULT;
goto out;
}
if (off == KVM_REG_ARM_CORE_REG(regs.pstate)) {
u32 mode = (*(u32 *)valp) & PSR_AA32_MODE_MASK;
switch (mode) {
case PSR_AA32_MODE_USR:
case PSR_AA32_MODE_FIQ:
case PSR_AA32_MODE_IRQ:
case PSR_AA32_MODE_SVC:
case PSR_AA32_MODE_ABT:
case PSR_AA32_MODE_UND:
case PSR_MODE_EL0t:
case PSR_MODE_EL1t:
case PSR_MODE_EL1h:
break;
default:
err = -EINVAL;
goto out;
}
}
memcpy((u32 *)regs + off, valp, KVM_REG_SIZE(reg->id));
out:
return err;
}
| 169,012 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 impeg2d_flush_ext_and_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while(u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE)
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX)
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | void impeg2d_flush_ext_and_user_data(dec_state_t *ps_dec)
{
UWORD32 u4_start_code;
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
while((u4_start_code == EXTENSION_START_CODE || u4_start_code == USER_DATA_START_CODE) &&
(ps_stream->u4_offset < ps_stream->u4_max_offset))
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
while(impeg2d_bit_stream_nxt(ps_stream,START_CODE_PREFIX_LEN) != START_CODE_PREFIX &&
(ps_stream->u4_offset < ps_stream->u4_max_offset))
{
impeg2d_bit_stream_flush(ps_stream,8);
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
}
| 173,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: int re_yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
Commit Message: re_lexer: Make reading escape sequences more robust (#586)
* Add test for issue #503
* re_lexer: Make reading escape sequences more robust
This commit fixes parsing incomplete escape sequences at the end of a
regular expression and parsing things like \xxy (invalid hex digits)
which before were silently turned into (char)255.
Close #503
* Update re_lexer.c
CWE ID: CWE-476 | int re_yyget_lineno (yyscan_t yyscanner)
{
struct yyguts_t * yyg = (struct yyguts_t*)yyscanner;
if (! YY_CURRENT_BUFFER)
return 0;
return yylineno;
}
| 168,484 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size);
PrintOutParsingResult(res, 1, caller);
return res;
}
Commit Message: NetKVM: BZ#1169718: Checking the length only on read
Signed-off-by: Joseph Hindin <[email protected]>
CWE ID: CWE-20 | tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, LPCSTR caller)
tTcpIpPacketParsingResult ParaNdis_ReviewIPPacket(PVOID buffer, ULONG size, BOOLEAN verifyLength, LPCSTR caller)
{
tTcpIpPacketParsingResult res = QualifyIpPacket((IPHeader *) buffer, size, verifyLength);
PrintOutParsingResult(res, 1, caller);
return res;
}
| 170,144 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: krb5_gss_inquire_context(minor_status, context_handle, initiator_name,
acceptor_name, lifetime_rec, mech_type, ret_flags,
locally_initiated, opened)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_name_t *initiator_name;
gss_name_t *acceptor_name;
OM_uint32 *lifetime_rec;
gss_OID *mech_type;
OM_uint32 *ret_flags;
int *locally_initiated;
int *opened;
{
krb5_context context;
krb5_error_code code;
krb5_gss_ctx_id_rec *ctx;
krb5_gss_name_t initiator, acceptor;
krb5_timestamp now;
krb5_deltat lifetime;
if (initiator_name)
*initiator_name = (gss_name_t) NULL;
if (acceptor_name)
*acceptor_name = (gss_name_t) NULL;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
initiator = NULL;
acceptor = NULL;
context = ctx->k5_context;
if ((code = krb5_timeofday(context, &now))) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
if ((lifetime = ctx->krb_times.endtime - now) < 0)
lifetime = 0;
if (initiator_name) {
if ((code = kg_duplicate_name(context,
ctx->initiate ? ctx->here : ctx->there,
&initiator))) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
}
if (acceptor_name) {
if ((code = kg_duplicate_name(context,
ctx->initiate ? ctx->there : ctx->here,
&acceptor))) {
if (initiator)
kg_release_name(context, &initiator);
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
}
if (initiator_name)
*initiator_name = (gss_name_t) initiator;
if (acceptor_name)
*acceptor_name = (gss_name_t) acceptor;
if (lifetime_rec)
*lifetime_rec = lifetime;
if (mech_type)
*mech_type = (gss_OID) ctx->mech_used;
if (ret_flags)
*ret_flags = ctx->gss_flags;
if (locally_initiated)
*locally_initiated = ctx->initiate;
if (opened)
*opened = ctx->established;
*minor_status = 0;
return((lifetime == 0)?GSS_S_CONTEXT_EXPIRED:GSS_S_COMPLETE);
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | krb5_gss_inquire_context(minor_status, context_handle, initiator_name,
acceptor_name, lifetime_rec, mech_type, ret_flags,
locally_initiated, opened)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
gss_name_t *initiator_name;
gss_name_t *acceptor_name;
OM_uint32 *lifetime_rec;
gss_OID *mech_type;
OM_uint32 *ret_flags;
int *locally_initiated;
int *opened;
{
krb5_context context;
krb5_error_code code;
krb5_gss_ctx_id_rec *ctx;
krb5_gss_name_t initiator, acceptor;
krb5_timestamp now;
krb5_deltat lifetime;
if (initiator_name)
*initiator_name = (gss_name_t) NULL;
if (acceptor_name)
*acceptor_name = (gss_name_t) NULL;
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
initiator = NULL;
acceptor = NULL;
context = ctx->k5_context;
if ((code = krb5_timeofday(context, &now))) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
if ((lifetime = ctx->krb_times.endtime - now) < 0)
lifetime = 0;
if (initiator_name) {
if ((code = kg_duplicate_name(context,
ctx->initiate ? ctx->here : ctx->there,
&initiator))) {
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
}
if (acceptor_name) {
if ((code = kg_duplicate_name(context,
ctx->initiate ? ctx->there : ctx->here,
&acceptor))) {
if (initiator)
kg_release_name(context, &initiator);
*minor_status = code;
save_error_info(*minor_status, context);
return(GSS_S_FAILURE);
}
}
if (initiator_name)
*initiator_name = (gss_name_t) initiator;
if (acceptor_name)
*acceptor_name = (gss_name_t) acceptor;
if (lifetime_rec)
*lifetime_rec = lifetime;
if (mech_type)
*mech_type = (gss_OID) ctx->mech_used;
if (ret_flags)
*ret_flags = ctx->gss_flags;
if (locally_initiated)
*locally_initiated = ctx->initiate;
if (opened)
*opened = ctx->established;
*minor_status = 0;
return((lifetime == 0)?GSS_S_CONTEXT_EXPIRED:GSS_S_COMPLETE);
}
| 166,816 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::string MediaStreamManager::MakeMediaAccessRequest(
int render_process_id,
int render_frame_id,
int page_request_id,
const StreamControls& controls,
const url::Origin& security_origin,
MediaAccessRequestCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, page_request_id,
false /* user gesture */, MEDIA_DEVICE_ACCESS, controls,
MediaDeviceSaltAndOrigin{std::string() /* salt */,
std::string() /* group_id_salt */,
security_origin});
const std::string& label = AddRequest(request);
request->media_access_request_cb = std::move(callback);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
return label;
}
Commit Message: Make MediaStreamDispatcherHost per-request instead of per-frame.
Instead of having RenderFrameHost own a single MSDH to handle all
requests from a frame, MSDH objects will be owned by a strong binding.
A consequence of this is that an additional requester ID is added to
requests to MediaStreamManager, so that an MSDH is able to cancel only
requests generated by it.
In practice, MSDH will continue to be per frame in most cases since
each frame normally makes a single request for an MSDH object.
This fixes a lifetime issue caused by the IO thread executing tasks
after the RenderFrameHost dies.
Drive-by: Fix some minor lint issues.
Bug: 912520
Change-Id: I52742ffc98b9fc57ce8e6f5093a61aed86d3e516
Reviewed-on: https://chromium-review.googlesource.com/c/1369799
Reviewed-by: Emircan Uysaler <[email protected]>
Reviewed-by: Ken Buchanan <[email protected]>
Reviewed-by: Olga Sharonova <[email protected]>
Commit-Queue: Guido Urdaneta <[email protected]>
Cr-Commit-Position: refs/heads/master@{#616347}
CWE ID: CWE-189 | std::string MediaStreamManager::MakeMediaAccessRequest(
int render_process_id,
int render_frame_id,
int requester_id,
int page_request_id,
const StreamControls& controls,
const url::Origin& security_origin,
MediaAccessRequestCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
DeviceRequest* request = new DeviceRequest(
render_process_id, render_frame_id, requester_id, page_request_id,
false /* user gesture */, MEDIA_DEVICE_ACCESS, controls,
MediaDeviceSaltAndOrigin{std::string() /* salt */,
std::string() /* group_id_salt */,
security_origin});
const std::string& label = AddRequest(request);
request->media_access_request_cb = std::move(callback);
base::PostTaskWithTraits(FROM_HERE, {BrowserThread::IO},
base::BindOnce(&MediaStreamManager::SetUpRequest,
base::Unretained(this), label));
return label;
}
| 173,104 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: process_bitmap_updates(STREAM s)
{
uint16 num_updates;
uint16 left, top, right, bottom, width, height;
uint16 cx, cy, bpp, Bpp, compress, bufsize, size;
uint8 *data, *bmpdata;
int i;
logger(Protocol, Debug, "%s()", __func__);
in_uint16_le(s, num_updates);
for (i = 0; i < num_updates; i++)
{
in_uint16_le(s, left);
in_uint16_le(s, top);
in_uint16_le(s, right);
in_uint16_le(s, bottom);
in_uint16_le(s, width);
in_uint16_le(s, height);
in_uint16_le(s, bpp);
Bpp = (bpp + 7) / 8;
in_uint16_le(s, compress);
in_uint16_le(s, bufsize);
cx = right - left + 1;
cy = bottom - top + 1;
logger(Graphics, Debug,
"process_bitmap_updates(), [%d,%d,%d,%d], [%d,%d], bpp=%d, compression=%d",
left, top, right, bottom, width, height, Bpp, compress);
if (!compress)
{
int y;
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
for (y = 0; y < height; y++)
{
in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)],
width * Bpp);
}
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
xfree(bmpdata);
continue;
}
if (compress & 0x400)
{
size = bufsize;
}
else
{
in_uint8s(s, 2); /* pad */
in_uint16_le(s, size);
in_uint8s(s, 4); /* line_size, final_size */
}
in_uint8p(s, data, size);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (bitmap_decompress(bmpdata, width, height, data, size, Bpp))
{
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
}
else
{
logger(Graphics, Warning,
"process_bitmap_updates(), failed to decompress bitmap");
}
xfree(bmpdata);
}
}
Commit Message: Malicious RDP server security fixes
This commit includes fixes for a set of 21 vulnerabilities in
rdesktop when a malicious RDP server is used.
All vulnerabilities was identified and reported by Eyal Itkin.
* Add rdp_protocol_error function that is used in several fixes
* Refactor of process_bitmap_updates
* Fix possible integer overflow in s_check_rem() on 32bit arch
* Fix memory corruption in process_bitmap_data - CVE-2018-8794
* Fix remote code execution in process_bitmap_data - CVE-2018-8795
* Fix remote code execution in process_plane - CVE-2018-8797
* Fix Denial of Service in mcs_recv_connect_response - CVE-2018-20175
* Fix Denial of Service in mcs_parse_domain_params - CVE-2018-20175
* Fix Denial of Service in sec_parse_crypt_info - CVE-2018-20176
* Fix Denial of Service in sec_recv - CVE-2018-20176
* Fix minor information leak in rdpdr_process - CVE-2018-8791
* Fix Denial of Service in cssp_read_tsrequest - CVE-2018-8792
* Fix remote code execution in cssp_read_tsrequest - CVE-2018-8793
* Fix Denial of Service in process_bitmap_data - CVE-2018-8796
* Fix minor information leak in rdpsnd_process_ping - CVE-2018-8798
* Fix Denial of Service in process_secondary_order - CVE-2018-8799
* Fix remote code execution in in ui_clip_handle_data - CVE-2018-8800
* Fix major information leak in ui_clip_handle_data - CVE-2018-20174
* Fix memory corruption in rdp_in_unistr - CVE-2018-20177
* Fix Denial of Service in process_demand_active - CVE-2018-20178
* Fix remote code execution in lspci_process - CVE-2018-20179
* Fix remote code execution in rdpsnddbg_process - CVE-2018-20180
* Fix remote code execution in seamless_process - CVE-2018-20181
* Fix remote code execution in seamless_process_line - CVE-2018-20182
CWE ID: CWE-119 | process_bitmap_updates(STREAM s)
/* Process TS_BITMAP_DATA */
static void
process_bitmap_data(STREAM s)
{
uint16 left, top, right, bottom, width, height;
uint16 cx, cy, bpp, Bpp, flags, bufsize, size;
uint8 *data, *bmpdata;
logger(Protocol, Debug, "%s()", __func__);
struct stream packet = *s;
in_uint16_le(s, left); /* destLeft */
in_uint16_le(s, top); /* destTop */
in_uint16_le(s, right); /* destRight */
in_uint16_le(s, bottom); /* destBottom */
in_uint16_le(s, width); /* width */
in_uint16_le(s, height); /* height */
in_uint16_le(s, bpp); /*bitsPerPixel */
Bpp = (bpp + 7) / 8;
in_uint16_le(s, flags); /* flags */
in_uint16_le(s, bufsize); /* bitmapLength */
cx = right - left + 1;
cy = bottom - top + 1;
/* FIXME: There are a assumtion that we do not consider in
this code. The value of bpp is not passed to
ui_paint_bitmap() which relies on g_server_bpp for drawing
the bitmap data.
Does this means that we can sanity check bpp with g_server_bpp ?
*/
if (Bpp == 0 || width == 0 || height == 0)
{
logger(Protocol, Warning, "%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x", __func__,
left, top, right, bottom, width, height, bpp, flags);
rdp_protocol_error("TS_BITMAP_DATA, unsafe size of bitmap data received from server", &packet);
}
if ((RD_UINT32_MAX / Bpp) <= (width * height))
{
logger(Protocol, Warning, "%s(), [%d,%d,%d,%d], [%d,%d], bpp=%d, flags=%x", __func__,
left, top, right, bottom, width, height, bpp, flags);
rdp_protocol_error("TS_BITMAP_DATA, unsafe size of bitmap data received from server", &packet);
}
if (flags == 0)
{
/* read uncompressed bitmap data */
int y;
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
for (y = 0; y < height; y++)
{
in_uint8a(s, &bmpdata[(height - y - 1) * (width * Bpp)], width * Bpp);
}
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
xfree(bmpdata);
return;
}
if (flags & NO_BITMAP_COMPRESSION_HDR)
{
size = bufsize;
}
else
{
/* Read TS_CD_HEADER */
in_uint8s(s, 2); /* skip cbCompFirstRowSize (must be 0x0000) */
in_uint16_le(s, size); /* cbCompMainBodySize */
in_uint8s(s, 2); /* skip cbScanWidth */
in_uint8s(s, 2); /* skip cbUncompressedSize */
}
/* read compressed bitmap data */
if (!s_check_rem(s, size))
{
rdp_protocol_error("process_bitmap_data(), consume of bitmap data from stream would overrun", &packet);
}
in_uint8p(s, data, size);
bmpdata = (uint8 *) xmalloc(width * height * Bpp);
if (bitmap_decompress(bmpdata, width, height, data, size, Bpp))
{
ui_paint_bitmap(left, top, cx, cy, width, height, bmpdata);
}
else
{
logger(Protocol, Warning, "%s(), failed to decompress bitmap", __func__);
}
xfree(bmpdata);
}
/* Process TS_UPDATE_BITMAP_DATA */
void
process_bitmap_updates(STREAM s)
{
int i;
uint16 num_updates;
in_uint16_le(s, num_updates); /* rectangles */
for (i = 0; i < num_updates; i++)
{
process_bitmap_data(s);
}
}
| 169,802 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Track::GetFirst(const BlockEntry*& pBlockEntry) const {
const Cluster* pCluster = m_pSegment->GetFirst();
for (int i = 0;;) {
if (pCluster == NULL) {
pBlockEntry = GetEOS();
return 1;
}
if (pCluster->EOS()) {
#if 0
if (m_pSegment->Unparsed() <= 0) { //all clusters have been loaded
pBlockEntry = GetEOS();
return 1;
}
#else
if (m_pSegment->DoneParsing()) {
pBlockEntry = GetEOS();
return 1;
}
#endif
pBlockEntry = 0;
return E_BUFFER_NOT_FULL;
}
long status = pCluster->GetFirst(pBlockEntry);
if (status < 0) // error
return status;
if (pBlockEntry == 0) { // empty cluster
pCluster = m_pSegment->GetNext(pCluster);
continue;
}
for (;;) {
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
const long long tn = pBlock->GetTrackNumber();
if ((tn == m_info.number) && VetEntry(pBlockEntry))
return 0;
const BlockEntry* pNextEntry;
status = pCluster->GetNext(pBlockEntry, pNextEntry);
if (status < 0) // error
return status;
if (pNextEntry == 0)
break;
pBlockEntry = pNextEntry;
}
++i;
if (i >= 100)
break;
pCluster = m_pSegment->GetNext(pCluster);
}
pBlockEntry = GetEOS(); // so we can return a non-NULL value
return 1;
}
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 Track::GetFirst(const BlockEntry*& pBlockEntry) const {
const Cluster* pCluster = m_pSegment->GetFirst();
for (int i = 0;;) {
if (pCluster == NULL) {
pBlockEntry = GetEOS();
return 1;
}
if (pCluster->EOS()) {
if (m_pSegment->DoneParsing()) {
pBlockEntry = GetEOS();
return 1;
}
pBlockEntry = 0;
return E_BUFFER_NOT_FULL;
}
long status = pCluster->GetFirst(pBlockEntry);
if (status < 0) // error
return status;
if (pBlockEntry == 0) { // empty cluster
pCluster = m_pSegment->GetNext(pCluster);
continue;
}
for (;;) {
const Block* const pBlock = pBlockEntry->GetBlock();
assert(pBlock);
const long long tn = pBlock->GetTrackNumber();
if ((tn == m_info.number) && VetEntry(pBlockEntry))
return 0;
const BlockEntry* pNextEntry;
status = pCluster->GetNext(pBlockEntry, pNextEntry);
if (status < 0) // error
return status;
if (pNextEntry == 0)
break;
pBlockEntry = pNextEntry;
}
++i;
if (i >= 100)
break;
pCluster = m_pSegment->GetNext(pCluster);
}
pBlockEntry = GetEOS(); // so we can return a non-NULL value
return 1;
}
| 173,819 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
if (num > VIRTIO_PCI_QUEUE_MAX) {
error_report("Invalid number of PCI queues: 0x%x", num);
return -1;
}
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
Commit Message:
CWE ID: CWE-94 | int virtio_load(VirtIODevice *vdev, QEMUFile *f)
{
int i, ret;
uint32_t num;
uint32_t features;
uint32_t supported_features;
BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));
VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
if (k->load_config) {
ret = k->load_config(qbus->parent, f);
if (ret)
return ret;
}
qemu_get_8s(f, &vdev->status);
qemu_get_8s(f, &vdev->isr);
qemu_get_be16s(f, &vdev->queue_sel);
if (vdev->queue_sel >= VIRTIO_PCI_QUEUE_MAX) {
return -1;
}
qemu_get_be32s(f, &features);
if (virtio_set_features(vdev, features) < 0) {
return -1;
}
vdev->config_len = qemu_get_be32(f);
qemu_get_buffer(f, vdev->config, vdev->config_len);
num = qemu_get_be32(f);
if (num > VIRTIO_PCI_QUEUE_MAX) {
error_report("Invalid number of PCI queues: 0x%x", num);
return -1;
}
for (i = 0; i < num; i++) {
vdev->vq[i].vring.num = qemu_get_be32(f);
if (k->has_variable_vring_alignment) {
vdev->vq[i].vring.align = qemu_get_be32(f);
}
vdev->vq[i].pa = qemu_get_be64(f);
qemu_get_be16s(f, &vdev->vq[i].last_avail_idx);
vdev->vq[i].signalled_used_valid = false;
vdev->vq[i].notification = true;
if (vdev->vq[i].pa) {
uint16_t nheads;
virtqueue_init(&vdev->vq[i]);
nheads = vring_avail_idx(&vdev->vq[i]) - vdev->vq[i].last_avail_idx;
/* Check it isn't doing very strange things with descriptor numbers. */
if (nheads > vdev->vq[i].vring.num) {
error_report("VQ %d size 0x%x Guest index 0x%x "
"inconsistent with Host index 0x%x: delta 0x%x",
i, vdev->vq[i].vring.num,
vring_avail_idx(&vdev->vq[i]),
vdev->vq[i].last_avail_idx, nheads);
return -1;
}
} else if (vdev->vq[i].last_avail_idx) {
error_report("VQ %d address 0x0 "
"inconsistent with Host index 0x%x",
i, vdev->vq[i].last_avail_idx);
return -1;
}
if (k->load_queue) {
ret = k->load_queue(qbus->parent, i, f);
if (ret)
return ret;
}
}
virtio_notify_vector(vdev, VIRTIO_NO_VECTOR);
return 0;
}
| 165,336 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: decnet_print(netdissect_options *ndo,
register const u_char *ap, register u_int length,
register u_int caplen)
{
register const union routehdr *rhp;
register int mflags;
int dst, src, hops;
u_int nsplen, pktlen;
const u_char *nspp;
if (length < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(*ap, sizeof(short));
pktlen = EXTRACT_LE_16BITS(ap);
if (pktlen < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
if (pktlen > length) {
ND_PRINT((ndo, "%s", tstr));
return;
}
length = pktlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
ND_TCHECK(rhp->rh_short.sh_flags);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
if (mflags & RMF_PAD) {
/* pad bytes of some sort in front of message */
u_int padlen = mflags & RMF_PADMASK;
if (ndo->ndo_vflag)
ND_PRINT((ndo, "[pad:%d] ", padlen));
if (length < padlen + 2) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(ap[sizeof(short)], padlen);
ap += padlen;
length -= padlen;
caplen -= padlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
}
if (mflags & RMF_FVER) {
ND_PRINT((ndo, "future-version-decnet"));
ND_DEFAULTPRINT(ap, min(length, caplen));
return;
}
/* is it a control message? */
if (mflags & RMF_CTLMSG) {
if (!print_decnet_ctlmsg(ndo, rhp, length, caplen))
goto trunc;
return;
}
switch (mflags & RMF_MASK) {
case RMF_LONG:
if (length < sizeof(struct longhdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK(rhp->rh_long);
dst =
EXTRACT_LE_16BITS(rhp->rh_long.lg_dst.dne_remote.dne_nodeaddr);
src =
EXTRACT_LE_16BITS(rhp->rh_long.lg_src.dne_remote.dne_nodeaddr);
hops = EXTRACT_LE_8BITS(rhp->rh_long.lg_visits);
nspp = &(ap[sizeof(short) + sizeof(struct longhdr)]);
nsplen = length - sizeof(struct longhdr);
break;
case RMF_SHORT:
ND_TCHECK(rhp->rh_short);
dst = EXTRACT_LE_16BITS(rhp->rh_short.sh_dst);
src = EXTRACT_LE_16BITS(rhp->rh_short.sh_src);
hops = (EXTRACT_LE_8BITS(rhp->rh_short.sh_visits) & VIS_MASK)+1;
nspp = &(ap[sizeof(short) + sizeof(struct shorthdr)]);
nsplen = length - sizeof(struct shorthdr);
break;
default:
ND_PRINT((ndo, "unknown message flags under mask"));
ND_DEFAULTPRINT((const u_char *)ap, min(length, caplen));
return;
}
ND_PRINT((ndo, "%s > %s %d ",
dnaddr_string(ndo, src), dnaddr_string(ndo, dst), pktlen));
if (ndo->ndo_vflag) {
if (mflags & RMF_RQR)
ND_PRINT((ndo, "RQR "));
if (mflags & RMF_RTS)
ND_PRINT((ndo, "RTS "));
if (mflags & RMF_IE)
ND_PRINT((ndo, "IE "));
ND_PRINT((ndo, "%d hops ", hops));
}
if (!print_nsp(ndo, nspp, nsplen))
goto trunc;
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
Commit Message: CVE-2017-12899/DECnet: Fix bounds checking.
If we're skipping over padding before the *real* flags, check whether
the real flags are in the captured data before fetching it. This fixes
a buffer over-read discovered by Kamil Frankowicz.
Note one place where we don't need to do bounds checking as it's already
been done.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | decnet_print(netdissect_options *ndo,
register const u_char *ap, register u_int length,
register u_int caplen)
{
register const union routehdr *rhp;
register int mflags;
int dst, src, hops;
u_int nsplen, pktlen;
const u_char *nspp;
if (length < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(*ap, sizeof(short));
pktlen = EXTRACT_LE_16BITS(ap);
if (pktlen < sizeof(struct shorthdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
if (pktlen > length) {
ND_PRINT((ndo, "%s", tstr));
return;
}
length = pktlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
ND_TCHECK(rhp->rh_short.sh_flags);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
if (mflags & RMF_PAD) {
/* pad bytes of some sort in front of message */
u_int padlen = mflags & RMF_PADMASK;
if (ndo->ndo_vflag)
ND_PRINT((ndo, "[pad:%d] ", padlen));
if (length < padlen + 2) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK2(ap[sizeof(short)], padlen);
ap += padlen;
length -= padlen;
caplen -= padlen;
rhp = (const union routehdr *)&(ap[sizeof(short)]);
ND_TCHECK(rhp->rh_short.sh_flags);
mflags = EXTRACT_LE_8BITS(rhp->rh_short.sh_flags);
}
if (mflags & RMF_FVER) {
ND_PRINT((ndo, "future-version-decnet"));
ND_DEFAULTPRINT(ap, min(length, caplen));
return;
}
/* is it a control message? */
if (mflags & RMF_CTLMSG) {
if (!print_decnet_ctlmsg(ndo, rhp, length, caplen))
goto trunc;
return;
}
switch (mflags & RMF_MASK) {
case RMF_LONG:
if (length < sizeof(struct longhdr)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
ND_TCHECK(rhp->rh_long);
dst =
EXTRACT_LE_16BITS(rhp->rh_long.lg_dst.dne_remote.dne_nodeaddr);
src =
EXTRACT_LE_16BITS(rhp->rh_long.lg_src.dne_remote.dne_nodeaddr);
hops = EXTRACT_LE_8BITS(rhp->rh_long.lg_visits);
nspp = &(ap[sizeof(short) + sizeof(struct longhdr)]);
nsplen = length - sizeof(struct longhdr);
break;
case RMF_SHORT:
ND_TCHECK(rhp->rh_short);
dst = EXTRACT_LE_16BITS(rhp->rh_short.sh_dst);
src = EXTRACT_LE_16BITS(rhp->rh_short.sh_src);
hops = (EXTRACT_LE_8BITS(rhp->rh_short.sh_visits) & VIS_MASK)+1;
nspp = &(ap[sizeof(short) + sizeof(struct shorthdr)]);
nsplen = length - sizeof(struct shorthdr);
break;
default:
ND_PRINT((ndo, "unknown message flags under mask"));
ND_DEFAULTPRINT((const u_char *)ap, min(length, caplen));
return;
}
ND_PRINT((ndo, "%s > %s %d ",
dnaddr_string(ndo, src), dnaddr_string(ndo, dst), pktlen));
if (ndo->ndo_vflag) {
if (mflags & RMF_RQR)
ND_PRINT((ndo, "RQR "));
if (mflags & RMF_RTS)
ND_PRINT((ndo, "RTS "));
if (mflags & RMF_IE)
ND_PRINT((ndo, "IE "));
ND_PRINT((ndo, "%d hops ", hops));
}
if (!print_nsp(ndo, nspp, nsplen))
goto trunc;
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
| 170,033 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LogLuvClose(TIFF* tif)
{
TIFFDirectory *td = &tif->tif_dir;
/*
* For consistency, we always want to write out the same
* bitspersample and sampleformat for our TIFF file,
* regardless of the data format being used by the application.
* Since this routine is called after tags have been set but
* before they have been recorded in the file, we reset them here.
*/
td->td_samplesperpixel =
(td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
td->td_bitspersample = 16;
td->td_sampleformat = SAMPLEFORMAT_INT;
}
Commit Message: * libtiff/tif_pixarlog.c, libtiff/tif_luv.c: fix heap-based buffer
overflow on generation of PixarLog / LUV compressed files, with
ColorMap, TransferFunction attached and nasty plays with bitspersample.
The fix for LUV has not been tested, but suffers from the same kind
of issue of PixarLog.
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2604
CWE ID: CWE-125 | LogLuvClose(TIFF* tif)
{
LogLuvState* sp = (LogLuvState*) tif->tif_data;
TIFFDirectory *td = &tif->tif_dir;
assert(sp != 0);
/*
* For consistency, we always want to write out the same
* bitspersample and sampleformat for our TIFF file,
* regardless of the data format being used by the application.
* Since this routine is called after tags have been set but
* before they have been recorded in the file, we reset them here.
* Note: this is really a nasty approach. See PixarLogClose
*/
if( sp->encoder_state )
{
/* See PixarLogClose. Might avoid issues with tags whose size depends
* on those below, but not completely sure this is enough. */
td->td_samplesperpixel =
(td->td_photometric == PHOTOMETRIC_LOGL) ? 1 : 3;
td->td_bitspersample = 16;
td->td_sampleformat = SAMPLEFORMAT_INT;
}
}
| 168,464 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void dns_resolver_describe(const struct key *key, struct seq_file *m)
{
seq_puts(m, key->description);
if (key_is_instantiated(key)) {
int err = PTR_ERR(key->payload.data[dns_key_error]);
if (err)
seq_printf(m, ": %d", err);
else
seq_printf(m, ": %u", key->datalen);
}
}
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 | static void dns_resolver_describe(const struct key *key, struct seq_file *m)
{
seq_puts(m, key->description);
if (key_is_positive(key)) {
int err = PTR_ERR(key->payload.data[dns_key_error]);
if (err)
seq_printf(m, ": %d", err);
else
seq_printf(m, ": %u", key->datalen);
}
}
| 167,691 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Tracks::Parse() {
assert(m_trackEntries == NULL);
assert(m_trackEntriesEnd == NULL);
const long long stop = m_start + m_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
int count = 0;
long long pos = m_start;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x2E) // TrackEntry ID
++count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
if (count <= 0)
return 0; // success
m_trackEntries = new (std::nothrow) Track* [count];
if (m_trackEntries == NULL)
return -1;
m_trackEntriesEnd = m_trackEntries;
pos = m_start;
while (pos < stop) {
const long long element_start = pos;
long long id, payload_size;
const long status =
ParseElementHeader(pReader, pos, stop, id, payload_size);
if (status < 0) // error
return status;
if (payload_size == 0) // weird
continue;
const long long payload_stop = pos + payload_size;
assert(payload_stop <= stop); // checked in ParseElement
const long long element_size = payload_stop - element_start;
if (id == 0x2E) { // TrackEntry ID
Track*& pTrack = *m_trackEntriesEnd;
pTrack = NULL;
const long status = ParseTrackEntry(pos, payload_size, element_start,
element_size, pTrack);
if (status)
return status;
if (pTrack)
++m_trackEntriesEnd;
}
pos = payload_stop;
assert(pos <= stop);
}
assert(pos == stop);
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 Tracks::Parse() {
assert(m_trackEntries == NULL);
assert(m_trackEntriesEnd == NULL);
const long long stop = m_start + m_size;
IMkvReader* const pReader = m_pSegment->m_pReader;
int count = 0;
long long pos = m_start;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (size == 0) // weird
continue;
if (id == 0x2E) // TrackEntry ID
++count;
pos += size; // consume payload
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
if (count <= 0)
return 0; // success
m_trackEntries = new (std::nothrow) Track*[count];
if (m_trackEntries == NULL)
return -1;
m_trackEntriesEnd = m_trackEntries;
pos = m_start;
while (pos < stop) {
const long long element_start = pos;
long long id, payload_size;
const long status =
ParseElementHeader(pReader, pos, stop, id, payload_size);
if (status < 0) // error
return status;
if (payload_size == 0) // weird
continue;
const long long payload_stop = pos + payload_size;
assert(payload_stop <= stop); // checked in ParseElement
const long long element_size = payload_stop - element_start;
if (id == 0x2E) { // TrackEntry ID
Track*& pTrack = *m_trackEntriesEnd;
pTrack = NULL;
const long status = ParseTrackEntry(pos, payload_size, element_start,
element_size, pTrack);
if (status)
return status;
if (pTrack)
++m_trackEntriesEnd;
}
pos = payload_stop;
if (pos > stop)
return E_FILE_FORMAT_INVALID;
}
if (pos != stop)
return E_FILE_FORMAT_INVALID;
return 0; // success
}
| 173,845 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool UnprivilegedProcessDelegate::CreateConnectedIpcChannel(
const std::string& channel_name,
IPC::Listener* delegate,
ScopedHandle* client_out,
scoped_ptr<IPC::ChannelProxy>* server_out) {
scoped_ptr<IPC::ChannelProxy> server;
if (!CreateIpcChannel(channel_name, kDaemonIpcSecurityDescriptor,
io_task_runner_, delegate, &server)) {
return false;
}
std::string pipe_name(kChromePipeNamePrefix);
pipe_name.append(channel_name);
SECURITY_ATTRIBUTES security_attributes;
security_attributes.nLength = sizeof(security_attributes);
security_attributes.lpSecurityDescriptor = NULL;
security_attributes.bInheritHandle = TRUE;
ScopedHandle client;
client.Set(CreateFile(UTF8ToUTF16(pipe_name).c_str(),
GENERIC_READ | GENERIC_WRITE,
0,
&security_attributes,
OPEN_EXISTING,
SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION |
FILE_FLAG_OVERLAPPED,
NULL));
if (!client.IsValid())
return false;
*client_out = client.Pass();
*server_out = server.Pass();
return true;
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool UnprivilegedProcessDelegate::CreateConnectedIpcChannel(
| 171,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int fscrypt_process_policy(struct inode *inode,
const struct fscrypt_policy *policy)
{
if (policy->version != 0)
return -EINVAL;
if (!inode_has_encryption_context(inode)) {
if (!inode->i_sb->s_cop->empty_dir)
return -EOPNOTSUPP;
if (!inode->i_sb->s_cop->empty_dir(inode))
return -ENOTEMPTY;
return create_encryption_context_from_policy(inode, policy);
}
if (is_encryption_context_consistent_with_policy(inode, policy))
return 0;
printk(KERN_WARNING "%s: Policy inconsistent with encryption context\n",
__func__);
return -EINVAL;
}
Commit Message: fscrypto: add authorization check for setting encryption policy
On an ext4 or f2fs filesystem with file encryption supported, a user
could set an encryption policy on any empty directory(*) to which they
had readonly access. This is obviously problematic, since such a
directory might be owned by another user and the new encryption policy
would prevent that other user from creating files in their own directory
(for example).
Fix this by requiring inode_owner_or_capable() permission to set an
encryption policy. This means that either the caller must own the file,
or the caller must have the capability CAP_FOWNER.
(*) Or also on any regular file, for f2fs v4.6 and later and ext4
v4.8-rc1 and later; a separate bug fix is coming for that.
Signed-off-by: Eric Biggers <[email protected]>
Cc: [email protected] # 4.1+; check fs/{ext4,f2fs}
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-264 | int fscrypt_process_policy(struct inode *inode,
const struct fscrypt_policy *policy)
{
if (!inode_owner_or_capable(inode))
return -EACCES;
if (policy->version != 0)
return -EINVAL;
if (!inode_has_encryption_context(inode)) {
if (!inode->i_sb->s_cop->empty_dir)
return -EOPNOTSUPP;
if (!inode->i_sb->s_cop->empty_dir(inode))
return -ENOTEMPTY;
return create_encryption_context_from_policy(inode, policy);
}
if (is_encryption_context_consistent_with_policy(inode, policy))
return 0;
printk(KERN_WARNING "%s: Policy inconsistent with encryption context\n",
__func__);
return -EINVAL;
}
| 168,460 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 key_notify_policy_flush(const struct km_event *c)
{
struct sk_buff *skb_out;
struct sadb_msg *hdr;
skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb_out)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
hdr->sadb_msg_type = SADB_X_SPDFLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
Commit Message: af_key: fix info leaks in notify messages
key_notify_sa_flush() and key_notify_policy_flush() miss to initialize
the sadb_msg_reserved member of the broadcasted message and thereby
leak 2 bytes of heap memory to listeners. Fix that.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Steffen Klassert <[email protected]>
Cc: "David S. Miller" <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int key_notify_policy_flush(const struct km_event *c)
{
struct sk_buff *skb_out;
struct sadb_msg *hdr;
skb_out = alloc_skb(sizeof(struct sadb_msg) + 16, GFP_ATOMIC);
if (!skb_out)
return -ENOBUFS;
hdr = (struct sadb_msg *) skb_put(skb_out, sizeof(struct sadb_msg));
hdr->sadb_msg_type = SADB_X_SPDFLUSH;
hdr->sadb_msg_seq = c->seq;
hdr->sadb_msg_pid = c->portid;
hdr->sadb_msg_version = PF_KEY_V2;
hdr->sadb_msg_errno = (uint8_t) 0;
hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC;
hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t));
hdr->sadb_msg_reserved = 0;
pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net);
return 0;
}
| 166,074 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_remote_connection_destroy(gpointer user_data)
{
cib_client_t *client = user_data;
if (client == NULL) {
return;
}
crm_trace("Cleaning up after client disconnect: %s/%s",
crm_str(client->name), client->id);
if (client->id != NULL) {
if (!g_hash_table_remove(client_list, client->id)) {
crm_err("Client %s not found in the hashtable", client->name);
}
}
crm_trace("Destroying %s (%p)", client->name, user_data);
num_clients--;
crm_trace("Num unfree'd clients: %d", num_clients);
free(client->name);
free(client->callback_id);
free(client->id);
free(client->user);
free(client);
crm_trace("Freed the cib client");
if (cib_shutdown_flag) {
cib_shutdown(0);
}
return;
}
Commit Message: High: core: Internal tls api improvements for reuse with future LRMD tls backend.
CWE ID: CWE-399 | cib_remote_connection_destroy(gpointer user_data)
{
cib_client_t *client = user_data;
int csock = 0;
if (client == NULL) {
return;
}
crm_trace("Cleaning up after client disconnect: %s/%s",
crm_str(client->name), client->id);
if (client->id != NULL) {
if (!g_hash_table_remove(client_list, client->id)) {
crm_err("Client %s not found in the hashtable", client->name);
}
}
crm_trace("Destroying %s (%p)", client->name, user_data);
num_clients--;
crm_trace("Num unfree'd clients: %d", num_clients);
if (client->remote_auth_timeout) {
g_source_remove(client->remote_auth_timeout);
}
if (client->encrypted) {
#ifdef HAVE_GNUTLS_GNUTLS_H
if (client->session) {
void *sock_ptr = gnutls_transport_get_ptr(*client->session);
csock = GPOINTER_TO_INT(sock_ptr);
if (client->handshake_complete) {
gnutls_bye(*client->session, GNUTLS_SHUT_WR);
}
gnutls_deinit(*client->session);
gnutls_free(client->session);
}
#endif
} else {
csock = GPOINTER_TO_INT(client->session);
}
client->session = NULL;
if (csock > 0) {
close(csock);
}
free(client->name);
free(client->callback_id);
free(client->id);
free(client->user);
free(client->recv_buf);
free(client);
crm_trace("Freed the cib client");
if (cib_shutdown_flag) {
cib_shutdown(0);
}
return;
}
| 166,147 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_FUNCTION(snmp_set_oid_output_format)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
}
Commit Message:
CWE ID: CWE-416 | PHP_FUNCTION(snmp_set_oid_output_format)
{
long a1;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &a1) == FAILURE) {
RETURN_FALSE;
}
switch((int) a1) {
case NETSNMP_OID_OUTPUT_SUFFIX:
case NETSNMP_OID_OUTPUT_MODULE:
case NETSNMP_OID_OUTPUT_FULL:
case NETSNMP_OID_OUTPUT_NUMERIC:
case NETSNMP_OID_OUTPUT_UCD:
case NETSNMP_OID_OUTPUT_NONE:
netsnmp_ds_set_int(NETSNMP_DS_LIBRARY_ID, NETSNMP_DS_LIB_OID_OUTPUT_FORMAT, a1);
RETURN_TRUE;
break;
default:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown SNMP output print format '%d'", (int) a1);
RETURN_FALSE;
break;
}
| 164,971 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: push_decoder_state (DECODER_STATE ds)
{
if (ds->idx >= ds->stacksize)
{
fprintf (stderr, "ERROR: decoder stack overflow!\n");
abort ();
}
ds->stack[ds->idx++] = ds->cur;
}
Commit Message:
CWE ID: CWE-20 | push_decoder_state (DECODER_STATE ds)
{
if (ds->idx >= ds->stacksize)
{
fprintf (stderr, "ksba: ber-decoder: stack overflow!\n");
return gpg_error (GPG_ERR_LIMIT_REACHED);
}
ds->stack[ds->idx++] = ds->cur;
return 0;
}
| 165,052 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OnZipAnalysisFinished(const zip_analyzer::Results& results) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(ClientDownloadRequest::ZIPPED_EXECUTABLE, type_);
if (!service_)
return;
if (results.success) {
zipped_executable_ = results.has_executable;
archived_binary_.CopyFrom(results.archived_binary);
DVLOG(1) << "Zip analysis finished for " << item_->GetFullPath().value()
<< ", has_executable=" << results.has_executable
<< " has_archive=" << results.has_archive;
} else {
DVLOG(1) << "Zip analysis failed for " << item_->GetFullPath().value();
}
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasExecutable",
zipped_executable_);
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasArchiveButNoExecutable",
results.has_archive && !zipped_executable_);
UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractZipFeaturesTime",
base::TimeTicks::Now() - zip_analysis_start_time_);
for (const auto& file_extension : results.archived_archive_filetypes)
RecordArchivedArchiveFileExtensionType(file_extension);
if (!zipped_executable_ && !results.has_archive) {
PostFinishTask(UNKNOWN, REASON_ARCHIVE_WITHOUT_BINARIES);
return;
}
if (!zipped_executable_ && results.has_archive)
type_ = ClientDownloadRequest::ZIPPED_ARCHIVE;
OnFileFeatureExtractionDone();
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID: | void OnZipAnalysisFinished(const zip_analyzer::Results& results) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK_EQ(ClientDownloadRequest::ZIPPED_EXECUTABLE, type_);
if (!service_)
return;
if (results.success) {
archived_executable_ = results.has_executable;
archived_binary_.CopyFrom(results.archived_binary);
DVLOG(1) << "Zip analysis finished for " << item_->GetFullPath().value()
<< ", has_executable=" << results.has_executable
<< " has_archive=" << results.has_archive;
} else {
DVLOG(1) << "Zip analysis failed for " << item_->GetFullPath().value();
}
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasExecutable",
archived_executable_);
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.ZipFileHasArchiveButNoExecutable",
results.has_archive && !archived_executable_);
UMA_HISTOGRAM_TIMES("SBClientDownload.ExtractZipFeaturesTime",
base::TimeTicks::Now() - zip_analysis_start_time_);
for (const auto& file_extension : results.archived_archive_filetypes)
RecordArchivedArchiveFileExtensionType(file_extension);
if (!archived_executable_ && !results.has_archive) {
PostFinishTask(UNKNOWN, REASON_ARCHIVE_WITHOUT_BINARIES);
return;
}
if (!archived_executable_ && results.has_archive)
type_ = ClientDownloadRequest::ZIPPED_ARCHIVE;
OnFileFeatureExtractionDone();
}
| 171,713 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AccessibilityOrientation AXNodeObject::orientation() const {
const AtomicString& ariaOrientation =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation);
AccessibilityOrientation orientation = AccessibilityOrientationUndefined;
if (equalIgnoringCase(ariaOrientation, "horizontal"))
orientation = AccessibilityOrientationHorizontal;
else if (equalIgnoringCase(ariaOrientation, "vertical"))
orientation = AccessibilityOrientationVertical;
switch (roleValue()) {
case ComboBoxRole:
case ListBoxRole:
case MenuRole:
case ScrollBarRole:
case TreeRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationVertical;
return orientation;
case MenuBarRole:
case SliderRole:
case SplitterRole:
case TabListRole:
case ToolbarRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationHorizontal;
return orientation;
case RadioGroupRole:
case TreeGridRole:
case TableRole:
return orientation;
default:
return AXObject::orientation();
}
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | AccessibilityOrientation AXNodeObject::orientation() const {
const AtomicString& ariaOrientation =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kOrientation);
AccessibilityOrientation orientation = AccessibilityOrientationUndefined;
if (equalIgnoringASCIICase(ariaOrientation, "horizontal"))
orientation = AccessibilityOrientationHorizontal;
else if (equalIgnoringASCIICase(ariaOrientation, "vertical"))
orientation = AccessibilityOrientationVertical;
switch (roleValue()) {
case ComboBoxRole:
case ListBoxRole:
case MenuRole:
case ScrollBarRole:
case TreeRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationVertical;
return orientation;
case MenuBarRole:
case SliderRole:
case SplitterRole:
case TabListRole:
case ToolbarRole:
if (orientation == AccessibilityOrientationUndefined)
orientation = AccessibilityOrientationHorizontal;
return orientation;
case RadioGroupRole:
case TreeGridRole:
case TableRole:
return orientation;
default:
return AXObject::orientation();
}
}
| 171,920 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
{
struct ipcm_cookie ipc;
struct rtable *rt = skb_rtable(skb);
struct net *net = dev_net(rt->dst.dev);
struct sock *sk;
struct inet_sock *inet;
__be32 daddr;
if (ip_options_echo(&icmp_param->replyopts, skb))
return;
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
inet = inet_sk(sk);
icmp_param->data.icmph.checksum = 0;
inet->tos = ip_hdr(skb)->tos;
daddr = ipc.addr = rt->rt_src;
ipc.opt = NULL;
ipc.tx_flags = 0;
if (icmp_param->replyopts.optlen) {
ipc.opt = &icmp_param->replyopts;
if (ipc.opt->srr)
daddr = icmp_param->replyopts.faddr;
}
{
struct flowi4 fl4 = {
.daddr = daddr,
.saddr = rt->rt_spec_dst,
.flowi4_tos = RT_TOS(ip_hdr(skb)->tos),
.flowi4_proto = IPPROTO_ICMP,
};
security_skb_classify_flow(skb, flowi4_to_flowi(&fl4));
rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt))
goto out_unlock;
}
if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type,
icmp_param->data.icmph.code))
icmp_push_reply(icmp_param, &ipc, &rt);
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
}
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 | static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
{
struct ipcm_cookie ipc;
struct rtable *rt = skb_rtable(skb);
struct net *net = dev_net(rt->dst.dev);
struct sock *sk;
struct inet_sock *inet;
__be32 daddr;
if (ip_options_echo(&icmp_param->replyopts.opt.opt, skb))
return;
sk = icmp_xmit_lock(net);
if (sk == NULL)
return;
inet = inet_sk(sk);
icmp_param->data.icmph.checksum = 0;
inet->tos = ip_hdr(skb)->tos;
daddr = ipc.addr = rt->rt_src;
ipc.opt = NULL;
ipc.tx_flags = 0;
if (icmp_param->replyopts.opt.opt.optlen) {
ipc.opt = &icmp_param->replyopts.opt;
if (ipc.opt->opt.srr)
daddr = icmp_param->replyopts.opt.opt.faddr;
}
{
struct flowi4 fl4 = {
.daddr = daddr,
.saddr = rt->rt_spec_dst,
.flowi4_tos = RT_TOS(ip_hdr(skb)->tos),
.flowi4_proto = IPPROTO_ICMP,
};
security_skb_classify_flow(skb, flowi4_to_flowi(&fl4));
rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt))
goto out_unlock;
}
if (icmpv4_xrlim_allow(net, rt, icmp_param->data.icmph.type,
icmp_param->data.icmph.code))
icmp_push_reply(icmp_param, &ipc, &rt);
ip_rt_put(rt);
out_unlock:
icmp_xmit_unlock(sk);
}
| 165,552 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GLSurfaceEGLSurfaceControl::SupportsSwapBuffersWithBounds() {
return false;
}
Commit Message: gpu/android : Add support for partial swap with surface control.
Add support for PostSubBuffer to GLSurfaceEGLSurfaceControl. This should
allow the display compositor to draw the minimum sub-rect necessary from
the damage tracking in BufferQueue on the client-side, and also to pass
this damage rect to the framework.
[email protected]
Bug: 926020
Change-Id: I73d3320cab68250d4c6865bf21c5531682d8bf61
Reviewed-on: https://chromium-review.googlesource.com/c/1457467
Commit-Queue: Khushal <[email protected]>
Commit-Queue: Antoine Labour <[email protected]>
Reviewed-by: Antoine Labour <[email protected]>
Auto-Submit: Khushal <[email protected]>
Cr-Commit-Position: refs/heads/master@{#629852}
CWE ID: | bool GLSurfaceEGLSurfaceControl::SupportsSwapBuffersWithBounds() {
| 172,112 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SoftGSM::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 8000;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftGSM::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = 1;
pcmParams->nSamplingRate = 8000;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,207 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 WebMediaPlayerImpl::HasSingleSecurityOrigin() const {
if (data_source_)
return data_source_->HasSingleOrigin();
return true;
}
Commit Message: Fix HasSingleSecurityOrigin for HLS
HLS manifests can request segments from a different origin than the
original manifest's origin. We do not inspect HLS manifests within
Chromium, and instead delegate to Android's MediaPlayer. This means we
need to be conservative, and always assume segments might come from a
different origin. HasSingleSecurityOrigin should always return false
when decoding HLS.
Bug: 864283
Change-Id: Ie16849ac6f29ae7eaa9caf342ad0509a226228ef
Reviewed-on: https://chromium-review.googlesource.com/1142691
Reviewed-by: Dale Curtis <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Commit-Queue: Thomas Guilbert <[email protected]>
Cr-Commit-Position: refs/heads/master@{#576378}
CWE ID: CWE-346 | bool WebMediaPlayerImpl::HasSingleSecurityOrigin() const {
if (demuxer_found_hls_) {
// HLS manifests might pull segments from a different origin. We can't know
// for sure, so we conservatively say no here.
return false;
}
if (data_source_)
return data_source_->HasSingleOrigin();
return true;
}
| 173,178 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu)
{
const struct usb_cdc_union_desc *union_desc;
struct usb_host_interface *alt;
union_desc = ims_pcu_get_cdc_union_desc(intf);
if (!union_desc)
return -EINVAL;
pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bMasterInterface0);
alt = pcu->ctrl_intf->cur_altsetting;
pcu->ep_ctrl = &alt->endpoint[0].desc;
pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl);
pcu->data_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bSlaveInterface0);
alt = pcu->data_intf->cur_altsetting;
if (alt->desc.bNumEndpoints != 2) {
dev_err(pcu->dev,
"Incorrect number of endpoints on data interface (%d)\n",
alt->desc.bNumEndpoints);
return -EINVAL;
}
pcu->ep_out = &alt->endpoint[0].desc;
if (!usb_endpoint_is_bulk_out(pcu->ep_out)) {
dev_err(pcu->dev,
"First endpoint on data interface is not BULK OUT\n");
return -EINVAL;
}
pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out);
if (pcu->max_out_size < 8) {
dev_err(pcu->dev,
"Max OUT packet size is too small (%zd)\n",
pcu->max_out_size);
return -EINVAL;
}
pcu->ep_in = &alt->endpoint[1].desc;
if (!usb_endpoint_is_bulk_in(pcu->ep_in)) {
dev_err(pcu->dev,
"Second endpoint on data interface is not BULK IN\n");
return -EINVAL;
}
pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in);
if (pcu->max_in_size < 8) {
dev_err(pcu->dev,
"Max IN packet size is too small (%zd)\n",
pcu->max_in_size);
return -EINVAL;
}
return 0;
}
Commit Message: Input: ims-pcu - sanity check against missing interfaces
A malicious device missing interface can make the driver oops.
Add sanity checking.
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
Signed-off-by: Dmitry Torokhov <[email protected]>
CWE ID: | static int ims_pcu_parse_cdc_data(struct usb_interface *intf, struct ims_pcu *pcu)
{
const struct usb_cdc_union_desc *union_desc;
struct usb_host_interface *alt;
union_desc = ims_pcu_get_cdc_union_desc(intf);
if (!union_desc)
return -EINVAL;
pcu->ctrl_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bMasterInterface0);
if (!pcu->ctrl_intf)
return -EINVAL;
alt = pcu->ctrl_intf->cur_altsetting;
pcu->ep_ctrl = &alt->endpoint[0].desc;
pcu->max_ctrl_size = usb_endpoint_maxp(pcu->ep_ctrl);
pcu->data_intf = usb_ifnum_to_if(pcu->udev,
union_desc->bSlaveInterface0);
if (!pcu->data_intf)
return -EINVAL;
alt = pcu->data_intf->cur_altsetting;
if (alt->desc.bNumEndpoints != 2) {
dev_err(pcu->dev,
"Incorrect number of endpoints on data interface (%d)\n",
alt->desc.bNumEndpoints);
return -EINVAL;
}
pcu->ep_out = &alt->endpoint[0].desc;
if (!usb_endpoint_is_bulk_out(pcu->ep_out)) {
dev_err(pcu->dev,
"First endpoint on data interface is not BULK OUT\n");
return -EINVAL;
}
pcu->max_out_size = usb_endpoint_maxp(pcu->ep_out);
if (pcu->max_out_size < 8) {
dev_err(pcu->dev,
"Max OUT packet size is too small (%zd)\n",
pcu->max_out_size);
return -EINVAL;
}
pcu->ep_in = &alt->endpoint[1].desc;
if (!usb_endpoint_is_bulk_in(pcu->ep_in)) {
dev_err(pcu->dev,
"Second endpoint on data interface is not BULK IN\n");
return -EINVAL;
}
pcu->max_in_size = usb_endpoint_maxp(pcu->ep_in);
if (pcu->max_in_size < 8) {
dev_err(pcu->dev,
"Max IN packet size is too small (%zd)\n",
pcu->max_in_size);
return -EINVAL;
}
return 0;
}
| 167,351 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int snmp_helper(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
struct snmp_ctx *ctx = (struct snmp_ctx *)context;
__be32 *pdata = (__be32 *)data;
if (*pdata == ctx->from) {
pr_debug("%s: %pI4 to %pI4\n", __func__,
(void *)&ctx->from, (void *)&ctx->to);
if (*ctx->check)
fast_csum(ctx, (unsigned char *)data - ctx->begin);
*pdata = ctx->to;
}
return 1;
}
Commit Message: netfilter: nf_nat_snmp_basic: add missing length checks in ASN.1 cbs
The generic ASN.1 decoder infrastructure doesn't guarantee that callbacks
will get as much data as they expect; callbacks have to check the `datalen`
parameter before looking at `data`. Make sure that snmp_version() and
snmp_helper() don't read/write beyond the end of the packet data.
(Also move the assignment to `pdata` down below the check to make it clear
that it isn't necessarily a pointer we can use before the `datalen` check.)
Fixes: cc2d58634e0f ("netfilter: nf_nat_snmp_basic: use asn1 decoder library")
Signed-off-by: Jann Horn <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-129 | int snmp_helper(void *context, size_t hdrlen, unsigned char tag,
const void *data, size_t datalen)
{
struct snmp_ctx *ctx = (struct snmp_ctx *)context;
__be32 *pdata;
if (datalen != 4)
return -EINVAL;
pdata = (__be32 *)data;
if (*pdata == ctx->from) {
pr_debug("%s: %pI4 to %pI4\n", __func__,
(void *)&ctx->from, (void *)&ctx->to);
if (*ctx->check)
fast_csum(ctx, (unsigned char *)data - ctx->begin);
*pdata = ctx->to;
}
return 1;
}
| 169,723 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
if (val > maxval)
ERREXIT(cinfo, JERR_PPM_TOOLARGE);
return val;
}
Commit Message: cjpeg: Fix OOB read caused by malformed 8-bit BMP
... in which one or more of the color indices is out of range for the
number of palette entries.
Fix partly borrowed from jpeg-9c. This commit also adopts Guido's
JERR_PPM_OUTOFRANGE enum value in lieu of our project-specific
JERR_PPM_TOOLARGE enum value.
Fixes #258
CWE ID: CWE-125 | read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
if (val > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
return val;
}
| 169,840 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AutofillPopupBaseView::AddExtraInitParams(
views::Widget::InitParams* params) {
params->opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
params->shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE;
}
Commit Message: [Autofill] Remove AutofillPopupViewViews and associated feature.
Bug: 906135,831603
Change-Id: I3c982f8b3ffb4928c7c878e74e10113999106499
Reviewed-on: https://chromium-review.googlesource.com/c/1387124
Reviewed-by: Robert Kaplow <[email protected]>
Reviewed-by: Vasilii Sukhanov <[email protected]>
Reviewed-by: Fabio Tirelo <[email protected]>
Reviewed-by: Tommy Martino <[email protected]>
Commit-Queue: Mathieu Perreault <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621360}
CWE ID: CWE-416 | void AutofillPopupBaseView::AddExtraInitParams(
| 172,092 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) {
if (message_loop_) {
delete message_loop_;
message_loop_ = NULL;
} else {
PP_NOTREACHED();
}
}
Commit Message: Fix PPB_Flash_MessageLoop.
This CL suspends script callbacks and resource loads while running nested message loop using PPB_Flash_MessageLoop.
BUG=569496
Review URL: https://codereview.chromium.org/1559113002
Cr-Commit-Position: refs/heads/master@{#374529}
CWE ID: CWE-264 | void TestFlashMessageLoop::DestroyMessageLoopResourceTask(int32_t unused) {
if (message_loop_) {
delete message_loop_;
message_loop_ = nullptr;
} else {
PP_NOTREACHED();
}
}
| 172,124 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: InvalidState AXNodeObject::getInvalidState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kInvalid);
if (equalIgnoringCase(attributeValue, "false"))
return InvalidStateFalse;
if (equalIgnoringCase(attributeValue, "true"))
return InvalidStateTrue;
if (equalIgnoringCase(attributeValue, "spelling"))
return InvalidStateSpelling;
if (equalIgnoringCase(attributeValue, "grammar"))
return InvalidStateGrammar;
if (!attributeValue.isEmpty())
return InvalidStateOther;
if (getNode() && getNode()->isElementNode() &&
toElement(getNode())->isFormControlElement()) {
HTMLFormControlElement* element = toHTMLFormControlElement(getNode());
HeapVector<Member<HTMLFormControlElement>> invalidControls;
bool isInvalid =
!element->checkValidity(&invalidControls, CheckValidityDispatchNoEvent);
return isInvalid ? InvalidStateTrue : InvalidStateFalse;
}
return AXObject::getInvalidState();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | InvalidState AXNodeObject::getInvalidState() const {
const AtomicString& attributeValue =
getAOMPropertyOrARIAAttribute(AOMStringProperty::kInvalid);
if (equalIgnoringASCIICase(attributeValue, "false"))
return InvalidStateFalse;
if (equalIgnoringASCIICase(attributeValue, "true"))
return InvalidStateTrue;
if (equalIgnoringASCIICase(attributeValue, "spelling"))
return InvalidStateSpelling;
if (equalIgnoringASCIICase(attributeValue, "grammar"))
return InvalidStateGrammar;
if (!attributeValue.isEmpty())
return InvalidStateOther;
if (getNode() && getNode()->isElementNode() &&
toElement(getNode())->isFormControlElement()) {
HTMLFormControlElement* element = toHTMLFormControlElement(getNode());
HeapVector<Member<HTMLFormControlElement>> invalidControls;
bool isInvalid =
!element->checkValidity(&invalidControls, CheckValidityDispatchNoEvent);
return isInvalid ? InvalidStateTrue : InvalidStateFalse;
}
return AXObject::getInvalidState();
}
| 171,912 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: StateBase* writeFileList(v8::Handle<v8::Value> value, StateBase* next)
{
FileList* fileList = V8FileList::toNative(value.As<v8::Object>());
if (!fileList)
return 0;
unsigned length = fileList->length();
Vector<int> blobIndices;
for (unsigned i = 0; i < length; ++i) {
int blobIndex = -1;
const File* file = fileList->item(i);
if (file->hasBeenClosed())
return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next);
m_blobDataHandles.add(file->uuid(), file->blobDataHandle());
if (appendFileInfo(file, &blobIndex)) {
ASSERT(!i || blobIndex > 0);
ASSERT(blobIndex >= 0);
blobIndices.append(blobIndex);
}
}
if (!blobIndices.isEmpty())
m_writer.writeFileListIndex(blobIndices);
else
m_writer.writeFileList(*fileList);
return 0;
}
Commit Message: Replace further questionable HashMap::add usages in bindings
BUG=390928
[email protected]
Review URL: https://codereview.chromium.org/411273002
git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | StateBase* writeFileList(v8::Handle<v8::Value> value, StateBase* next)
{
FileList* fileList = V8FileList::toNative(value.As<v8::Object>());
if (!fileList)
return 0;
unsigned length = fileList->length();
Vector<int> blobIndices;
for (unsigned i = 0; i < length; ++i) {
int blobIndex = -1;
const File* file = fileList->item(i);
if (file->hasBeenClosed())
return handleError(DataCloneError, "A File object has been closed, and could therefore not be cloned.", next);
m_blobDataHandles.set(file->uuid(), file->blobDataHandle());
if (appendFileInfo(file, &blobIndex)) {
ASSERT(!i || blobIndex > 0);
ASSERT(blobIndex >= 0);
blobIndices.append(blobIndex);
}
}
if (!blobIndices.isEmpty())
m_writer.writeFileListIndex(blobIndices);
else
m_writer.writeFileList(*fileList);
return 0;
}
| 171,652 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
Commit Message:
CWE ID: CWE-20 | SProcXFixesChangeSaveSet(ClientPtr client)
{
REQUEST(xXFixesChangeSaveSetReq);
REQUEST_SIZE_MATCH(xXFixesChangeSaveSetReq);
swaps(&stuff->length);
swapl(&stuff->window);
}
| 165,443 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_DetachItemFromObject( cJSON *object, const char *string )
{
int i = 0;
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) ) {
++i;
c = c->next;
}
if ( c )
return cJSON_DetachItemFromArray( object, i );
return 0;
}
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_DetachItemFromObject( cJSON *object, const char *string )
| 167,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebContents* DevToolsWindow::OpenURLFromTab(
WebContents* source,
const content::OpenURLParams& params) {
DCHECK(source == main_web_contents_);
if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) {
WebContents* inspected_web_contents = GetInspectedWebContents();
return inspected_web_contents ?
inspected_web_contents->OpenURL(params) : NULL;
}
bindings_->Reload();
return main_web_contents_;
}
Commit Message: [DevTools] Use no-referrer for DevTools links
Bug: 732751
Change-Id: I77753120e2424203dedcc7bc0847fb67f87fe2b2
Reviewed-on: https://chromium-review.googlesource.com/615021
Reviewed-by: Andrey Kosyakov <[email protected]>
Commit-Queue: Dmitry Gozman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#494413}
CWE ID: CWE-668 | WebContents* DevToolsWindow::OpenURLFromTab(
WebContents* source,
const content::OpenURLParams& params) {
DCHECK(source == main_web_contents_);
if (!params.url.SchemeIs(content::kChromeDevToolsScheme)) {
WebContents* inspected_web_contents = GetInspectedWebContents();
if (!inspected_web_contents)
return nullptr;
content::OpenURLParams modified = params;
modified.referrer = content::Referrer();
return inspected_web_contents->OpenURL(modified);
}
bindings_->Reload();
return main_web_contents_;
}
| 172,960 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool UsbChooserContext::HasDevicePermission(
const GURL& requesting_origin,
const GURL& embedding_origin,
const device::mojom::UsbDeviceInfo& device_info) {
if (UsbBlocklist::Get().IsExcluded(device_info))
return false;
if (!CanRequestObjectPermission(requesting_origin, embedding_origin))
return false;
auto it = ephemeral_devices_.find(
std::make_pair(requesting_origin, embedding_origin));
if (it != ephemeral_devices_.end() &&
base::ContainsKey(it->second, device_info.guid)) {
return true;
}
std::vector<std::unique_ptr<base::DictionaryValue>> device_list =
GetGrantedObjects(requesting_origin, embedding_origin);
for (const std::unique_ptr<base::DictionaryValue>& device_dict :
device_list) {
int vendor_id;
int product_id;
base::string16 serial_number;
if (device_dict->GetInteger(kVendorIdKey, &vendor_id) &&
device_info.vendor_id == vendor_id &&
device_dict->GetInteger(kProductIdKey, &product_id) &&
device_info.product_id == product_id &&
device_dict->GetString(kSerialNumberKey, &serial_number) &&
device_info.serial_number == serial_number) {
return true;
}
}
return false;
}
Commit Message: Enforce the WebUsbAllowDevicesForUrls policy
This change modifies UsbChooserContext to use the UsbAllowDevicesForUrls
class to consider devices allowed by the WebUsbAllowDevicesForUrls
policy. The WebUsbAllowDevicesForUrls policy overrides the other WebUSB
policies. Unit tests are also added to ensure that the policy is being
enforced correctly.
The design document for this feature is found at:
https://docs.google.com/document/d/1MPvsrWiVD_jAC8ELyk8njFpy6j1thfVU5aWT3TCWE8w
Bug: 854329
Change-Id: I5f82e662ca9dc544da5918eae766b5535a31296b
Reviewed-on: https://chromium-review.googlesource.com/c/1259289
Commit-Queue: Ovidio Henriquez <[email protected]>
Reviewed-by: Reilly Grant <[email protected]>
Reviewed-by: Julian Pastarmov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597926}
CWE ID: CWE-119 | bool UsbChooserContext::HasDevicePermission(
const GURL& requesting_origin,
const GURL& embedding_origin,
const device::mojom::UsbDeviceInfo& device_info) {
if (UsbBlocklist::Get().IsExcluded(device_info))
return false;
if (usb_policy_allowed_devices_->IsDeviceAllowed(
requesting_origin, embedding_origin, device_info)) {
return true;
}
if (!CanRequestObjectPermission(requesting_origin, embedding_origin))
return false;
auto it = ephemeral_devices_.find(
std::make_pair(requesting_origin, embedding_origin));
if (it != ephemeral_devices_.end() &&
base::ContainsKey(it->second, device_info.guid)) {
return true;
}
std::vector<std::unique_ptr<base::DictionaryValue>> device_list =
GetGrantedObjects(requesting_origin, embedding_origin);
for (const std::unique_ptr<base::DictionaryValue>& device_dict :
device_list) {
int vendor_id;
int product_id;
base::string16 serial_number;
if (device_dict->GetInteger(kVendorIdKey, &vendor_id) &&
device_info.vendor_id == vendor_id &&
device_dict->GetInteger(kProductIdKey, &product_id) &&
device_info.product_id == product_id &&
device_dict->GetString(kSerialNumberKey, &serial_number) &&
device_info.serial_number == serial_number) {
return true;
}
}
return false;
}
| 173,335 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SendRequest() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!service_)
return;
bool is_extended_reporting = false;
if (item_->GetBrowserContext()) {
Profile* profile =
Profile::FromBrowserContext(item_->GetBrowserContext());
is_extended_reporting = profile &&
profile->GetPrefs()->GetBoolean(
prefs::kSafeBrowsingExtendedReportingEnabled);
}
ClientDownloadRequest request;
if (is_extended_reporting) {
request.mutable_population()->set_user_population(
ChromeUserPopulation::EXTENDED_REPORTING);
} else {
request.mutable_population()->set_user_population(
ChromeUserPopulation::SAFE_BROWSING);
}
request.set_url(SanitizeUrl(item_->GetUrlChain().back()));
request.mutable_digests()->set_sha256(item_->GetHash());
request.set_length(item_->GetReceivedBytes());
for (size_t i = 0; i < item_->GetUrlChain().size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(SanitizeUrl(item_->GetUrlChain()[i]));
if (i == item_->GetUrlChain().size() - 1) {
resource->set_type(ClientDownloadRequest::DOWNLOAD_URL);
resource->set_referrer(SanitizeUrl(item_->GetReferrerUrl()));
DVLOG(2) << "dl url " << resource->url();
if (!item_->GetRemoteAddress().empty()) {
resource->set_remote_ip(item_->GetRemoteAddress());
DVLOG(2) << " dl url remote addr: " << resource->remote_ip();
}
DVLOG(2) << "dl referrer " << resource->referrer();
} else {
DVLOG(2) << "dl redirect " << i << " " << resource->url();
resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT);
}
}
for (size_t i = 0; i < tab_redirects_.size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
DVLOG(2) << "tab redirect " << i << " " << tab_redirects_[i].spec();
resource->set_url(SanitizeUrl(tab_redirects_[i]));
resource->set_type(ClientDownloadRequest::TAB_REDIRECT);
}
if (tab_url_.is_valid()) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(SanitizeUrl(tab_url_));
DVLOG(2) << "tab url " << resource->url();
resource->set_type(ClientDownloadRequest::TAB_URL);
if (tab_referrer_url_.is_valid()) {
resource->set_referrer(SanitizeUrl(tab_referrer_url_));
DVLOG(2) << "tab referrer " << resource->referrer();
}
}
request.set_user_initiated(item_->HasUserGesture());
request.set_file_basename(
item_->GetTargetFilePath().BaseName().AsUTF8Unsafe());
request.set_download_type(type_);
request.mutable_signature()->CopyFrom(signature_info_);
if (image_headers_)
request.set_allocated_image_headers(image_headers_.release());
if (zipped_executable_)
request.mutable_archived_binary()->Swap(&archived_binary_);
if (!request.SerializeToString(&client_download_request_data_)) {
FinishRequest(UNKNOWN, REASON_INVALID_REQUEST_PROTO);
return;
}
service_->client_download_request_callbacks_.Notify(item_, &request);
DVLOG(2) << "Sending a request for URL: "
<< item_->GetUrlChain().back();
fetcher_ = net::URLFetcher::Create(0 /* ID used for testing */,
GetDownloadRequestUrl(),
net::URLFetcher::POST, this);
fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
fetcher_->SetAutomaticallyRetryOn5xx(false); // Don't retry on error.
fetcher_->SetRequestContext(service_->request_context_getter_.get());
fetcher_->SetUploadData("application/octet-stream",
client_download_request_data_);
request_start_time_ = base::TimeTicks::Now();
UMA_HISTOGRAM_COUNTS("SBClientDownload.DownloadRequestPayloadSize",
client_download_request_data_.size());
fetcher_->Start();
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID: | void SendRequest() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!service_)
return;
bool is_extended_reporting = false;
if (item_->GetBrowserContext()) {
Profile* profile =
Profile::FromBrowserContext(item_->GetBrowserContext());
is_extended_reporting = profile &&
profile->GetPrefs()->GetBoolean(
prefs::kSafeBrowsingExtendedReportingEnabled);
}
ClientDownloadRequest request;
if (is_extended_reporting) {
request.mutable_population()->set_user_population(
ChromeUserPopulation::EXTENDED_REPORTING);
} else {
request.mutable_population()->set_user_population(
ChromeUserPopulation::SAFE_BROWSING);
}
request.set_url(SanitizeUrl(item_->GetUrlChain().back()));
request.mutable_digests()->set_sha256(item_->GetHash());
request.set_length(item_->GetReceivedBytes());
for (size_t i = 0; i < item_->GetUrlChain().size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(SanitizeUrl(item_->GetUrlChain()[i]));
if (i == item_->GetUrlChain().size() - 1) {
resource->set_type(ClientDownloadRequest::DOWNLOAD_URL);
resource->set_referrer(SanitizeUrl(item_->GetReferrerUrl()));
DVLOG(2) << "dl url " << resource->url();
if (!item_->GetRemoteAddress().empty()) {
resource->set_remote_ip(item_->GetRemoteAddress());
DVLOG(2) << " dl url remote addr: " << resource->remote_ip();
}
DVLOG(2) << "dl referrer " << resource->referrer();
} else {
DVLOG(2) << "dl redirect " << i << " " << resource->url();
resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT);
}
}
for (size_t i = 0; i < tab_redirects_.size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
DVLOG(2) << "tab redirect " << i << " " << tab_redirects_[i].spec();
resource->set_url(SanitizeUrl(tab_redirects_[i]));
resource->set_type(ClientDownloadRequest::TAB_REDIRECT);
}
if (tab_url_.is_valid()) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(SanitizeUrl(tab_url_));
DVLOG(2) << "tab url " << resource->url();
resource->set_type(ClientDownloadRequest::TAB_URL);
if (tab_referrer_url_.is_valid()) {
resource->set_referrer(SanitizeUrl(tab_referrer_url_));
DVLOG(2) << "tab referrer " << resource->referrer();
}
}
request.set_user_initiated(item_->HasUserGesture());
request.set_file_basename(
item_->GetTargetFilePath().BaseName().AsUTF8Unsafe());
request.set_download_type(type_);
request.mutable_signature()->CopyFrom(signature_info_);
if (image_headers_)
request.set_allocated_image_headers(image_headers_.release());
if (archived_executable_)
request.mutable_archived_binary()->Swap(&archived_binary_);
if (!request.SerializeToString(&client_download_request_data_)) {
FinishRequest(UNKNOWN, REASON_INVALID_REQUEST_PROTO);
return;
}
service_->client_download_request_callbacks_.Notify(item_, &request);
DVLOG(2) << "Sending a request for URL: "
<< item_->GetUrlChain().back();
DVLOG(2) << "Detected " << request.archived_binary().size() << " archived "
<< "binaries";
fetcher_ = net::URLFetcher::Create(0 /* ID used for testing */,
GetDownloadRequestUrl(),
net::URLFetcher::POST, this);
fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
fetcher_->SetAutomaticallyRetryOn5xx(false); // Don't retry on error.
fetcher_->SetRequestContext(service_->request_context_getter_.get());
fetcher_->SetUploadData("application/octet-stream",
client_download_request_data_);
request_start_time_ = base::TimeTicks::Now();
UMA_HISTOGRAM_COUNTS("SBClientDownload.DownloadRequestPayloadSize",
client_download_request_data_.size());
fetcher_->Start();
}
| 171,714 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UpdateAtlas::didSwapBuffers()
{
m_areaAllocator.clear();
buildLayoutIfNeeded();
}
Commit Message: [WK2] LayerTreeCoordinator should release unused UpdatedAtlases
https://bugs.webkit.org/show_bug.cgi?id=95072
Reviewed by Jocelyn Turcotte.
Release graphic buffers that haven't been used for a while in order to save memory.
This way we can give back memory to the system when no user interaction happens
after a period of time, for example when we are in the background.
* Shared/ShareableBitmap.h:
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.cpp:
(WebKit::LayerTreeCoordinator::LayerTreeCoordinator):
(WebKit::LayerTreeCoordinator::beginContentUpdate):
(WebKit):
(WebKit::LayerTreeCoordinator::scheduleReleaseInactiveAtlases):
(WebKit::LayerTreeCoordinator::releaseInactiveAtlasesTimerFired):
* WebProcess/WebPage/CoordinatedGraphics/LayerTreeCoordinator.h:
(LayerTreeCoordinator):
* WebProcess/WebPage/UpdateAtlas.cpp:
(WebKit::UpdateAtlas::UpdateAtlas):
(WebKit::UpdateAtlas::didSwapBuffers):
Don't call buildLayoutIfNeeded here. It's enought to call it in beginPaintingOnAvailableBuffer
and this way we can track whether this atlas is used with m_areaAllocator.
(WebKit::UpdateAtlas::beginPaintingOnAvailableBuffer):
* WebProcess/WebPage/UpdateAtlas.h:
(WebKit::UpdateAtlas::addTimeInactive):
(WebKit::UpdateAtlas::isInactive):
(WebKit::UpdateAtlas::isInUse):
(UpdateAtlas):
git-svn-id: svn://svn.chromium.org/blink/trunk@128473 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | void UpdateAtlas::didSwapBuffers()
{
m_areaAllocator.clear();
}
| 170,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: get_linux_shareopts(const char *shareopts, char **plinux_opts)
{
int rc;
assert(plinux_opts != NULL);
*plinux_opts = NULL;
/* default options for Solaris shares */
(void) add_linux_shareopt(plinux_opts, "no_subtree_check", NULL);
(void) add_linux_shareopt(plinux_opts, "no_root_squash", NULL);
(void) add_linux_shareopt(plinux_opts, "mountpoint", NULL);
rc = foreach_nfs_shareopt(shareopts, get_linux_shareopts_cb,
plinux_opts);
if (rc != SA_OK) {
free(*plinux_opts);
*plinux_opts = NULL;
}
return (rc);
}
Commit Message: Move nfs.c:foreach_nfs_shareopt() to libshare.c:foreach_shareopt()
so that it can be (re)used in other parts of libshare.
CWE ID: CWE-200 | get_linux_shareopts(const char *shareopts, char **plinux_opts)
{
int rc;
assert(plinux_opts != NULL);
*plinux_opts = NULL;
/* default options for Solaris shares */
(void) add_linux_shareopt(plinux_opts, "no_subtree_check", NULL);
(void) add_linux_shareopt(plinux_opts, "no_root_squash", NULL);
(void) add_linux_shareopt(plinux_opts, "mountpoint", NULL);
rc = foreach_shareopt(shareopts, get_linux_shareopts_cb,
plinux_opts);
if (rc != SA_OK) {
free(*plinux_opts);
*plinux_opts = NULL;
}
return (rc);
}
| 170,134 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const {
return add_default_proxy_bypass_rules_;
}
Commit Message: Implicitly bypass localhost when proxying requests.
This aligns Chrome's behavior with the Windows and macOS proxy resolvers (but not Firefox).
Concretely:
* localhost names (as determined by net::IsLocalhost) now implicitly bypass the proxy
* link-local IP addresses implicitly bypass the proxy
The implicit rules are handled by ProxyBypassRules, and it is possible to override them when manually configuring proxy settings (but not when using PAC or auto-detect).
This change also adds support for the "<-loopback>" proxy bypass rule, with similar semantics as it has on Windows (removes the implicit bypass rules for localhost and link-local).
The compatibility risk of this change should be low as proxying through localhost was not universally supported. It is however an idiom used in testing (a number of our own tests had such a dependency). Impacted users can use the "<-loopback>" bypass rule as a workaround.
Bug: 413511, 899126, 901896
Change-Id: I263ca21ef9f12d4759a20cb4751dc3261bda6ac0
Reviewed-on: https://chromium-review.googlesource.com/c/1303626
Commit-Queue: Eric Roman <[email protected]>
Reviewed-by: Dominick Ng <[email protected]>
Reviewed-by: Tarun Bansal <[email protected]>
Reviewed-by: Matt Menke <[email protected]>
Reviewed-by: Sami Kyöstilä <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606112}
CWE ID: CWE-20 | bool TestDataReductionProxyConfig::ShouldAddDefaultProxyBypassRules() const {
void TestDataReductionProxyConfig::AddDefaultProxyBypassRules() {
if (!add_default_proxy_bypass_rules_) {
// Set bypass rules which allow proxying localhost.
configurator_->SetBypassRules(
net::ProxyBypassRules::GetRulesToSubtractImplicit());
}
}
| 172,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
if (pkt->size >= 7 &&
pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
uint8_t desc[256];
int score = AVPROBE_SCORE_EXTENSION, ret;
AVIStream *ast = st->priv_data;
AVInputFormat *sub_demuxer;
AVRational time_base;
int size;
AVIOContext *pb = avio_alloc_context(pkt->data + 7,
pkt->size - 7,
0, NULL, NULL, NULL, NULL);
AVProbeData pd;
unsigned int desc_len = avio_rl32(pb);
if (desc_len > pb->buf_end - pb->buf_ptr)
goto error;
ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
avio_skip(pb, desc_len - ret);
if (*desc)
av_dict_set(&st->metadata, "title", desc, 0);
avio_rl16(pb); /* flags? */
avio_rl32(pb); /* data size */
size = pb->buf_end - pb->buf_ptr;
pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
.buf_size = size };
if (!pd.buf)
goto error;
memcpy(pd.buf, pb->buf_ptr, size);
sub_demuxer = av_probe_input_format2(&pd, 1, &score);
av_freep(&pd.buf);
if (!sub_demuxer)
goto error;
if (!(ast->sub_ctx = avformat_alloc_context()))
goto error;
ast->sub_ctx->pb = pb;
if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
goto error;
if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
if (ast->sub_ctx->nb_streams != 1)
goto error;
ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
time_base = ast->sub_ctx->streams[0]->time_base;
avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
}
ast->sub_buffer = pkt->data;
memset(pkt, 0, sizeof(*pkt));
return 1;
error:
av_freep(&ast->sub_ctx);
av_freep(&pb);
}
return 0;
}
Commit Message: avformat/avidec: Limit formats in gab2 to srt and ass/ssa
This prevents part of one exploit leading to an information leak
Found-by: Emil Lerner and Pavel Cheremushkin
Reported-by: Thierry Foucu <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-200 | static int read_gab2_sub(AVFormatContext *s, AVStream *st, AVPacket *pkt)
{
if (pkt->size >= 7 &&
pkt->size < INT_MAX - AVPROBE_PADDING_SIZE &&
!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data + 5) == 2) {
uint8_t desc[256];
int score = AVPROBE_SCORE_EXTENSION, ret;
AVIStream *ast = st->priv_data;
AVInputFormat *sub_demuxer;
AVRational time_base;
int size;
AVIOContext *pb = avio_alloc_context(pkt->data + 7,
pkt->size - 7,
0, NULL, NULL, NULL, NULL);
AVProbeData pd;
unsigned int desc_len = avio_rl32(pb);
if (desc_len > pb->buf_end - pb->buf_ptr)
goto error;
ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
avio_skip(pb, desc_len - ret);
if (*desc)
av_dict_set(&st->metadata, "title", desc, 0);
avio_rl16(pb); /* flags? */
avio_rl32(pb); /* data size */
size = pb->buf_end - pb->buf_ptr;
pd = (AVProbeData) { .buf = av_mallocz(size + AVPROBE_PADDING_SIZE),
.buf_size = size };
if (!pd.buf)
goto error;
memcpy(pd.buf, pb->buf_ptr, size);
sub_demuxer = av_probe_input_format2(&pd, 1, &score);
av_freep(&pd.buf);
if (!sub_demuxer)
goto error;
if (strcmp(sub_demuxer->name, "srt") && strcmp(sub_demuxer->name, "ass"))
goto error;
if (!(ast->sub_ctx = avformat_alloc_context()))
goto error;
ast->sub_ctx->pb = pb;
if (ff_copy_whiteblacklists(ast->sub_ctx, s) < 0)
goto error;
if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
if (ast->sub_ctx->nb_streams != 1)
goto error;
ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
avcodec_parameters_copy(st->codecpar, ast->sub_ctx->streams[0]->codecpar);
time_base = ast->sub_ctx->streams[0]->time_base;
avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
}
ast->sub_buffer = pkt->data;
memset(pkt, 0, sizeof(*pkt));
return 1;
error:
av_freep(&ast->sub_ctx);
av_freep(&pb);
}
return 0;
}
| 168,073 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 int LocaleLowercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
Commit Message: ...
CWE ID: CWE-125 | MagickExport int LocaleLowercase(const int c)
{
if (c == EOF)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
| 170,235 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DoTest(ExternalProtocolHandler::BlockState block_state,
shell_integration::DefaultWebClientState os_state,
Action expected_action) {
GURL url("mailto:[email protected]");
EXPECT_FALSE(delegate_.has_prompted());
EXPECT_FALSE(delegate_.has_launched());
EXPECT_FALSE(delegate_.has_blocked());
delegate_.set_block_state(block_state);
delegate_.set_os_state(os_state);
ExternalProtocolHandler::LaunchUrlWithDelegate(
url, 0, 0, ui::PAGE_TRANSITION_LINK, true, &delegate_);
content::RunAllTasksUntilIdle();
EXPECT_EQ(expected_action == Action::PROMPT, delegate_.has_prompted());
EXPECT_EQ(expected_action == Action::LAUNCH, delegate_.has_launched());
EXPECT_EQ(expected_action == Action::BLOCK, delegate_.has_blocked());
}
Commit Message: Reland "Launching an external protocol handler now escapes the URL."
This is a reland of 2401e58572884b3561e4348d64f11ac74667ef02
Original change's description:
> Launching an external protocol handler now escapes the URL.
>
> Fixes bug introduced in r102449.
>
> Bug: 785809
> Change-Id: I9e6dd1031dd7e7b8d378b138ab151daefdc0c6dc
> Reviewed-on: https://chromium-review.googlesource.com/778747
> Commit-Queue: Matt Giuca <[email protected]>
> Reviewed-by: Eric Lawrence <[email protected]>
> Reviewed-by: Ben Wells <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#518848}
Bug: 785809
Change-Id: Ib8954584004ff5681654398db76d48cdf4437df7
Reviewed-on: https://chromium-review.googlesource.com/788551
Reviewed-by: Ben Wells <[email protected]>
Commit-Queue: Matt Giuca <[email protected]>
Cr-Commit-Position: refs/heads/master@{#519203}
CWE ID: CWE-20 | void DoTest(ExternalProtocolHandler::BlockState block_state,
shell_integration::DefaultWebClientState os_state,
Action expected_action) {
DoTest(block_state, os_state, expected_action,
GURL("mailto:[email protected]"));
}
void DoTest(ExternalProtocolHandler::BlockState block_state,
shell_integration::DefaultWebClientState os_state,
Action expected_action,
const GURL& url) {
EXPECT_FALSE(delegate_.has_prompted());
EXPECT_FALSE(delegate_.has_launched());
EXPECT_FALSE(delegate_.has_blocked());
delegate_.set_block_state(block_state);
delegate_.set_os_state(os_state);
ExternalProtocolHandler::LaunchUrlWithDelegate(
url, 0, 0, ui::PAGE_TRANSITION_LINK, true, &delegate_);
content::RunAllTasksUntilIdle();
EXPECT_EQ(expected_action == Action::PROMPT, delegate_.has_prompted());
EXPECT_EQ(expected_action == Action::LAUNCH, delegate_.has_launched());
EXPECT_EQ(expected_action == Action::BLOCK, delegate_.has_blocked());
}
| 172,688 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Document* LocalDOMWindow::InstallNewDocument(const String& mime_type,
const DocumentInit& init,
bool force_xhtml) {
DCHECK_EQ(init.GetFrame(), GetFrame());
ClearDocument();
document_ = CreateDocument(mime_type, init, force_xhtml);
event_queue_ = DOMWindowEventQueue::Create(document_.Get());
document_->Initialize();
if (!GetFrame())
return document_;
GetFrame()->GetScriptController().UpdateDocument();
document_->UpdateViewportDescription();
if (GetFrame()->GetPage() && GetFrame()->View()) {
GetFrame()->GetPage()->GetChromeClient().InstallSupplements(*GetFrame());
if (ScrollingCoordinator* scrolling_coordinator =
GetFrame()->GetPage()->GetScrollingCoordinator()) {
scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange(
GetFrame()->View(), kHorizontalScrollbar);
scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange(
GetFrame()->View(), kVerticalScrollbar);
scrolling_coordinator->ScrollableAreaScrollLayerDidChange(
GetFrame()->View());
}
}
GetFrame()->Selection().UpdateSecureKeyboardEntryIfActive();
if (GetFrame()->IsCrossOriginSubframe())
document_->RecordDeferredLoadReason(WouldLoadReason::kCreated);
return document_;
}
Commit Message: MacViews: Enable secure text input for password Textfields.
In Cocoa the NSTextInputContext automatically enables secure text input
when activated and it's in the secure text entry mode.
RenderWidgetHostViewMac did the similar thing for ages following the
WebKit example.
views::Textfield needs to do the same thing in a fashion that's
sycnrhonized with RenderWidgetHostViewMac, otherwise the race conditions
are possible when the Textfield gets focus, activates the secure text
input mode and the RWHVM loses focus immediately afterwards and disables
the secure text input instead of leaving it in the enabled state.
BUG=818133,677220
Change-Id: I6db6c4b59e4a1a72cbb7f8c7056f71b04a3df08b
Reviewed-on: https://chromium-review.googlesource.com/943064
Commit-Queue: Michail Pishchagin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#542517}
CWE ID: | Document* LocalDOMWindow::InstallNewDocument(const String& mime_type,
const DocumentInit& init,
bool force_xhtml) {
DCHECK_EQ(init.GetFrame(), GetFrame());
ClearDocument();
document_ = CreateDocument(mime_type, init, force_xhtml);
event_queue_ = DOMWindowEventQueue::Create(document_.Get());
document_->Initialize();
if (!GetFrame())
return document_;
GetFrame()->GetScriptController().UpdateDocument();
document_->UpdateViewportDescription();
if (GetFrame()->GetPage() && GetFrame()->View()) {
GetFrame()->GetPage()->GetChromeClient().InstallSupplements(*GetFrame());
if (ScrollingCoordinator* scrolling_coordinator =
GetFrame()->GetPage()->GetScrollingCoordinator()) {
scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange(
GetFrame()->View(), kHorizontalScrollbar);
scrolling_coordinator->ScrollableAreaScrollbarLayerDidChange(
GetFrame()->View(), kVerticalScrollbar);
scrolling_coordinator->ScrollableAreaScrollLayerDidChange(
GetFrame()->View());
}
}
if (GetFrame()->IsCrossOriginSubframe())
document_->RecordDeferredLoadReason(WouldLoadReason::kCreated);
return document_;
}
| 171,855 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) {
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2dF scroll_offset_dip;
if (max_offset.x()) {
scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) /
max_offset.x());
}
if (max_offset.y()) {
scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) /
max_offset.y());
}
DCHECK_LE(0.f, scroll_offset_dip.x());
DCHECK_LE(0.f, scroll_offset_dip.y());
DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() ||
scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon)
<< scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x();
DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() ||
scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon)
<< scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y();
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
TRACE_EVENT_INSTANT2("android_webview",
"BrowserViewRenderer::ScrollTo",
TRACE_EVENT_SCOPE_THREAD,
"x",
scroll_offset_dip.x(),
"y",
scroll_offset_dip.y());
if (compositor_) {
compositor_->DidChangeRootLayerScrollOffset(
gfx::ScrollOffset(scroll_offset_dip_));
}
}
Commit Message: sync compositor: pass simple gfx types by const ref
See bug for reasoning
BUG=159273
Review URL: https://codereview.chromium.org/1417893006
Cr-Commit-Position: refs/heads/master@{#356653}
CWE ID: CWE-399 | void BrowserViewRenderer::ScrollTo(gfx::Vector2d scroll_offset) {
void BrowserViewRenderer::ScrollTo(const gfx::Vector2d& scroll_offset) {
gfx::Vector2d max_offset = max_scroll_offset();
gfx::Vector2dF scroll_offset_dip;
if (max_offset.x()) {
scroll_offset_dip.set_x((scroll_offset.x() * max_scroll_offset_dip_.x()) /
max_offset.x());
}
if (max_offset.y()) {
scroll_offset_dip.set_y((scroll_offset.y() * max_scroll_offset_dip_.y()) /
max_offset.y());
}
DCHECK_LE(0.f, scroll_offset_dip.x());
DCHECK_LE(0.f, scroll_offset_dip.y());
DCHECK(scroll_offset_dip.x() < max_scroll_offset_dip_.x() ||
scroll_offset_dip.x() - max_scroll_offset_dip_.x() < kEpsilon)
<< scroll_offset_dip.x() << " " << max_scroll_offset_dip_.x();
DCHECK(scroll_offset_dip.y() < max_scroll_offset_dip_.y() ||
scroll_offset_dip.y() - max_scroll_offset_dip_.y() < kEpsilon)
<< scroll_offset_dip.y() << " " << max_scroll_offset_dip_.y();
if (scroll_offset_dip_ == scroll_offset_dip)
return;
scroll_offset_dip_ = scroll_offset_dip;
TRACE_EVENT_INSTANT2("android_webview",
"BrowserViewRenderer::ScrollTo",
TRACE_EVENT_SCOPE_THREAD,
"x",
scroll_offset_dip.x(),
"y",
scroll_offset_dip.y());
if (compositor_) {
compositor_->DidChangeRootLayerScrollOffset(
gfx::ScrollOffset(scroll_offset_dip_));
}
}
| 171,614 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int socket_accept(int fd, uint16_t port)
{
#ifdef WIN32
int addr_len;
#else
socklen_t addr_len;
#endif
int result;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(port);
addr_len = sizeof(addr);
result = accept(fd, (struct sockaddr*)&addr, &addr_len);
return result;
}
Commit Message: common: [security fix] Make sure sockets only listen locally
CWE ID: CWE-284 | int socket_accept(int fd, uint16_t port)
{
#ifdef WIN32
int addr_len;
#else
socklen_t addr_len;
#endif
int result;
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
addr.sin_port = htons(port);
addr_len = sizeof(addr);
result = accept(fd, (struct sockaddr*)&addr, &addr_len);
return result;
}
| 167,165 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 get_siz(Jpeg2000DecoderContext *s)
{
int i;
int ncomponents;
uint32_t log2_chroma_wh = 0;
const enum AVPixelFormat *possible_fmts = NULL;
int possible_fmts_nb = 0;
if (bytestream2_get_bytes_left(&s->g) < 36)
return AVERROR_INVALIDDATA;
s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
s->width = bytestream2_get_be32u(&s->g); // Width
s->height = bytestream2_get_be32u(&s->g); // Height
s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
ncomponents = bytestream2_get_be16u(&s->g); // CSiz
if (ncomponents <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
s->ncomponents);
return AVERROR_INVALIDDATA;
}
if (ncomponents > 4) {
avpriv_request_sample(s->avctx, "Support for %d components",
s->ncomponents);
return AVERROR_PATCHWELCOME;
}
s->ncomponents = ncomponents;
if (s->tile_width <= 0 || s->tile_height <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
s->tile_width, s->tile_height);
return AVERROR_INVALIDDATA;
}
if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
return AVERROR_INVALIDDATA;
for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
uint8_t x = bytestream2_get_byteu(&s->g);
s->cbps[i] = (x & 0x7f) + 1;
s->precision = FFMAX(s->cbps[i], s->precision);
s->sgnd[i] = !!(x & 0x80);
s->cdx[i] = bytestream2_get_byteu(&s->g);
s->cdy[i] = bytestream2_get_byteu(&s->g);
if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
|| !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
return AVERROR_INVALIDDATA;
}
log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
}
s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(EINVAL);
}
s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
if (!s->tile) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
Jpeg2000Tile *tile = s->tile + i;
tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
if (!tile->comp)
return AVERROR(ENOMEM);
}
/* compute image size with reduction factor */
s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
s->reduction_factor);
s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
s->reduction_factor);
if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
possible_fmts = xyz_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
} else {
switch (s->colour_space) {
case 16:
possible_fmts = rgb_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
break;
case 17:
possible_fmts = gray_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
break;
case 18:
possible_fmts = yuv_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
break;
default:
possible_fmts = all_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
break;
}
}
for (i = 0; i < possible_fmts_nb; ++i) {
if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
s->avctx->pix_fmt = possible_fmts[i];
break;
}
}
if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown pix_fmt, profile: %d, colour_space: %d, "
"components: %d, precision: %d, "
"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
s->avctx->profile, s->colour_space, ncomponents, s->precision,
ncomponents > 2 ? s->cdx[1] : 0,
ncomponents > 2 ? s->cdy[1] : 0,
ncomponents > 2 ? s->cdx[2] : 0,
ncomponents > 2 ? s->cdy[2] : 0);
}
s->avctx->bits_per_raw_sample = s->precision;
return 0;
}
Commit Message: avcodec/jpeg2000dec: non zero image offsets are not supported
Fixes out of array accesses
Fixes Ticket3080
Found-by: ami_stuff
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int get_siz(Jpeg2000DecoderContext *s)
{
int i;
int ncomponents;
uint32_t log2_chroma_wh = 0;
const enum AVPixelFormat *possible_fmts = NULL;
int possible_fmts_nb = 0;
if (bytestream2_get_bytes_left(&s->g) < 36)
return AVERROR_INVALIDDATA;
s->avctx->profile = bytestream2_get_be16u(&s->g); // Rsiz
s->width = bytestream2_get_be32u(&s->g); // Width
s->height = bytestream2_get_be32u(&s->g); // Height
s->image_offset_x = bytestream2_get_be32u(&s->g); // X0Siz
s->image_offset_y = bytestream2_get_be32u(&s->g); // Y0Siz
s->tile_width = bytestream2_get_be32u(&s->g); // XTSiz
s->tile_height = bytestream2_get_be32u(&s->g); // YTSiz
s->tile_offset_x = bytestream2_get_be32u(&s->g); // XT0Siz
s->tile_offset_y = bytestream2_get_be32u(&s->g); // YT0Siz
ncomponents = bytestream2_get_be16u(&s->g); // CSiz
if (s->image_offset_x || s->image_offset_y) {
avpriv_request_sample(s->avctx, "Support for image offsets");
return AVERROR_PATCHWELCOME;
}
if (ncomponents <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid number of components: %d\n",
s->ncomponents);
return AVERROR_INVALIDDATA;
}
if (ncomponents > 4) {
avpriv_request_sample(s->avctx, "Support for %d components",
s->ncomponents);
return AVERROR_PATCHWELCOME;
}
s->ncomponents = ncomponents;
if (s->tile_width <= 0 || s->tile_height <= 0) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid tile dimension %dx%d.\n",
s->tile_width, s->tile_height);
return AVERROR_INVALIDDATA;
}
if (bytestream2_get_bytes_left(&s->g) < 3 * s->ncomponents)
return AVERROR_INVALIDDATA;
for (i = 0; i < s->ncomponents; i++) { // Ssiz_i XRsiz_i, YRsiz_i
uint8_t x = bytestream2_get_byteu(&s->g);
s->cbps[i] = (x & 0x7f) + 1;
s->precision = FFMAX(s->cbps[i], s->precision);
s->sgnd[i] = !!(x & 0x80);
s->cdx[i] = bytestream2_get_byteu(&s->g);
s->cdy[i] = bytestream2_get_byteu(&s->g);
if ( !s->cdx[i] || s->cdx[i] == 3 || s->cdx[i] > 4
|| !s->cdy[i] || s->cdy[i] == 3 || s->cdy[i] > 4) {
av_log(s->avctx, AV_LOG_ERROR, "Invalid sample separation %d/%d\n", s->cdx[i], s->cdy[i]);
return AVERROR_INVALIDDATA;
}
log2_chroma_wh |= s->cdy[i] >> 1 << i * 4 | s->cdx[i] >> 1 << i * 4 + 2;
}
s->numXtiles = ff_jpeg2000_ceildiv(s->width - s->tile_offset_x, s->tile_width);
s->numYtiles = ff_jpeg2000_ceildiv(s->height - s->tile_offset_y, s->tile_height);
if (s->numXtiles * (uint64_t)s->numYtiles > INT_MAX/sizeof(*s->tile)) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(EINVAL);
}
s->tile = av_mallocz_array(s->numXtiles * s->numYtiles, sizeof(*s->tile));
if (!s->tile) {
s->numXtiles = s->numYtiles = 0;
return AVERROR(ENOMEM);
}
for (i = 0; i < s->numXtiles * s->numYtiles; i++) {
Jpeg2000Tile *tile = s->tile + i;
tile->comp = av_mallocz(s->ncomponents * sizeof(*tile->comp));
if (!tile->comp)
return AVERROR(ENOMEM);
}
/* compute image size with reduction factor */
s->avctx->width = ff_jpeg2000_ceildivpow2(s->width - s->image_offset_x,
s->reduction_factor);
s->avctx->height = ff_jpeg2000_ceildivpow2(s->height - s->image_offset_y,
s->reduction_factor);
if (s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_2K ||
s->avctx->profile == FF_PROFILE_JPEG2000_DCINEMA_4K) {
possible_fmts = xyz_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(xyz_pix_fmts);
} else {
switch (s->colour_space) {
case 16:
possible_fmts = rgb_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(rgb_pix_fmts);
break;
case 17:
possible_fmts = gray_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(gray_pix_fmts);
break;
case 18:
possible_fmts = yuv_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(yuv_pix_fmts);
break;
default:
possible_fmts = all_pix_fmts;
possible_fmts_nb = FF_ARRAY_ELEMS(all_pix_fmts);
break;
}
}
for (i = 0; i < possible_fmts_nb; ++i) {
if (pix_fmt_match(possible_fmts[i], ncomponents, s->precision, log2_chroma_wh, s->pal8)) {
s->avctx->pix_fmt = possible_fmts[i];
break;
}
}
if (s->avctx->pix_fmt == AV_PIX_FMT_NONE) {
av_log(s->avctx, AV_LOG_ERROR,
"Unknown pix_fmt, profile: %d, colour_space: %d, "
"components: %d, precision: %d, "
"cdx[1]: %d, cdy[1]: %d, cdx[2]: %d, cdy[2]: %d\n",
s->avctx->profile, s->colour_space, ncomponents, s->precision,
ncomponents > 2 ? s->cdx[1] : 0,
ncomponents > 2 ? s->cdy[1] : 0,
ncomponents > 2 ? s->cdx[2] : 0,
ncomponents > 2 ? s->cdy[2] : 0);
}
s->avctx->bits_per_raw_sample = s->precision;
return 0;
}
| 165,927 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: append_utf8_value (const unsigned char *value, size_t length,
struct stringbuf *sb)
{
unsigned char tmp[6];
const unsigned char *s;
size_t n;
int i, nmore;
if (length && (*value == ' ' || *value == '#'))
{
tmp[0] = '\\';
tmp[1] = *value;
put_stringbuf_mem (sb, tmp, 2);
value++;
length--;
}
if (length && value[length-1] == ' ')
{
tmp[0] = '\\';
tmp[1] = ' ';
put_stringbuf_mem (sb, tmp, 2);
length--;
}
/* FIXME: check that the invalid encoding handling is correct */
for (s=value, n=0;;)
{
for (value = s; n < length && !(*s & 0x80); n++, s++)
for (value = s; n < length && !(*s & 0x80); n++, s++)
;
append_quoted (sb, value, s-value, 0);
if (n==length)
return; /* ready */
assert ((*s & 0x80));
if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */
nmore = 1;
else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */
nmore = 2;
else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */
nmore = 3;
else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */
nmore = 4;
else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */
nmore = 5;
else /* invalid encoding */
nmore = 5; /* we will reduce the check length anyway */
if (n+nmore > length)
nmore = length - n; /* oops, encoding to short */
tmp[0] = *s++; n++;
for (i=1; i <= nmore; i++)
{
if ( (*s & 0xc0) != 0x80)
break; /* invalid encoding - stop */
tmp[i] = *s++;
n++;
}
put_stringbuf_mem (sb, tmp, i);
}
}
Commit Message:
CWE ID: CWE-119 | append_utf8_value (const unsigned char *value, size_t length,
struct stringbuf *sb)
{
unsigned char tmp[6];
const unsigned char *s;
size_t n;
int i, nmore;
if (length && (*value == ' ' || *value == '#'))
{
tmp[0] = '\\';
tmp[1] = *value;
put_stringbuf_mem (sb, tmp, 2);
value++;
length--;
}
if (length && value[length-1] == ' ')
{
tmp[0] = '\\';
tmp[1] = ' ';
put_stringbuf_mem (sb, tmp, 2);
length--;
}
for (s=value, n=0;;)
{
for (value = s; n < length && !(*s & 0x80); n++, s++)
for (value = s; n < length && !(*s & 0x80); n++, s++)
;
append_quoted (sb, value, s-value, 0);
if (n==length)
return; /* ready */
if (!(*s & 0x80))
nmore = 0; /* Not expected here: high bit not set. */
else if ( (*s & 0xe0) == 0xc0 ) /* 110x xxxx */
nmore = 1;
else if ( (*s & 0xf0) == 0xe0 ) /* 1110 xxxx */
nmore = 2;
else if ( (*s & 0xf8) == 0xf0 ) /* 1111 0xxx */
nmore = 3;
else if ( (*s & 0xfc) == 0xf8 ) /* 1111 10xx */
nmore = 4;
else if ( (*s & 0xfe) == 0xfc ) /* 1111 110x */
nmore = 5;
else /* Invalid encoding */
nmore = 0;
if (!nmore)
{
/* Encoding error: We quote the bad byte. */
snprintf (tmp, sizeof tmp, "\\%02X", *s);
put_stringbuf_mem (sb, tmp, 3);
s++; n++;
}
else
{
if (n+nmore > length)
nmore = length - n; /* Oops, encoding to short */
tmp[0] = *s++; n++;
for (i=1; i <= nmore; i++)
{
if ( (*s & 0xc0) != 0x80)
break; /* Invalid encoding - let the next cycle detect this. */
tmp[i] = *s++;
n++;
}
put_stringbuf_mem (sb, tmp, i);
}
}
}
| 165,050 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: std::unique_ptr<net::test_server::HttpResponse> GetConfigResponse(
const net::test_server::HttpRequest& request) {
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_content(config_.SerializeAsString());
response->set_content_type("text/plain");
if (config_run_loop_)
config_run_loop_->Quit();
return response;
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | std::unique_ptr<net::test_server::HttpResponse> GetConfigResponse(
const net::test_server::HttpRequest& request) {
// Config should not be fetched when in holdback.
EXPECT_FALSE(
data_reduction_proxy::params::IsIncludedInHoldbackFieldTrial());
auto response = std::make_unique<net::test_server::BasicHttpResponse>();
response->set_content(config_.SerializeAsString());
response->set_content_type("text/plain");
if (config_run_loop_)
config_run_loop_->Quit();
return response;
}
| 172,414 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
}
Commit Message: kvm:vmx: more complete state update on APICv on/off
The function to update APICv on/off state (in particular, to deactivate
it when enabling Hyper-V SynIC) is incomplete: it doesn't adjust
APICv-related fields among secondary processor-based VM-execution
controls. As a result, Windows 2012 guests get stuck when SynIC-based
auto-EOI interrupt intersected with e.g. an IPI in the guest.
In addition, the MSR intercept bitmap isn't updated every time "virtualize
x2APIC mode" is toggled. This path can only be triggered by a malicious
guest, because Windows didn't use x2APIC but rather their own synthetic
APIC access MSRs; however a guest running in a SynIC-enabled VM could
switch to x2APIC and thus obtain direct access to host APIC MSRs
(CVE-2016-4440).
The patch fixes those omissions.
Signed-off-by: Roman Kagan <[email protected]>
Reported-by: Steve Rutherford <[email protected]>
Reported-by: Yang Zhang <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static void vmx_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
{
struct vcpu_vmx *vmx = to_vmx(vcpu);
vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, vmx_pin_based_exec_ctrl(vmx));
if (cpu_has_secondary_exec_ctrls()) {
if (kvm_vcpu_apicv_active(vcpu))
vmcs_set_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
else
vmcs_clear_bits(SECONDARY_VM_EXEC_CONTROL,
SECONDARY_EXEC_APIC_REGISTER_VIRT |
SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY);
}
if (cpu_has_vmx_msr_bitmap())
vmx_set_msr_bitmap(vcpu);
}
| 167,263 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
(void) SeekBlob(image, offset, SEEK_CUR);
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
Commit Message:
CWE ID: CWE-399 | static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
| 168,853 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: jbig2_sd_release(Jbig2Ctx *ctx, Jbig2SymbolDict *dict)
{
int i;
if (dict == NULL)
return;
for (i = 0; i < dict->n_symbols; i++)
if (dict->glyphs[i])
jbig2_image_release(ctx, dict->glyphs[i]);
jbig2_free(ctx->allocator, dict->glyphs);
jbig2_free(ctx->allocator, dict);
}
Commit Message:
CWE ID: CWE-119 | jbig2_sd_release(Jbig2Ctx *ctx, Jbig2SymbolDict *dict)
{
uint32_t i;
if (dict == NULL)
return;
for (i = 0; i < dict->n_symbols; i++)
if (dict->glyphs[i])
jbig2_image_release(ctx, dict->glyphs[i]);
jbig2_free(ctx->allocator, dict->glyphs);
jbig2_free(ctx->allocator, dict);
}
| 165,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: void LauncherView::UpdateFirstButtonPadding() {
if (view_model_->view_size() > 0) {
view_model_->view_at(0)->set_border(views::Border::CreateEmptyBorder(
primary_axis_coordinate(0, kLeadingInset),
primary_axis_coordinate(kLeadingInset, 0),
0,
0));
}
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void LauncherView::UpdateFirstButtonPadding() {
if (view_model_->view_size() > 0) {
view_model_->view_at(0)->set_border(views::Border::CreateEmptyBorder(
primary_axis_coordinate(0, leading_inset()),
primary_axis_coordinate(leading_inset(), 0),
0,
0));
}
}
| 170,897 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: String InspectorPageAgent::CachedResourceTypeJson(
const Resource& cached_resource) {
return ResourceTypeJson(CachedResourceType(cached_resource));
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | String InspectorPageAgent::CachedResourceTypeJson(
const Resource& cached_resource) {
return ResourceTypeJson(ToResourceType(cached_resource.GetType()));
}
| 172,470 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 KioskNextHomeInterfaceBrokerImpl::GetAppController(
mojom::AppControllerRequest request) {
app_controller_->BindRequest(std::move(request));
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | void KioskNextHomeInterfaceBrokerImpl::GetAppController(
mojom::AppControllerRequest request) {
AppControllerService::Get(context_)->BindRequest(std::move(request));
}
| 172,090 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 cp2112_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
struct cp2112_device *dev;
u8 buf[3];
struct cp2112_smbus_config_report config;
int ret;
dev = devm_kzalloc(&hdev->dev, sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->in_out_buffer = devm_kzalloc(&hdev->dev, CP2112_REPORT_MAX_LENGTH,
GFP_KERNEL);
if (!dev->in_out_buffer)
return -ENOMEM;
spin_lock_init(&dev->lock);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
return ret;
}
ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
if (ret) {
hid_err(hdev, "hw start failed\n");
return ret;
}
ret = hid_hw_open(hdev);
if (ret) {
hid_err(hdev, "hw open failed\n");
goto err_hid_stop;
}
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
goto err_hid_close;
}
ret = cp2112_hid_get(hdev, CP2112_GET_VERSION_INFO, buf, sizeof(buf),
HID_FEATURE_REPORT);
if (ret != sizeof(buf)) {
hid_err(hdev, "error requesting version\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_info(hdev, "Part Number: 0x%02X Device Version: 0x%02X\n",
buf[1], buf[2]);
ret = cp2112_hid_get(hdev, CP2112_SMBUS_CONFIG, (u8 *)&config,
sizeof(config), HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error requesting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
config.retry_time = cpu_to_be16(1);
ret = cp2112_hid_output(hdev, (u8 *)&config, sizeof(config),
HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error setting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_set_drvdata(hdev, (void *)dev);
dev->hdev = hdev;
dev->adap.owner = THIS_MODULE;
dev->adap.class = I2C_CLASS_HWMON;
dev->adap.algo = &smbus_algorithm;
dev->adap.algo_data = dev;
dev->adap.dev.parent = &hdev->dev;
snprintf(dev->adap.name, sizeof(dev->adap.name),
"CP2112 SMBus Bridge on hiddev%d", hdev->minor);
dev->hwversion = buf[2];
init_waitqueue_head(&dev->wait);
hid_device_io_start(hdev);
ret = i2c_add_adapter(&dev->adap);
hid_device_io_stop(hdev);
if (ret) {
hid_err(hdev, "error registering i2c adapter\n");
goto err_power_normal;
}
hid_dbg(hdev, "adapter registered\n");
dev->gc.label = "cp2112_gpio";
dev->gc.direction_input = cp2112_gpio_direction_input;
dev->gc.direction_output = cp2112_gpio_direction_output;
dev->gc.set = cp2112_gpio_set;
dev->gc.get = cp2112_gpio_get;
dev->gc.base = -1;
dev->gc.ngpio = 8;
dev->gc.can_sleep = 1;
dev->gc.parent = &hdev->dev;
ret = gpiochip_add_data(&dev->gc, dev);
if (ret < 0) {
hid_err(hdev, "error registering gpio chip\n");
goto err_free_i2c;
}
ret = sysfs_create_group(&hdev->dev.kobj, &cp2112_attr_group);
if (ret < 0) {
hid_err(hdev, "error creating sysfs attrs\n");
goto err_gpiochip_remove;
}
chmod_sysfs_attrs(hdev);
hid_hw_power(hdev, PM_HINT_NORMAL);
ret = gpiochip_irqchip_add(&dev->gc, &cp2112_gpio_irqchip, 0,
handle_simple_irq, IRQ_TYPE_NONE);
if (ret) {
dev_err(dev->gc.parent, "failed to add IRQ chip\n");
goto err_sysfs_remove;
}
return ret;
err_sysfs_remove:
sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
err_gpiochip_remove:
gpiochip_remove(&dev->gc);
err_free_i2c:
i2c_del_adapter(&dev->adap);
err_power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
err_hid_close:
hid_hw_close(hdev);
err_hid_stop:
hid_hw_stop(hdev);
return ret;
}
Commit Message: HID: cp2112: fix sleep-while-atomic
A recent commit fixing DMA-buffers on stack added a shared transfer
buffer protected by a spinlock. This is broken as the USB HID request
callbacks can sleep. Fix this up by replacing the spinlock with a mutex.
Fixes: 1ffb3c40ffb5 ("HID: cp2112: make transfer buffers DMA capable")
Cc: stable <[email protected]> # 4.9
Signed-off-by: Johan Hovold <[email protected]>
Reviewed-by: Benjamin Tissoires <[email protected]>
Signed-off-by: Jiri Kosina <[email protected]>
CWE ID: CWE-404 | static int cp2112_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
struct cp2112_device *dev;
u8 buf[3];
struct cp2112_smbus_config_report config;
int ret;
dev = devm_kzalloc(&hdev->dev, sizeof(*dev), GFP_KERNEL);
if (!dev)
return -ENOMEM;
dev->in_out_buffer = devm_kzalloc(&hdev->dev, CP2112_REPORT_MAX_LENGTH,
GFP_KERNEL);
if (!dev->in_out_buffer)
return -ENOMEM;
mutex_init(&dev->lock);
ret = hid_parse(hdev);
if (ret) {
hid_err(hdev, "parse failed\n");
return ret;
}
ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
if (ret) {
hid_err(hdev, "hw start failed\n");
return ret;
}
ret = hid_hw_open(hdev);
if (ret) {
hid_err(hdev, "hw open failed\n");
goto err_hid_stop;
}
ret = hid_hw_power(hdev, PM_HINT_FULLON);
if (ret < 0) {
hid_err(hdev, "power management error: %d\n", ret);
goto err_hid_close;
}
ret = cp2112_hid_get(hdev, CP2112_GET_VERSION_INFO, buf, sizeof(buf),
HID_FEATURE_REPORT);
if (ret != sizeof(buf)) {
hid_err(hdev, "error requesting version\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_info(hdev, "Part Number: 0x%02X Device Version: 0x%02X\n",
buf[1], buf[2]);
ret = cp2112_hid_get(hdev, CP2112_SMBUS_CONFIG, (u8 *)&config,
sizeof(config), HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error requesting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
config.retry_time = cpu_to_be16(1);
ret = cp2112_hid_output(hdev, (u8 *)&config, sizeof(config),
HID_FEATURE_REPORT);
if (ret != sizeof(config)) {
hid_err(hdev, "error setting SMBus config\n");
if (ret >= 0)
ret = -EIO;
goto err_power_normal;
}
hid_set_drvdata(hdev, (void *)dev);
dev->hdev = hdev;
dev->adap.owner = THIS_MODULE;
dev->adap.class = I2C_CLASS_HWMON;
dev->adap.algo = &smbus_algorithm;
dev->adap.algo_data = dev;
dev->adap.dev.parent = &hdev->dev;
snprintf(dev->adap.name, sizeof(dev->adap.name),
"CP2112 SMBus Bridge on hiddev%d", hdev->minor);
dev->hwversion = buf[2];
init_waitqueue_head(&dev->wait);
hid_device_io_start(hdev);
ret = i2c_add_adapter(&dev->adap);
hid_device_io_stop(hdev);
if (ret) {
hid_err(hdev, "error registering i2c adapter\n");
goto err_power_normal;
}
hid_dbg(hdev, "adapter registered\n");
dev->gc.label = "cp2112_gpio";
dev->gc.direction_input = cp2112_gpio_direction_input;
dev->gc.direction_output = cp2112_gpio_direction_output;
dev->gc.set = cp2112_gpio_set;
dev->gc.get = cp2112_gpio_get;
dev->gc.base = -1;
dev->gc.ngpio = 8;
dev->gc.can_sleep = 1;
dev->gc.parent = &hdev->dev;
ret = gpiochip_add_data(&dev->gc, dev);
if (ret < 0) {
hid_err(hdev, "error registering gpio chip\n");
goto err_free_i2c;
}
ret = sysfs_create_group(&hdev->dev.kobj, &cp2112_attr_group);
if (ret < 0) {
hid_err(hdev, "error creating sysfs attrs\n");
goto err_gpiochip_remove;
}
chmod_sysfs_attrs(hdev);
hid_hw_power(hdev, PM_HINT_NORMAL);
ret = gpiochip_irqchip_add(&dev->gc, &cp2112_gpio_irqchip, 0,
handle_simple_irq, IRQ_TYPE_NONE);
if (ret) {
dev_err(dev->gc.parent, "failed to add IRQ chip\n");
goto err_sysfs_remove;
}
return ret;
err_sysfs_remove:
sysfs_remove_group(&hdev->dev.kobj, &cp2112_attr_group);
err_gpiochip_remove:
gpiochip_remove(&dev->gc);
err_free_i2c:
i2c_del_adapter(&dev->adap);
err_power_normal:
hid_hw_power(hdev, PM_HINT_NORMAL);
err_hid_close:
hid_hw_close(hdev);
err_hid_stop:
hid_hw_stop(hdev);
return ret;
}
| 168,212 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_export_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 ret;
ret = gss_export_sec_context(minor_status,
context_handle,
interprocess_token);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_export_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t interprocess_token)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = *(spnego_gss_ctx_id_t *)context_handle;
/* We don't currently support exporting partially established
* contexts. */
if (!sc->opened)
return GSS_S_UNAVAILABLE;
ret = gss_export_sec_context(minor_status,
&sc->ctx_handle,
interprocess_token);
if (sc->ctx_handle == GSS_C_NO_CONTEXT) {
release_spnego_ctx(&sc);
*context_handle = GSS_C_NO_CONTEXT;
}
return (ret);
}
| 166,655 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 SeekHead::Parse()
{
IMkvReader* const pReader = m_pSegment->m_pReader;
long long pos = m_start;
const long long stop = m_start + m_size;
int entry_count = 0;
int void_element_count = 0;
while (pos < stop)
{
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x0DBB) //SeekEntry ID
++entry_count;
else if (id == 0x6C) //Void ID
++void_element_count;
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
m_entries = new (std::nothrow) Entry[entry_count];
if (m_entries == NULL)
return -1;
m_void_elements = new (std::nothrow) VoidElement[void_element_count];
if (m_void_elements == NULL)
return -1;
Entry* pEntry = m_entries;
VoidElement* pVoidElement = m_void_elements;
pos = m_start;
while (pos < stop)
{
const long long idpos = pos;
long long id, size;
const long status = ParseElementHeader(
pReader,
pos,
stop,
id,
size);
if (status < 0) //error
return status;
if (id == 0x0DBB) //SeekEntry ID
{
if (ParseEntry(pReader, pos, size, pEntry))
{
Entry& e = *pEntry++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
}
else if (id == 0x6C) //Void ID
{
VoidElement& e = *pVoidElement++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
pos += size; //consume payload
assert(pos <= stop);
}
assert(pos == stop);
ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries);
assert(count_ >= 0);
assert(count_ <= entry_count);
m_entry_count = static_cast<int>(count_);
count_ = ptrdiff_t(pVoidElement - m_void_elements);
assert(count_ >= 0);
assert(count_ <= void_element_count);
m_void_element_count = static_cast<int>(count_);
return 0;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long SeekHead::Parse()
long long pos = m_start;
const long long stop = m_start + m_size;
// first count the seek head entries
int entry_count = 0;
int void_element_count = 0;
while (pos < stop) {
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0DBB) // SeekEntry ID
++entry_count;
else if (id == 0x6C) // Void ID
++void_element_count;
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
m_entries = new (std::nothrow) Entry[entry_count];
if (m_entries == NULL)
return -1;
m_void_elements = new (std::nothrow) VoidElement[void_element_count];
if (m_void_elements == NULL)
return -1;
// now parse the entries and void elements
Entry* pEntry = m_entries;
VoidElement* pVoidElement = m_void_elements;
pos = m_start;
while (pos < stop) {
const long long idpos = pos;
long long id, size;
const long status = ParseElementHeader(pReader, pos, stop, id, size);
if (status < 0) // error
return status;
if (id == 0x0DBB) { // SeekEntry ID
if (ParseEntry(pReader, pos, size, pEntry)) {
Entry& e = *pEntry++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
} else if (id == 0x6C) { // Void ID
VoidElement& e = *pVoidElement++;
e.element_start = idpos;
e.element_size = (pos + size) - idpos;
}
pos += size; // consume payload
assert(pos <= stop);
}
assert(pos == stop);
ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries);
assert(count_ >= 0);
assert(count_ <= entry_count);
m_entry_count = static_cast<int>(count_);
count_ = ptrdiff_t(pVoidElement - m_void_elements);
assert(count_ >= 0);
assert(count_ <= void_element_count);
m_void_element_count = static_cast<int>(count_);
return 0;
}
int SeekHead::GetCount() const { return m_entry_count; }
const SeekHead::Entry* SeekHead::GetEntry(int idx) const {
if (idx < 0)
return 0;
if (idx >= m_entry_count)
return 0;
return m_entries + idx;
}
| 174,413 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void reds_handle_ticket(void *opaque)
{
RedLinkInfo *link = (RedLinkInfo *)opaque;
char password[SPICE_MAX_PASSWORD_LENGTH];
time_t ltime;
time(<ime);
RSA_private_decrypt(link->tiTicketing.rsa_size,
link->tiTicketing.encrypted_ticket.encrypted_data,
(unsigned char *)password, link->tiTicketing.rsa, RSA_PKCS1_OAEP_PADDING);
if (ticketing_enabled && !link->skip_auth) {
int expired = taTicket.expiration_time < ltime;
if (strlen(taTicket.password) == 0) {
reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED);
spice_warning("Ticketing is enabled, but no password is set. "
"please set a ticket first");
reds_link_free(link);
return;
}
if (expired || strncmp(password, taTicket.password, SPICE_MAX_PASSWORD_LENGTH) != 0) {
if (expired) {
spice_warning("Ticket has expired");
} else {
spice_warning("Invalid password");
}
reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED);
reds_link_free(link);
return;
}
}
reds_handle_link(link);
}
Commit Message:
CWE ID: CWE-119 | static void reds_handle_ticket(void *opaque)
{
RedLinkInfo *link = (RedLinkInfo *)opaque;
char *password;
time_t ltime;
int password_size;
time(<ime);
if (RSA_size(link->tiTicketing.rsa) < SPICE_MAX_PASSWORD_LENGTH) {
spice_warning("RSA modulus size is smaller than SPICE_MAX_PASSWORD_LENGTH (%d < %d), "
"SPICE ticket sent from client may be truncated",
RSA_size(link->tiTicketing.rsa), SPICE_MAX_PASSWORD_LENGTH);
}
password = g_malloc0(RSA_size(link->tiTicketing.rsa) + 1);
password_size = RSA_private_decrypt(link->tiTicketing.rsa_size,
link->tiTicketing.encrypted_ticket.encrypted_data,
(unsigned char *)password,
link->tiTicketing.rsa,
RSA_PKCS1_OAEP_PADDING);
if (password_size == -1) {
spice_warning("failed to decrypt RSA encrypted password: %s",
ERR_error_string(ERR_get_error(), NULL));
goto error;
}
password[password_size] = '\0';
if (ticketing_enabled && !link->skip_auth) {
int expired = taTicket.expiration_time < ltime;
if (strlen(taTicket.password) == 0) {
spice_warning("Ticketing is enabled, but no password is set. "
"please set a ticket first");
goto error;
}
if (expired || strcmp(password, taTicket.password) != 0) {
if (expired) {
spice_warning("Ticket has expired");
} else {
spice_warning("Invalid password");
}
goto error;
}
}
reds_handle_link(link);
goto end;
error:
reds_send_link_result(link, SPICE_LINK_ERR_PERMISSION_DENIED);
reds_link_free(link);
end:
g_free(password);
}
| 164,661 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: spnego_gss_complete_auth_token(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer)
{
OM_uint32 ret;
ret = gss_complete_auth_token(minor_status,
context_handle,
input_message_buffer);
return (ret);
}
Commit Message: Fix SPNEGO context aliasing bugs [CVE-2015-2695]
The SPNEGO mechanism currently replaces its context handle with the
mechanism context handle upon establishment, under the assumption that
most GSS functions are only called after context establishment. This
assumption is incorrect, and can lead to aliasing violations for some
programs. Maintain the SPNEGO context structure after context
establishment and refer to it in all GSS methods. Add initiate and
opened flags to the SPNEGO context structure for use in
gss_inquire_context() prior to context establishment.
CVE-2015-2695:
In MIT krb5 1.5 and later, applications which call
gss_inquire_context() on a partially-established SPNEGO context can
cause the GSS-API library to read from a pointer using the wrong type,
generally causing a process crash. This bug may go unnoticed, because
the most common SPNEGO authentication scenario establishes the context
after just one call to gss_accept_sec_context(). Java server
applications using the native JGSS provider are vulnerable to this
bug. A carefully crafted SPNEGO packet might allow the
gss_inquire_context() call to succeed with attacker-determined
results, but applications should not make access control decisions
based on gss_inquire_context() results prior to context establishment.
CVSSv2 Vector: AV:N/AC:M/Au:N/C:N/I:N/A:C/E:POC/RL:OF/RC:C
[[email protected]: several bugfixes, style changes, and edge-case
behavior changes; commit message and CVE description]
ticket: 8244
target_version: 1.14
tags: pullup
CWE ID: CWE-18 | spnego_gss_complete_auth_token(
OM_uint32 *minor_status,
const gss_ctx_id_t context_handle,
gss_buffer_t input_message_buffer)
{
OM_uint32 ret;
spnego_gss_ctx_id_t sc = (spnego_gss_ctx_id_t)context_handle;
if (sc->ctx_handle == GSS_C_NO_CONTEXT)
return (GSS_S_UNAVAILABLE);
ret = gss_complete_auth_token(minor_status,
sc->ctx_handle,
input_message_buffer);
return (ret);
}
| 166,652 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
{
element()->setFocus(true);
}
Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree.
destroyShadowSubtree could dispatch 'blur' event unexpectedly because
element()->focused() had incorrect information. We make sure it has
correct information by checking if the UA shadow root contains the
focused element.
BUG=257353
Review URL: https://chromiumcodereview.appspot.com/19067004
git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
{
if (!containsFocusedShadowElement())
return;
element()->setFocus(true);
}
| 171,212 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 FileSystemOperation::GetUsageAndQuotaThenRunTask(
const GURL& origin, FileSystemType type,
const base::Closure& task,
const base::Closure& error_callback) {
quota::QuotaManagerProxy* quota_manager_proxy =
file_system_context()->quota_manager_proxy();
if (!quota_manager_proxy ||
!file_system_context()->GetQuotaUtil(type)) {
operation_context_.set_allowed_bytes_growth(kint64max);
task.Run();
return;
}
TaskParamsForDidGetQuota params;
params.origin = origin;
params.type = type;
params.task = task;
params.error_callback = error_callback;
DCHECK(quota_manager_proxy);
DCHECK(quota_manager_proxy->quota_manager());
quota_manager_proxy->quota_manager()->GetUsageAndQuota(
origin,
FileSystemTypeToQuotaStorageType(type),
base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask,
base::Unretained(this), params));
}
Commit Message: Crash fix in fileapi::FileSystemOperation::DidGetUsageAndQuotaAndRunTask
https://chromiumcodereview.appspot.com/10008047 introduced delete-with-inflight-tasks in Write sequence but I failed to convert this callback to use WeakPtr().
BUG=128178
TEST=manual test
Review URL: https://chromiumcodereview.appspot.com/10408006
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137635 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void FileSystemOperation::GetUsageAndQuotaThenRunTask(
const GURL& origin, FileSystemType type,
const base::Closure& task,
const base::Closure& error_callback) {
quota::QuotaManagerProxy* quota_manager_proxy =
file_system_context()->quota_manager_proxy();
if (!quota_manager_proxy ||
!file_system_context()->GetQuotaUtil(type)) {
operation_context_.set_allowed_bytes_growth(kint64max);
task.Run();
return;
}
TaskParamsForDidGetQuota params;
params.origin = origin;
params.type = type;
params.task = task;
params.error_callback = error_callback;
DCHECK(quota_manager_proxy);
DCHECK(quota_manager_proxy->quota_manager());
quota_manager_proxy->quota_manager()->GetUsageAndQuota(
origin,
FileSystemTypeToQuotaStorageType(type),
base::Bind(&FileSystemOperation::DidGetUsageAndQuotaAndRunTask,
weak_factory_.GetWeakPtr(), params));
}
| 170,762 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, descsz);
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
RCAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
case OS_STYLE_FREEBSD:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t argoff, pidoff;
if (clazz == ELFCLASS32)
argoff = 4 + 4 + 17;
else
argoff = 4 + 4 + 8 + 17;
if (file_printf(ms, ", from '%.80s'", nbuf + doff +
argoff) == -1)
return 1;
pidoff = argoff + 81 + 2;
if (doff + pidoff + 4 <= size) {
if (file_printf(ms, ", pid=%u",
elf_getu32(swap, *RCAST(uint32_t *, (nbuf +
doff + pidoff)))) == -1)
return 1;
}
*flags |= FLAGS_DID_CORE;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; cp < nbuf + size && *cp
&& isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
Commit Message: Avoid OOB read (found by ASAN reported by F. Alonso)
CWE ID: CWE-125 | do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi)));
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
RCAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
case OS_STYLE_FREEBSD:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t argoff, pidoff;
if (clazz == ELFCLASS32)
argoff = 4 + 4 + 17;
else
argoff = 4 + 4 + 8 + 17;
if (file_printf(ms, ", from '%.80s'", nbuf + doff +
argoff) == -1)
return 1;
pidoff = argoff + 81 + 2;
if (doff + pidoff + 4 <= size) {
if (file_printf(ms, ", pid=%u",
elf_getu32(swap, *RCAST(uint32_t *, (nbuf +
doff + pidoff)))) == -1)
return 1;
}
*flags |= FLAGS_DID_CORE;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; cp < nbuf + size && *cp
&& isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
| 169,727 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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_vdec::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr)
{
unsigned int index = 0;
if (bufferHdr == NULL || m_inp_mem_ptr == NULL) {
return OMX_ErrorBadParameter;
}
index = bufferHdr - m_inp_mem_ptr;
DEBUG_PRINT_LOW("Free Input Buffer index = %d",index);
if (index < drv_ctx.ip_buf.actualcount && drv_ctx.ptr_inputbuffer) {
DEBUG_PRINT_LOW("Free Input Buffer index = %d",index);
if (drv_ctx.ptr_inputbuffer[index].pmem_fd > 0) {
struct vdec_setbuffer_cmd setbuffers;
setbuffers.buffer_type = VDEC_BUFFER_TYPE_INPUT;
memcpy (&setbuffers.buffer,&drv_ctx.ptr_inputbuffer[index],
sizeof (vdec_bufferpayload));
if (!secure_mode) {
DEBUG_PRINT_LOW("unmap the input buffer fd=%d",
drv_ctx.ptr_inputbuffer[index].pmem_fd);
DEBUG_PRINT_LOW("unmap the input buffer size=%u address = %p",
(unsigned int)drv_ctx.ptr_inputbuffer[index].mmaped_size,
drv_ctx.ptr_inputbuffer[index].bufferaddr);
munmap (drv_ctx.ptr_inputbuffer[index].bufferaddr,
drv_ctx.ptr_inputbuffer[index].mmaped_size);
}
close (drv_ctx.ptr_inputbuffer[index].pmem_fd);
drv_ctx.ptr_inputbuffer[index].pmem_fd = -1;
if (m_desc_buffer_ptr && m_desc_buffer_ptr[index].buf_addr) {
free(m_desc_buffer_ptr[index].buf_addr);
m_desc_buffer_ptr[index].buf_addr = NULL;
m_desc_buffer_ptr[index].desc_data_size = 0;
}
#ifdef USE_ION
free_ion_memory(&drv_ctx.ip_buf_ion_info[index]);
#endif
}
}
return OMX_ErrorNone;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: Avoid processing ETBs/FTBs in invalid states
(per the spec) ETB/FTB should not be handled in states other than
Executing, Paused and Idle. This avoids accessing invalid buffers.
Also add a lock to protect the private-buffers from being deleted
while accessing from another thread.
Bug: 27890802
Security Vulnerability - Heap Use-After-Free and Possible LPE in
MediaServer (libOmxVdec problem #6)
CRs-Fixed: 1008882
Change-Id: Iaac2e383cd53cf9cf8042c9ed93ddc76dba3907e
CWE ID: | OMX_ERRORTYPE omx_vdec::free_input_buffer(OMX_BUFFERHEADERTYPE *bufferHdr)
{
unsigned int index = 0;
if (bufferHdr == NULL || m_inp_mem_ptr == NULL) {
return OMX_ErrorBadParameter;
}
index = bufferHdr - m_inp_mem_ptr;
DEBUG_PRINT_LOW("Free Input Buffer index = %d",index);
auto_lock l(buf_lock);
bufferHdr->pInputPortPrivate = NULL;
if (index < drv_ctx.ip_buf.actualcount && drv_ctx.ptr_inputbuffer) {
DEBUG_PRINT_LOW("Free Input Buffer index = %d",index);
if (drv_ctx.ptr_inputbuffer[index].pmem_fd > 0) {
struct vdec_setbuffer_cmd setbuffers;
setbuffers.buffer_type = VDEC_BUFFER_TYPE_INPUT;
memcpy (&setbuffers.buffer,&drv_ctx.ptr_inputbuffer[index],
sizeof (vdec_bufferpayload));
if (!secure_mode) {
DEBUG_PRINT_LOW("unmap the input buffer fd=%d",
drv_ctx.ptr_inputbuffer[index].pmem_fd);
DEBUG_PRINT_LOW("unmap the input buffer size=%u address = %p",
(unsigned int)drv_ctx.ptr_inputbuffer[index].mmaped_size,
drv_ctx.ptr_inputbuffer[index].bufferaddr);
munmap (drv_ctx.ptr_inputbuffer[index].bufferaddr,
drv_ctx.ptr_inputbuffer[index].mmaped_size);
}
close (drv_ctx.ptr_inputbuffer[index].pmem_fd);
drv_ctx.ptr_inputbuffer[index].pmem_fd = -1;
if (m_desc_buffer_ptr && m_desc_buffer_ptr[index].buf_addr) {
free(m_desc_buffer_ptr[index].buf_addr);
m_desc_buffer_ptr[index].buf_addr = NULL;
m_desc_buffer_ptr[index].desc_data_size = 0;
}
#ifdef USE_ION
free_ion_memory(&drv_ctx.ip_buf_ion_info[index]);
#endif
}
}
return OMX_ErrorNone;
}
| 173,752 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: AppControllerImpl::AppControllerImpl(Profile* profile)
//// static
: profile_(profile),
app_service_proxy_(apps::AppServiceProxy::Get(profile)),
url_prefix_(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
chromeos::switches::kKioskNextHomeUrlPrefix)) {
app_service_proxy_->AppRegistryCache().AddObserver(this);
if (profile) {
content::URLDataSource::Add(profile,
std::make_unique<apps::AppIconSource>(profile));
}
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | AppControllerImpl::AppControllerImpl(Profile* profile)
//// static
AppControllerService* AppControllerService::Get(
content::BrowserContext* context) {
return AppControllerServiceFactory::GetForBrowserContext(context);
}
AppControllerService::AppControllerService(Profile* profile)
: profile_(profile),
app_service_proxy_(apps::AppServiceProxy::Get(profile)),
url_prefix_(base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
chromeos::switches::kKioskNextHomeUrlPrefix)) {
DCHECK(profile);
app_service_proxy_->AppRegistryCache().AddObserver(this);
content::URLDataSource::Add(profile,
std::make_unique<apps::AppIconSource>(profile));
}
| 172,079 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this,
image_pixel *that, png_const_structp pp,
PNG_CONST transform_display *display)
{
/* NOTE: we can actually pend the tRNS processing at this point because we
* can correctly recognize the original pixel value even though we have
* mapped the one gray channel to the three RGB ones, but in fact libpng
* doesn't do this, so we don't either.
*/
if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
image_pixel_add_alpha(that, &display->this);
/* Simply expand the bit depth and alter the colour type as required. */
if (that->colour_type == PNG_COLOR_TYPE_GRAY)
{
/* RGB images have a bit depth at least equal to '8' */
if (that->bit_depth < 8)
that->sample_depth = that->bit_depth = 8;
/* And just changing the colour type works here because the green and blue
* channels are being maintained in lock-step with the red/gray:
*/
that->colour_type = PNG_COLOR_TYPE_RGB;
}
else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
this->next->mod(this->next, that, pp, display);
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this,
image_transform_png_set_gray_to_rgb_mod(const image_transform *this,
image_pixel *that, png_const_structp pp,
const transform_display *display)
{
/* NOTE: we can actually pend the tRNS processing at this point because we
* can correctly recognize the original pixel value even though we have
* mapped the one gray channel to the three RGB ones, but in fact libpng
* doesn't do this, so we don't either.
*/
if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS)
image_pixel_add_alpha(that, &display->this, 0/*!for background*/);
/* Simply expand the bit depth and alter the colour type as required. */
if (that->colour_type == PNG_COLOR_TYPE_GRAY)
{
/* RGB images have a bit depth at least equal to '8' */
if (that->bit_depth < 8)
that->sample_depth = that->bit_depth = 8;
/* And just changing the colour type works here because the green and blue
* channels are being maintained in lock-step with the red/gray:
*/
that->colour_type = PNG_COLOR_TYPE_RGB;
}
else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA)
that->colour_type = PNG_COLOR_TYPE_RGB_ALPHA;
this->next->mod(this->next, that, pp, display);
}
| 173,636 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebsiteSettingsPopupAndroid::WebsiteSettingsPopupAndroid(
JNIEnv* env,
jobject java_website_settings_pop,
content::WebContents* web_contents) {
content::NavigationEntry* nav_entry =
web_contents->GetController().GetVisibleEntry();
if (nav_entry == NULL)
return;
url_ = nav_entry->GetURL();
popup_jobject_.Reset(env, java_website_settings_pop);
presenter_.reset(new WebsiteSettings(
this,
Profile::FromBrowserContext(web_contents->GetBrowserContext()),
TabSpecificContentSettings::FromWebContents(web_contents),
InfoBarService::FromWebContents(web_contents),
nav_entry->GetURL(),
nav_entry->GetSSL(),
content::CertStore::GetInstance()));
}
Commit Message: Fix UAF in Origin Info Bubble and permission settings UI.
In addition to fixing the UAF, will this also fix the problem of the bubble
showing over the previous tab (if the bubble is open when the tab it was opened
for closes).
BUG=490492
TBR=tedchoc
Review URL: https://codereview.chromium.org/1317443002
Cr-Commit-Position: refs/heads/master@{#346023}
CWE ID: | WebsiteSettingsPopupAndroid::WebsiteSettingsPopupAndroid(
JNIEnv* env,
jobject java_website_settings_pop,
content::WebContents* web_contents) {
content::NavigationEntry* nav_entry =
web_contents->GetController().GetVisibleEntry();
if (nav_entry == NULL)
return;
url_ = nav_entry->GetURL();
popup_jobject_.Reset(env, java_website_settings_pop);
presenter_.reset(new WebsiteSettings(
this,
Profile::FromBrowserContext(web_contents->GetBrowserContext()),
TabSpecificContentSettings::FromWebContents(web_contents),
web_contents,
nav_entry->GetURL(),
nav_entry->GetSSL(),
content::CertStore::GetInstance()));
}
| 171,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void process_tree(struct rev_info *revs,
struct tree *tree,
show_object_fn show,
struct strbuf *base,
const char *name,
void *cb_data)
{
struct object *obj = &tree->object;
struct tree_desc desc;
struct name_entry entry;
enum interesting match = revs->diffopt.pathspec.nr == 0 ?
all_entries_interesting: entry_not_interesting;
int baselen = base->len;
if (!revs->tree_objects)
return;
if (!obj)
die("bad tree object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) {
if (revs->ignore_missing_links)
return;
die("bad tree object %s", oid_to_hex(&obj->oid));
}
obj->flags |= SEEN;
show(obj, base, name, cb_data);
strbuf_addstr(base, name);
if (base->len)
strbuf_addch(base, '/');
init_tree_desc(&desc, tree->buffer, tree->size);
while (tree_entry(&desc, &entry)) {
if (match != all_entries_interesting) {
match = tree_entry_interesting(&entry, base, 0,
&revs->diffopt.pathspec);
if (match == all_entries_not_interesting)
break;
if (match == entry_not_interesting)
continue;
}
if (S_ISDIR(entry.mode))
process_tree(revs,
lookup_tree(entry.sha1),
show, base, entry.path,
cb_data);
else if (S_ISGITLINK(entry.mode))
process_gitlink(revs, entry.sha1,
show, base, entry.path,
cb_data);
else
process_blob(revs,
lookup_blob(entry.sha1),
show, base, entry.path,
cb_data);
}
strbuf_setlen(base, baselen);
free_tree_buffer(tree);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static void process_tree(struct rev_info *revs,
struct tree *tree,
show_object_fn show,
struct strbuf *base,
const char *name,
void *cb_data)
{
struct object *obj = &tree->object;
struct tree_desc desc;
struct name_entry entry;
enum interesting match = revs->diffopt.pathspec.nr == 0 ?
all_entries_interesting: entry_not_interesting;
int baselen = base->len;
if (!revs->tree_objects)
return;
if (!obj)
die("bad tree object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
if (parse_tree_gently(tree, revs->ignore_missing_links) < 0) {
if (revs->ignore_missing_links)
return;
die("bad tree object %s", oid_to_hex(&obj->oid));
}
obj->flags |= SEEN;
strbuf_addstr(base, name);
show(obj, base->buf, cb_data);
if (base->len)
strbuf_addch(base, '/');
init_tree_desc(&desc, tree->buffer, tree->size);
while (tree_entry(&desc, &entry)) {
if (match != all_entries_interesting) {
match = tree_entry_interesting(&entry, base, 0,
&revs->diffopt.pathspec);
if (match == all_entries_not_interesting)
break;
if (match == entry_not_interesting)
continue;
}
if (S_ISDIR(entry.mode))
process_tree(revs,
lookup_tree(entry.sha1),
show, base, entry.path,
cb_data);
else if (S_ISGITLINK(entry.mode))
process_gitlink(revs, entry.sha1,
show, base, entry.path,
cb_data);
else
process_blob(revs,
lookup_blob(entry.sha1),
show, base, entry.path,
cb_data);
}
strbuf_setlen(base, baselen);
free_tree_buffer(tree);
}
| 167,419 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the 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 AXObject::isHiddenForTextAlternativeCalculation() const {
if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false"))
return false;
if (getLayoutObject())
return getLayoutObject()->style()->visibility() != EVisibility::kVisible;
Document* document = getDocument();
if (!document || !document->frame())
return false;
if (Node* node = getNode()) {
if (node->isConnected() && node->isElementNode()) {
RefPtr<ComputedStyle> style =
document->ensureStyleResolver().styleForElement(toElement(node));
return style->display() == EDisplay::kNone ||
style->visibility() != EVisibility::kVisible;
}
}
return false;
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXObject::isHiddenForTextAlternativeCalculation() const {
if (equalIgnoringASCIICase(getAttribute(aria_hiddenAttr), "false"))
return false;
if (getLayoutObject())
return getLayoutObject()->style()->visibility() != EVisibility::kVisible;
Document* document = getDocument();
if (!document || !document->frame())
return false;
if (Node* node = getNode()) {
if (node->isConnected() && node->isElementNode()) {
RefPtr<ComputedStyle> style =
document->ensureStyleResolver().styleForElement(toElement(node));
return style->display() == EDisplay::kNone ||
style->visibility() != EVisibility::kVisible;
}
}
return false;
}
| 171,926 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XGetDeviceControl(
register Display *dpy,
XDevice *dev,
int control)
{
XDeviceControl *Device = NULL;
XDeviceControl *Sav = NULL;
xDeviceState *d = NULL;
xDeviceState *sav = NULL;
xGetDeviceControlReq *req;
xGetDeviceControlReply rep;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Add_XChangeDeviceControl, info) == -1)
return NULL;
GetReq(GetDeviceControl, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetDeviceControl;
req->deviceid = dev->device_id;
req->control = control;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
goto out;
if (rep.length > 0) {
unsigned long nbytes;
size_t size = 0;
if (rep.length < (INT_MAX >> 2)) {
nbytes = (unsigned long) rep.length << 2;
d = Xmalloc(nbytes);
}
_XEatDataWords(dpy, rep.length);
goto out;
}
sav = d;
_XRead(dpy, (char *)d, nbytes);
/* In theory, we should just be able to use d->length to get the size.
* Turns out that a number of X servers (up to and including server
* 1.4) sent the wrong length value down the wire. So to not break
* apps that run against older servers, we have to calculate the size
* manually.
*/
switch (d->control) {
case DEVICE_RESOLUTION:
{
xDeviceResolutionState *r;
size_t val_size;
size_t val_size;
r = (xDeviceResolutionState *) d;
if (r->num_valuators >= (INT_MAX / (3 * sizeof(int))))
goto out;
val_size = 3 * sizeof(int) * r->num_valuators;
if ((sizeof(xDeviceResolutionState) + val_size) > nbytes)
break;
}
case DEVICE_ABS_CALIB:
{
if (sizeof(xDeviceAbsCalibState) > nbytes)
goto out;
size = sizeof(XDeviceAbsCalibState);
break;
}
case DEVICE_ABS_AREA:
{
if (sizeof(xDeviceAbsAreaState) > nbytes)
goto out;
size = sizeof(XDeviceAbsAreaState);
break;
}
case DEVICE_CORE:
{
if (sizeof(xDeviceCoreState) > nbytes)
goto out;
size = sizeof(XDeviceCoreState);
break;
}
default:
if (d->length > nbytes)
goto out;
size = d->length;
break;
}
Device = Xmalloc(size);
if (!Device)
goto out;
Sav = Device;
d = sav;
switch (control) {
case DEVICE_RESOLUTION:
{
int *iptr, *iptr2;
xDeviceResolutionState *r;
XDeviceResolutionState *R;
unsigned int i;
r = (xDeviceResolutionState *) d;
R = (XDeviceResolutionState *) Device;
R->control = DEVICE_RESOLUTION;
R->length = sizeof(XDeviceResolutionState);
R->num_valuators = r->num_valuators;
iptr = (int *)(R + 1);
iptr2 = (int *)(r + 1);
R->resolutions = iptr;
R->min_resolutions = iptr + R->num_valuators;
R->max_resolutions = iptr + (2 * R->num_valuators);
for (i = 0; i < (3 * R->num_valuators); i++)
*iptr++ = *iptr2++;
break;
}
case DEVICE_ABS_CALIB:
{
xDeviceAbsCalibState *c = (xDeviceAbsCalibState *) d;
XDeviceAbsCalibState *C = (XDeviceAbsCalibState *) Device;
C->control = DEVICE_ABS_CALIB;
C->length = sizeof(XDeviceAbsCalibState);
C->min_x = c->min_x;
C->max_x = c->max_x;
C->min_y = c->min_y;
C->max_y = c->max_y;
C->flip_x = c->flip_x;
C->flip_y = c->flip_y;
C->rotation = c->rotation;
C->button_threshold = c->button_threshold;
break;
}
case DEVICE_ABS_AREA:
{
xDeviceAbsAreaState *a = (xDeviceAbsAreaState *) d;
XDeviceAbsAreaState *A = (XDeviceAbsAreaState *) Device;
A->control = DEVICE_ABS_AREA;
A->length = sizeof(XDeviceAbsAreaState);
A->offset_x = a->offset_x;
A->offset_y = a->offset_y;
A->width = a->width;
A->height = a->height;
A->screen = a->screen;
A->following = a->following;
break;
}
case DEVICE_CORE:
{
xDeviceCoreState *c = (xDeviceCoreState *) d;
XDeviceCoreState *C = (XDeviceCoreState *) Device;
C->control = DEVICE_CORE;
C->length = sizeof(XDeviceCoreState);
C->status = c->status;
C->iscore = c->iscore;
break;
}
case DEVICE_ENABLE:
{
xDeviceEnableState *e = (xDeviceEnableState *) d;
XDeviceEnableState *E = (XDeviceEnableState *) Device;
E->control = DEVICE_ENABLE;
E->length = sizeof(E);
E->enable = e->enable;
break;
}
default:
break;
}
}
Commit Message:
CWE ID: CWE-284 | XGetDeviceControl(
register Display *dpy,
XDevice *dev,
int control)
{
XDeviceControl *Device = NULL;
XDeviceControl *Sav = NULL;
xDeviceState *d = NULL;
xDeviceState *sav = NULL;
xGetDeviceControlReq *req;
xGetDeviceControlReply rep;
XExtDisplayInfo *info = XInput_find_display(dpy);
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Add_XChangeDeviceControl, info) == -1)
return NULL;
GetReq(GetDeviceControl, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetDeviceControl;
req->deviceid = dev->device_id;
req->control = control;
if (!_XReply(dpy, (xReply *) & rep, 0, xFalse))
goto out;
if (rep.length > 0) {
unsigned long nbytes;
size_t size = 0;
if (rep.length < (INT_MAX >> 2) &&
(rep.length << 2) >= sizeof(xDeviceState)) {
nbytes = (unsigned long) rep.length << 2;
d = Xmalloc(nbytes);
}
_XEatDataWords(dpy, rep.length);
goto out;
}
sav = d;
_XRead(dpy, (char *)d, nbytes);
/* In theory, we should just be able to use d->length to get the size.
* Turns out that a number of X servers (up to and including server
* 1.4) sent the wrong length value down the wire. So to not break
* apps that run against older servers, we have to calculate the size
* manually.
*/
switch (d->control) {
case DEVICE_RESOLUTION:
{
xDeviceResolutionState *r;
size_t val_size;
size_t val_size;
r = (xDeviceResolutionState *) d;
if (sizeof(xDeviceResolutionState) > nbytes ||
r->num_valuators >= (INT_MAX / (3 * sizeof(int))))
goto out;
val_size = 3 * sizeof(int) * r->num_valuators;
if ((sizeof(xDeviceResolutionState) + val_size) > nbytes)
break;
}
case DEVICE_ABS_CALIB:
{
if (sizeof(xDeviceAbsCalibState) > nbytes)
goto out;
size = sizeof(XDeviceAbsCalibState);
break;
}
case DEVICE_ABS_AREA:
{
if (sizeof(xDeviceAbsAreaState) > nbytes)
goto out;
size = sizeof(XDeviceAbsAreaState);
break;
}
case DEVICE_CORE:
{
if (sizeof(xDeviceCoreState) > nbytes)
goto out;
size = sizeof(XDeviceCoreState);
break;
}
default:
if (d->length > nbytes)
goto out;
size = d->length;
break;
}
Device = Xmalloc(size);
if (!Device)
goto out;
Sav = Device;
d = sav;
switch (control) {
case DEVICE_RESOLUTION:
{
int *iptr, *iptr2;
xDeviceResolutionState *r;
XDeviceResolutionState *R;
unsigned int i;
r = (xDeviceResolutionState *) d;
R = (XDeviceResolutionState *) Device;
R->control = DEVICE_RESOLUTION;
R->length = sizeof(XDeviceResolutionState);
R->num_valuators = r->num_valuators;
iptr = (int *)(R + 1);
iptr2 = (int *)(r + 1);
R->resolutions = iptr;
R->min_resolutions = iptr + R->num_valuators;
R->max_resolutions = iptr + (2 * R->num_valuators);
for (i = 0; i < (3 * R->num_valuators); i++)
*iptr++ = *iptr2++;
break;
}
case DEVICE_ABS_CALIB:
{
xDeviceAbsCalibState *c = (xDeviceAbsCalibState *) d;
XDeviceAbsCalibState *C = (XDeviceAbsCalibState *) Device;
C->control = DEVICE_ABS_CALIB;
C->length = sizeof(XDeviceAbsCalibState);
C->min_x = c->min_x;
C->max_x = c->max_x;
C->min_y = c->min_y;
C->max_y = c->max_y;
C->flip_x = c->flip_x;
C->flip_y = c->flip_y;
C->rotation = c->rotation;
C->button_threshold = c->button_threshold;
break;
}
case DEVICE_ABS_AREA:
{
xDeviceAbsAreaState *a = (xDeviceAbsAreaState *) d;
XDeviceAbsAreaState *A = (XDeviceAbsAreaState *) Device;
A->control = DEVICE_ABS_AREA;
A->length = sizeof(XDeviceAbsAreaState);
A->offset_x = a->offset_x;
A->offset_y = a->offset_y;
A->width = a->width;
A->height = a->height;
A->screen = a->screen;
A->following = a->following;
break;
}
case DEVICE_CORE:
{
xDeviceCoreState *c = (xDeviceCoreState *) d;
XDeviceCoreState *C = (XDeviceCoreState *) Device;
C->control = DEVICE_CORE;
C->length = sizeof(XDeviceCoreState);
C->status = c->status;
C->iscore = c->iscore;
break;
}
case DEVICE_ENABLE:
{
xDeviceEnableState *e = (xDeviceEnableState *) d;
XDeviceEnableState *E = (XDeviceEnableState *) Device;
E->control = DEVICE_ENABLE;
E->length = sizeof(E);
E->enable = e->enable;
break;
}
default:
break;
}
}
| 164,918 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.