instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct raw6_frag_vec rfv;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
rfv.msg = msg;
rfv.hlen = 0;
err = rawv6_probe_proto_opt(&rfv, &fl6);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
if (inet->hdrincl)
fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, raw6_getfrag, &rfv,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static int rawv6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions *opt_to_free = NULL;
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct raw6_sock *rp = raw6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct raw6_frag_vec rfv;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
u16 proto;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (sin6) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (sin6->sin6_family && sin6->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
/* port is the proto value [0..255] carried in nexthdr */
proto = ntohs(sin6->sin6_port);
if (!proto)
proto = inet->inet_num;
else if (proto != inet->inet_num)
return -EINVAL;
if (proto > 255)
return -EINVAL;
daddr = &sin6->sin6_addr;
if (np->sndflow) {
fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
sin6->sin6_scope_id &&
__ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr)))
fl6.flowi6_oif = sin6->sin6_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
proto = inet->inet_num;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (!flowlabel)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt) {
opt = txopt_get(np);
opt_to_free = opt;
}
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = proto;
rfv.msg = msg;
rfv.hlen = 0;
err = rawv6_probe_proto_opt(&rfv, &fl6);
if (err)
goto out;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
if (inet->hdrincl)
fl6.flowi6_flags |= FLOWI_FLAG_KNOWN_NH;
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags&MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
if (inet->hdrincl)
err = rawv6_send_hdrinc(sk, msg, len, &fl6, &dst, msg->msg_flags);
else {
lock_sock(sk);
err = ip6_append_data(sk, raw6_getfrag, &rfv,
len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = rawv6_push_pending_frames(sk, &fl6, rp);
release_sock(sk);
}
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
txopt_put(opt_to_free);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
| 167,338 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, int sh_num)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
Commit Message: - Add a limit to the number of ELF notes processed (Suggested by Alexander
Cherepanov)
- Restructure ELF note printing so that we don't print the same message
multiple times on repeated notes of the same kind.
CWE ID: CWE-399 | dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int sh_num, int *flags,
uint16_t *notecount)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
const char *interp = "";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment 0x%lx",
(unsigned long)align) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
break;
default:
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xph_type) {
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
interp = (const char *)nbuf;
} else
interp = "*empty*";
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
(size_t)bufsize, clazz, swap, align,
flags, notecount);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
| 166,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SeekHead::~SeekHead()
{
delete[] m_entries;
delete[] m_void_elements;
}
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 | SeekHead::~SeekHead()
SeekHead::~SeekHead() {
delete[] m_entries;
delete[] m_void_elements;
}
| 174,469 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gss_wrap_aead (minor_status,
context_handle,
conf_req_flag,
qop_req,
input_assoc_buffer,
input_payload_buffer,
conf_state,
output_message_buffer)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
gss_buffer_t input_assoc_buffer;
gss_buffer_t input_payload_buffer;
int * conf_state;
gss_buffer_t output_message_buffer;
{
OM_uint32 status;
gss_mechanism mech;
gss_union_ctx_id_t ctx;
status = val_wrap_aead_args(minor_status, context_handle,
conf_req_flag, qop_req,
input_assoc_buffer, input_payload_buffer,
conf_state, output_message_buffer);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t)context_handle;
mech = gssint_get_mechanism (ctx->mech_type);
if (!mech)
return (GSS_S_BAD_MECH);
return gssint_wrap_aead(mech, minor_status, ctx,
conf_req_flag, qop_req,
input_assoc_buffer, input_payload_buffer,
conf_state, output_message_buffer);
}
Commit Message: Preserve GSS context on init/accept failure
After gss_init_sec_context() or gss_accept_sec_context() has created a
context, don't delete the mechglue context on failures from subsequent
calls, even if the mechanism deletes the mech-specific context (which
is allowed by RFC 2744 but not preferred). Check for union contexts
with no mechanism context in each GSS function which accepts a
gss_ctx_id_t.
CVE-2017-11462:
RFC 2744 permits a GSS-API implementation to delete an existing
security context on a second or subsequent call to
gss_init_sec_context() or gss_accept_sec_context() if the call results
in an error. This API behavior has been found to be dangerous,
leading to the possibility of memory errors in some callers. For
safety, GSS-API implementations should instead preserve existing
security contexts on error until the caller deletes them.
All versions of MIT krb5 prior to this change may delete acceptor
contexts on error. Versions 1.13.4 through 1.13.7, 1.14.1 through
1.14.5, and 1.15 through 1.15.1 may also delete initiator contexts on
error.
ticket: 8598 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-415 | gss_wrap_aead (minor_status,
context_handle,
conf_req_flag,
qop_req,
input_assoc_buffer,
input_payload_buffer,
conf_state,
output_message_buffer)
OM_uint32 * minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
gss_buffer_t input_assoc_buffer;
gss_buffer_t input_payload_buffer;
int * conf_state;
gss_buffer_t output_message_buffer;
{
OM_uint32 status;
gss_mechanism mech;
gss_union_ctx_id_t ctx;
status = val_wrap_aead_args(minor_status, context_handle,
conf_req_flag, qop_req,
input_assoc_buffer, input_payload_buffer,
conf_state, output_message_buffer);
if (status != GSS_S_COMPLETE)
return (status);
/*
* select the approprate underlying mechanism routine and
* call it.
*/
ctx = (gss_union_ctx_id_t)context_handle;
if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT)
return (GSS_S_NO_CONTEXT);
mech = gssint_get_mechanism (ctx->mech_type);
if (!mech)
return (GSS_S_BAD_MECH);
return gssint_wrap_aead(mech, minor_status, ctx,
conf_req_flag, qop_req,
input_assoc_buffer, input_payload_buffer,
conf_state, output_message_buffer);
}
| 168,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: rpl_print(netdissect_options *ndo,
const struct icmp6_hdr *hdr,
const u_char *bp, u_int length)
{
int secured = hdr->icmp6_code & 0x80;
int basecode= hdr->icmp6_code & 0x7f;
if(secured) {
ND_PRINT((ndo, ", (SEC) [worktodo]"));
/* XXX
* the next header pointer needs to move forward to
* skip the secure part.
*/
return;
} else {
ND_PRINT((ndo, ", (CLR)"));
}
switch(basecode) {
case ND_RPL_DAG_IS:
ND_PRINT((ndo, "DODAG Information Solicitation"));
if(ndo->ndo_vflag) {
}
break;
case ND_RPL_DAG_IO:
ND_PRINT((ndo, "DODAG Information Object"));
if(ndo->ndo_vflag) {
rpl_dio_print(ndo, bp, length);
}
break;
case ND_RPL_DAO:
ND_PRINT((ndo, "Destination Advertisement Object"));
if(ndo->ndo_vflag) {
rpl_dao_print(ndo, bp, length);
}
break;
case ND_RPL_DAO_ACK:
ND_PRINT((ndo, "Destination Advertisement Object Ack"));
if(ndo->ndo_vflag) {
rpl_daoack_print(ndo, bp, length);
}
break;
default:
ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code));
break;
}
return;
#if 0
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
#endif
}
Commit Message: (for 4.9.3) CVE-2018-14882/ICMP6 RPL: Add a missing bounds check
Moreover:
Add and use *_tstr[] strings.
Update four tests outputs accordingly.
Fix a space.
Wang Junjie of 360 ESG Codesafe Team had independently identified this
vulnerability in 2018 by means of fuzzing and provided the packet capture
file for the test.
CWE ID: CWE-125 | rpl_print(netdissect_options *ndo,
const struct icmp6_hdr *hdr,
const u_char *bp, u_int length)
{
int secured = hdr->icmp6_code & 0x80;
int basecode= hdr->icmp6_code & 0x7f;
if(secured) {
ND_PRINT((ndo, ", (SEC) [worktodo]"));
/* XXX
* the next header pointer needs to move forward to
* skip the secure part.
*/
return;
} else {
ND_PRINT((ndo, ", (CLR)"));
}
switch(basecode) {
case ND_RPL_DAG_IS:
ND_PRINT((ndo, "DODAG Information Solicitation"));
if(ndo->ndo_vflag) {
}
break;
case ND_RPL_DAG_IO:
ND_PRINT((ndo, "DODAG Information Object"));
if(ndo->ndo_vflag) {
rpl_dio_print(ndo, bp, length);
}
break;
case ND_RPL_DAO:
ND_PRINT((ndo, "Destination Advertisement Object"));
if(ndo->ndo_vflag) {
rpl_dao_print(ndo, bp, length);
}
break;
case ND_RPL_DAO_ACK:
ND_PRINT((ndo, "Destination Advertisement Object Ack"));
if(ndo->ndo_vflag) {
rpl_daoack_print(ndo, bp, length);
}
break;
default:
ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code));
break;
}
return;
#if 0
trunc:
ND_PRINT((ndo, "%s", rpl_tstr));
return;
#endif
}
| 169,832 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderProcessImpl::RenderProcessImpl()
: ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_(
FROM_HERE, base::TimeDelta::FromSeconds(5),
this, &RenderProcessImpl::ClearTransportDIBCache)),
transport_dib_next_sequence_number_(0) {
in_process_plugins_ = InProcessPlugins();
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i)
shared_mem_cache_[i] = NULL;
#if defined(OS_WIN)
if (GetModuleHandle(L"LPK.DLL") == NULL) {
typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs);
GdiInitializeLanguagePack gdi_init_lpk =
reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress(
GetModuleHandle(L"GDI32.DLL"),
"GdiInitializeLanguagePack"));
DCHECK(gdi_init_lpk);
if (gdi_init_lpk) {
gdi_init_lpk(0);
}
}
#endif
webkit_glue::SetJavaScriptFlags(
"--debugger-auto-break"
" --prof --prof-lazy");
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kJavaScriptFlags)) {
webkit_glue::SetJavaScriptFlags(
command_line.GetSwitchValueASCII(switches::kJavaScriptFlags));
}
}
Commit Message: Allow browser to handle all WebUI navigations.
BUG=113496
TEST="Google Dashboard" link in Sync settings loads in new process.
Review URL: http://codereview.chromium.org/9663045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@126949 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | RenderProcessImpl::RenderProcessImpl()
: ALLOW_THIS_IN_INITIALIZER_LIST(shared_mem_cache_cleaner_(
FROM_HERE, base::TimeDelta::FromSeconds(5),
this, &RenderProcessImpl::ClearTransportDIBCache)),
transport_dib_next_sequence_number_(0),
enabled_bindings_(0) {
in_process_plugins_ = InProcessPlugins();
for (size_t i = 0; i < arraysize(shared_mem_cache_); ++i)
shared_mem_cache_[i] = NULL;
#if defined(OS_WIN)
if (GetModuleHandle(L"LPK.DLL") == NULL) {
typedef BOOL (__stdcall *GdiInitializeLanguagePack)(int LoadedShapingDLLs);
GdiInitializeLanguagePack gdi_init_lpk =
reinterpret_cast<GdiInitializeLanguagePack>(GetProcAddress(
GetModuleHandle(L"GDI32.DLL"),
"GdiInitializeLanguagePack"));
DCHECK(gdi_init_lpk);
if (gdi_init_lpk) {
gdi_init_lpk(0);
}
}
#endif
webkit_glue::SetJavaScriptFlags(
"--debugger-auto-break"
" --prof --prof-lazy");
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kJavaScriptFlags)) {
webkit_glue::SetJavaScriptFlags(
command_line.GetSwitchValueASCII(switches::kJavaScriptFlags));
}
}
| 171,017 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType WritePICTImage(const ImageInfo *image_info,
Image *image)
{
#define MaxCount 128
#define PictCropRegionOp 0x01
#define PictEndOfPictureOp 0xff
#define PictJPEGOp 0x8200
#define PictInfoOp 0x0C00
#define PictInfoSize 512
#define PictPixmapOp 0x9A
#define PictPICTOp 0x98
#define PictVersion 0x11
const StringInfo
*profile;
double
x_resolution,
y_resolution;
MagickBooleanType
status;
MagickOffsetType
offset;
PICTPixmap
pixmap;
PICTRectangle
bounds,
crop_rectangle,
destination_rectangle,
frame_rectangle,
size_rectangle,
source_rectangle;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
size_t
bytes_per_line,
count,
row_bytes,
storage_class;
ssize_t
y;
unsigned char
*buffer,
*packed_scanline,
*scanline;
unsigned short
base_address,
transfer_mode;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 65535L) || (image->rows > 65535L))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Initialize image info.
*/
size_rectangle.top=0;
size_rectangle.left=0;
size_rectangle.bottom=(short) image->rows;
size_rectangle.right=(short) image->columns;
frame_rectangle=size_rectangle;
crop_rectangle=size_rectangle;
source_rectangle=size_rectangle;
destination_rectangle=size_rectangle;
base_address=0xff;
row_bytes=image->columns;
bounds.top=0;
bounds.left=0;
bounds.bottom=(short) image->rows;
bounds.right=(short) image->columns;
pixmap.version=0;
pixmap.pack_type=0;
pixmap.pack_size=0;
pixmap.pixel_type=0;
pixmap.bits_per_pixel=8;
pixmap.component_count=1;
pixmap.component_size=8;
pixmap.plane_bytes=0;
pixmap.table=0;
pixmap.reserved=0;
transfer_mode=0;
x_resolution=image->x_resolution != 0.0 ? image->x_resolution :
DefaultResolution;
y_resolution=image->y_resolution != 0.0 ? image->y_resolution :
DefaultResolution;
storage_class=image->storage_class;
if (image_info->compression == JPEGCompression)
storage_class=DirectClass;
if (storage_class == DirectClass)
{
pixmap.component_count=image->matte != MagickFalse ? 4 : 3;
pixmap.pixel_type=16;
pixmap.bits_per_pixel=32;
pixmap.pack_type=0x04;
transfer_mode=0x40;
row_bytes=4*image->columns;
}
/*
Allocate memory.
*/
bytes_per_line=image->columns;
if (storage_class == DirectClass)
bytes_per_line*=image->matte != MagickFalse ? 4 : 3;
buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer));
packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t)
(row_bytes+MaxCount),sizeof(*packed_scanline));
scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline));
if ((buffer == (unsigned char *) NULL) ||
(packed_scanline == (unsigned char *) NULL) ||
(scanline == (unsigned char *) NULL))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(scanline,0,row_bytes);
(void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount));
/*
Write header, header size, size bounding box, version, and reserved.
*/
(void) ResetMagickMemory(buffer,0,PictInfoSize);
(void) WriteBlob(image,PictInfoSize,buffer);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right);
(void) WriteBlobMSBShort(image,PictVersion);
(void) WriteBlobMSBShort(image,0x02ff); /* version #2 */
(void) WriteBlobMSBShort(image,PictInfoOp);
(void) WriteBlobMSBLong(image,0xFFFE0000UL);
/*
Write full size of the file, resolution, frame bounding box, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right);
(void) WriteBlobMSBLong(image,0x00000000L);
profile=GetImageProfile(image,"iptc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0x1f2);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobString(image,"8BIM");
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
}
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,4);
(void) WriteBlobMSBLong(image,0x00000002UL);
}
/*
Write crop region opcode and crop bounding box.
*/
(void) WriteBlobMSBShort(image,PictCropRegionOp);
(void) WriteBlobMSBShort(image,0xa);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right);
if (image_info->compression == JPEGCompression)
{
Image
*jpeg_image;
ImageInfo
*jpeg_info;
size_t
length;
unsigned char
*blob;
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
jpeg_info=CloneImageInfo(image_info);
(void) CopyMagickString(jpeg_info->magick,"JPEG",MaxTextExtent);
length=0;
blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length,
&image->exception);
jpeg_info=DestroyImageInfo(jpeg_info);
if (blob == (unsigned char *) NULL)
return(MagickFalse);
jpeg_image=DestroyImage(jpeg_image);
(void) WriteBlobMSBShort(image,PictJPEGOp);
(void) WriteBlobMSBLong(image,(unsigned int) length+154);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x40000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00400000UL);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00566A70UL);
(void) WriteBlobMSBLong(image,0x65670000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000001UL);
(void) WriteBlobMSBLong(image,0x00016170UL);
(void) WriteBlobMSBLong(image,0x706C0000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x87AC0001UL);
(void) WriteBlobMSBLong(image,0x0B466F74UL);
(void) WriteBlobMSBLong(image,0x6F202D20UL);
(void) WriteBlobMSBLong(image,0x4A504547UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x0018FFFFUL);
(void) WriteBlob(image,length,blob);
if ((length & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/*
Write picture opcode, row bytes, and picture bounding box, and version.
*/
if (storage_class == PseudoClass)
(void) WriteBlobMSBShort(image,PictPICTOp);
else
{
(void) WriteBlobMSBShort(image,PictPixmapOp);
(void) WriteBlobMSBLong(image,(size_t) base_address);
}
(void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000));
(void) WriteBlobMSBShort(image,(unsigned short) bounds.top);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.left);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.right);
/*
Write pack type, pack size, resolution, pixel type, and pixel size.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.version);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size);
(void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel);
/*
Write component count, size, plane bytes, table size, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.table);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved);
if (storage_class == PseudoClass)
{
/*
Write image colormap.
*/
(void) WriteBlobMSBLong(image,0x00000000L); /* color seed */
(void) WriteBlobMSBShort(image,0L); /* color flags */
(void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1));
for (i=0; i < (ssize_t) image->colors; i++)
{
(void) WriteBlobMSBShort(image,(unsigned short) i);
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].red));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].green));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].blue));
}
}
/*
Write source and destination rectangle.
*/
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) transfer_mode);
/*
Write picture data.
*/
count=0;
if (storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
scanline[x]=(unsigned char) GetPixelIndex(indexes+x);
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image_info->compression == JPEGCompression)
{
(void) ResetMagickMemory(scanline,0,row_bytes);
for (y=0; y < (ssize_t) image->rows; y++)
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
}
else
{
register unsigned char
*blue,
*green,
*opacity,
*red;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
opacity=scanline+3*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
if (image->matte != MagickFalse)
{
opacity=scanline;
red=scanline+image->columns;
green=scanline+2*image->columns;
blue=scanline+3*image->columns;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
*red++=ScaleQuantumToChar(GetPixelRed(p));
*green++=ScaleQuantumToChar(GetPixelGreen(p));
*blue++=ScaleQuantumToChar(GetPixelBlue(p));
if (image->matte != MagickFalse)
*opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p)));
p++;
}
count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if ((count & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
(void) WriteBlobMSBShort(image,PictEndOfPictureOp);
offset=TellBlob(image);
offset=SeekBlob(image,512,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) offset);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(MagickTrue);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/577
CWE ID: CWE-772 | static MagickBooleanType WritePICTImage(const ImageInfo *image_info,
Image *image)
{
#define MaxCount 128
#define PictCropRegionOp 0x01
#define PictEndOfPictureOp 0xff
#define PictJPEGOp 0x8200
#define PictInfoOp 0x0C00
#define PictInfoSize 512
#define PictPixmapOp 0x9A
#define PictPICTOp 0x98
#define PictVersion 0x11
const StringInfo
*profile;
double
x_resolution,
y_resolution;
MagickBooleanType
status;
MagickOffsetType
offset;
PICTPixmap
pixmap;
PICTRectangle
bounds,
crop_rectangle,
destination_rectangle,
frame_rectangle,
size_rectangle,
source_rectangle;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register ssize_t
i,
x;
size_t
bytes_per_line,
count,
row_bytes,
storage_class;
ssize_t
y;
unsigned char
*buffer,
*packed_scanline,
*scanline;
unsigned short
base_address,
transfer_mode;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if ((image->columns > 65535L) || (image->rows > 65535L))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace);
/*
Initialize image info.
*/
size_rectangle.top=0;
size_rectangle.left=0;
size_rectangle.bottom=(short) image->rows;
size_rectangle.right=(short) image->columns;
frame_rectangle=size_rectangle;
crop_rectangle=size_rectangle;
source_rectangle=size_rectangle;
destination_rectangle=size_rectangle;
base_address=0xff;
row_bytes=image->columns;
bounds.top=0;
bounds.left=0;
bounds.bottom=(short) image->rows;
bounds.right=(short) image->columns;
pixmap.version=0;
pixmap.pack_type=0;
pixmap.pack_size=0;
pixmap.pixel_type=0;
pixmap.bits_per_pixel=8;
pixmap.component_count=1;
pixmap.component_size=8;
pixmap.plane_bytes=0;
pixmap.table=0;
pixmap.reserved=0;
transfer_mode=0;
x_resolution=image->x_resolution != 0.0 ? image->x_resolution :
DefaultResolution;
y_resolution=image->y_resolution != 0.0 ? image->y_resolution :
DefaultResolution;
storage_class=image->storage_class;
if (image_info->compression == JPEGCompression)
storage_class=DirectClass;
if (storage_class == DirectClass)
{
pixmap.component_count=image->matte != MagickFalse ? 4 : 3;
pixmap.pixel_type=16;
pixmap.bits_per_pixel=32;
pixmap.pack_type=0x04;
transfer_mode=0x40;
row_bytes=4*image->columns;
}
/*
Allocate memory.
*/
bytes_per_line=image->columns;
if (storage_class == DirectClass)
bytes_per_line*=image->matte != MagickFalse ? 4 : 3;
buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer));
packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t)
(row_bytes+MaxCount),sizeof(*packed_scanline));
scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline));
if ((buffer == (unsigned char *) NULL) ||
(packed_scanline == (unsigned char *) NULL) ||
(scanline == (unsigned char *) NULL))
{
if (scanline != (unsigned char *) NULL)
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
if (packed_scanline != (unsigned char *) NULL)
packed_scanline=(unsigned char *) RelinquishMagickMemory(
packed_scanline);
if (buffer != (unsigned char *) NULL)
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) ResetMagickMemory(scanline,0,row_bytes);
(void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount));
/*
Write header, header size, size bounding box, version, and reserved.
*/
(void) ResetMagickMemory(buffer,0,PictInfoSize);
(void) WriteBlob(image,PictInfoSize,buffer);
(void) WriteBlobMSBShort(image,0);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right);
(void) WriteBlobMSBShort(image,PictVersion);
(void) WriteBlobMSBShort(image,0x02ff); /* version #2 */
(void) WriteBlobMSBShort(image,PictInfoOp);
(void) WriteBlobMSBLong(image,0xFFFE0000UL);
/*
Write full size of the file, resolution, frame bounding box, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right);
(void) WriteBlobMSBLong(image,0x00000000L);
profile=GetImageProfile(image,"iptc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0x1f2);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobString(image,"8BIM");
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
}
profile=GetImageProfile(image,"icc");
if (profile != (StringInfo *) NULL)
{
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,(unsigned short)
(GetStringInfoLength(profile)+4));
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlob(image,GetStringInfoLength(profile),
GetStringInfoDatum(profile));
(void) WriteBlobMSBShort(image,0xa1);
(void) WriteBlobMSBShort(image,0xe0);
(void) WriteBlobMSBShort(image,4);
(void) WriteBlobMSBLong(image,0x00000002UL);
}
/*
Write crop region opcode and crop bounding box.
*/
(void) WriteBlobMSBShort(image,PictCropRegionOp);
(void) WriteBlobMSBShort(image,0xa);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right);
if (image_info->compression == JPEGCompression)
{
Image
*jpeg_image;
ImageInfo
*jpeg_info;
size_t
length;
unsigned char
*blob;
jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception);
if (jpeg_image == (Image *) NULL)
{
(void) CloseBlob(image);
return(MagickFalse);
}
jpeg_info=CloneImageInfo(image_info);
(void) CopyMagickString(jpeg_info->magick,"JPEG",MaxTextExtent);
length=0;
blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length,
&image->exception);
jpeg_info=DestroyImageInfo(jpeg_info);
if (blob == (unsigned char *) NULL)
return(MagickFalse);
jpeg_image=DestroyImage(jpeg_image);
(void) WriteBlobMSBShort(image,PictJPEGOp);
(void) WriteBlobMSBLong(image,(unsigned int) length+154);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00010000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x40000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00400000UL);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00566A70UL);
(void) WriteBlobMSBLong(image,0x65670000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000001UL);
(void) WriteBlobMSBLong(image,0x00016170UL);
(void) WriteBlobMSBLong(image,0x706C0000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBShort(image,768);
(void) WriteBlobMSBShort(image,(unsigned short) image->columns);
(void) WriteBlobMSBShort(image,(unsigned short) image->rows);
(void) WriteBlobMSBShort(image,(unsigned short) x_resolution);
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) y_resolution);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x87AC0001UL);
(void) WriteBlobMSBLong(image,0x0B466F74UL);
(void) WriteBlobMSBLong(image,0x6F202D20UL);
(void) WriteBlobMSBLong(image,0x4A504547UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x00000000UL);
(void) WriteBlobMSBLong(image,0x0018FFFFUL);
(void) WriteBlob(image,length,blob);
if ((length & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
blob=(unsigned char *) RelinquishMagickMemory(blob);
}
/*
Write picture opcode, row bytes, and picture bounding box, and version.
*/
if (storage_class == PseudoClass)
(void) WriteBlobMSBShort(image,PictPICTOp);
else
{
(void) WriteBlobMSBShort(image,PictPixmapOp);
(void) WriteBlobMSBLong(image,(size_t) base_address);
}
(void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000));
(void) WriteBlobMSBShort(image,(unsigned short) bounds.top);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.left);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) bounds.right);
/*
Write pack type, pack size, resolution, pixel type, and pixel size.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.version);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size);
(void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5));
(void) WriteBlobMSBShort(image,0x0000);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel);
/*
Write component count, size, plane bytes, table size, and reserved.
*/
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count);
(void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.table);
(void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved);
if (storage_class == PseudoClass)
{
/*
Write image colormap.
*/
(void) WriteBlobMSBLong(image,0x00000000L); /* color seed */
(void) WriteBlobMSBShort(image,0L); /* color flags */
(void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1));
for (i=0; i < (ssize_t) image->colors; i++)
{
(void) WriteBlobMSBShort(image,(unsigned short) i);
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].red));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].green));
(void) WriteBlobMSBShort(image,ScaleQuantumToShort(
image->colormap[i].blue));
}
}
/*
Write source and destination rectangle.
*/
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom);
(void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right);
(void) WriteBlobMSBShort(image,(unsigned short) transfer_mode);
/*
Write picture data.
*/
count=0;
if (storage_class == PseudoClass)
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
scanline[x]=(unsigned char) GetPixelIndex(indexes+x);
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image_info->compression == JPEGCompression)
{
(void) ResetMagickMemory(scanline,0,row_bytes);
for (y=0; y < (ssize_t) image->rows; y++)
count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF),
packed_scanline);
}
else
{
register unsigned char
*blue,
*green,
*opacity,
*red;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
opacity=scanline+3*image->columns;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
red=scanline;
green=scanline+image->columns;
blue=scanline+2*image->columns;
if (image->matte != MagickFalse)
{
opacity=scanline;
red=scanline+image->columns;
green=scanline+2*image->columns;
blue=scanline+3*image->columns;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
*red++=ScaleQuantumToChar(GetPixelRed(p));
*green++=ScaleQuantumToChar(GetPixelGreen(p));
*blue++=ScaleQuantumToChar(GetPixelBlue(p));
if (image->matte != MagickFalse)
*opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p)));
p++;
}
count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if ((count & 0x01) != 0)
(void) WriteBlobByte(image,'\0');
(void) WriteBlobMSBShort(image,PictEndOfPictureOp);
offset=TellBlob(image);
offset=SeekBlob(image,512,SEEK_SET);
(void) WriteBlobMSBShort(image,(unsigned short) offset);
scanline=(unsigned char *) RelinquishMagickMemory(scanline);
packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline);
buffer=(unsigned char *) RelinquishMagickMemory(buffer);
(void) CloseBlob(image);
return(MagickTrue);
}
| 167,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: gst_asf_demux_process_ext_content_desc (GstASFDemux * demux, guint8 * data,
guint64 size)
{
/* Other known (and unused) 'text/unicode' metadata available :
*
* WM/Lyrics =
* WM/MediaPrimaryClassID = {D1607DBC-E323-4BE2-86A1-48A42A28441E}
* WMFSDKVersion = 9.00.00.2980
* WMFSDKNeeded = 0.0.0.0000
* WM/UniqueFileIdentifier = AMGa_id=R 15334;AMGp_id=P 5149;AMGt_id=T 2324984
* WM/Publisher = 4AD
* WM/Provider = AMG
* WM/ProviderRating = 8
* WM/ProviderStyle = Rock (similar to WM/Genre)
* WM/GenreID (similar to WM/Genre)
* WM/TrackNumber (same as WM/Track but as a string)
*
* Other known (and unused) 'non-text' metadata available :
*
* WM/EncodingTime
* WM/MCDI
* IsVBR
*
* We might want to read WM/TrackNumber and use atoi() if we don't have
* WM/Track
*/
GstTagList *taglist;
guint16 blockcount, i;
gboolean content3D = FALSE;
struct
{
const gchar *interleave_name;
GstASF3DMode interleaving_type;
} stereoscopic_layout_map[] = {
{
"SideBySideRF", GST_ASF_3D_SIDE_BY_SIDE_HALF_RL}, {
"SideBySideLF", GST_ASF_3D_SIDE_BY_SIDE_HALF_LR}, {
"OverUnderRT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL}, {
"OverUnderLT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR}, {
"DualStream", GST_ASF_3D_DUAL_STREAM}
};
GST_INFO_OBJECT (demux, "object is an extended content description");
taglist = gst_tag_list_new_empty ();
/* Content Descriptor Count */
if (size < 2)
goto not_enough_data;
blockcount = gst_asf_demux_get_uint16 (&data, &size);
for (i = 1; i <= blockcount; ++i) {
const gchar *gst_tag_name;
guint16 datatype;
guint16 value_len;
guint16 name_len;
GValue tag_value = { 0, };
gsize in, out;
gchar *name;
gchar *name_utf8 = NULL;
gchar *value;
/* Descriptor */
if (!gst_asf_demux_get_string (&name, &name_len, &data, &size))
goto not_enough_data;
if (size < 2) {
g_free (name);
goto not_enough_data;
}
/* Descriptor Value Data Type */
datatype = gst_asf_demux_get_uint16 (&data, &size);
/* Descriptor Value (not really a string, but same thing reading-wise) */
if (!gst_asf_demux_get_string (&value, &value_len, &data, &size)) {
g_free (name);
goto not_enough_data;
}
name_utf8 =
g_convert (name, name_len, "UTF-8", "UTF-16LE", &in, &out, NULL);
if (name_utf8 != NULL) {
GST_DEBUG ("Found tag/metadata %s", name_utf8);
gst_tag_name = gst_asf_demux_get_gst_tag_from_tag_name (name_utf8);
GST_DEBUG ("gst_tag_name %s", GST_STR_NULL (gst_tag_name));
switch (datatype) {
case ASF_DEMUX_DATA_TYPE_UTF16LE_STRING:{
gchar *value_utf8;
value_utf8 = g_convert (value, value_len, "UTF-8", "UTF-16LE",
&in, &out, NULL);
/* get rid of tags with empty value */
if (value_utf8 != NULL && *value_utf8 != '\0') {
GST_DEBUG ("string value %s", value_utf8);
value_utf8[out] = '\0';
if (gst_tag_name != NULL) {
if (strcmp (gst_tag_name, GST_TAG_DATE_TIME) == 0) {
guint year = atoi (value_utf8);
if (year > 0) {
g_value_init (&tag_value, GST_TYPE_DATE_TIME);
g_value_take_boxed (&tag_value, gst_date_time_new_y (year));
}
} else if (strcmp (gst_tag_name, GST_TAG_GENRE) == 0) {
guint id3v1_genre_id;
const gchar *genre_str;
if (sscanf (value_utf8, "(%u)", &id3v1_genre_id) == 1 &&
((genre_str = gst_tag_id3_genre_get (id3v1_genre_id)))) {
GST_DEBUG ("Genre: %s -> %s", value_utf8, genre_str);
g_free (value_utf8);
value_utf8 = g_strdup (genre_str);
}
} else {
GType tag_type;
/* convert tag from string to other type if required */
tag_type = gst_tag_get_type (gst_tag_name);
g_value_init (&tag_value, tag_type);
if (!gst_value_deserialize (&tag_value, value_utf8)) {
GValue from_val = { 0, };
g_value_init (&from_val, G_TYPE_STRING);
g_value_set_string (&from_val, value_utf8);
if (!g_value_transform (&from_val, &tag_value)) {
GST_WARNING_OBJECT (demux,
"Could not transform string tag to " "%s tag type %s",
gst_tag_name, g_type_name (tag_type));
g_value_unset (&tag_value);
}
g_value_unset (&from_val);
}
}
} else {
/* metadata ! */
GST_DEBUG ("Setting metadata");
g_value_init (&tag_value, G_TYPE_STRING);
g_value_set_string (&tag_value, value_utf8);
/* If we found a stereoscopic marker, look for StereoscopicLayout
* metadata */
if (content3D) {
guint i;
if (strncmp ("StereoscopicLayout", name_utf8,
strlen (name_utf8)) == 0) {
for (i = 0; i < G_N_ELEMENTS (stereoscopic_layout_map); i++) {
if (g_str_equal (stereoscopic_layout_map[i].interleave_name,
value_utf8)) {
demux->asf_3D_mode =
stereoscopic_layout_map[i].interleaving_type;
GST_INFO ("find interleave type %u", demux->asf_3D_mode);
}
}
}
GST_INFO_OBJECT (demux, "3d type is %u", demux->asf_3D_mode);
} else {
demux->asf_3D_mode = GST_ASF_3D_NONE;
GST_INFO_OBJECT (demux, "None 3d type");
}
}
} else if (value_utf8 == NULL) {
GST_WARNING ("Failed to convert string value to UTF8, skipping");
} else {
GST_DEBUG ("Skipping empty string value for %s",
GST_STR_NULL (gst_tag_name));
}
g_free (value_utf8);
break;
}
case ASF_DEMUX_DATA_TYPE_BYTE_ARRAY:{
if (gst_tag_name) {
if (!g_str_equal (gst_tag_name, GST_TAG_IMAGE)) {
GST_FIXME ("Unhandled byte array tag %s",
GST_STR_NULL (gst_tag_name));
break;
} else {
asf_demux_parse_picture_tag (taglist, (guint8 *) value,
value_len);
}
}
break;
}
case ASF_DEMUX_DATA_TYPE_DWORD:{
guint uint_val = GST_READ_UINT32_LE (value);
/* this is the track number */
g_value_init (&tag_value, G_TYPE_UINT);
/* WM/Track counts from 0 */
if (!strcmp (name_utf8, "WM/Track"))
++uint_val;
g_value_set_uint (&tag_value, uint_val);
break;
}
/* Detect 3D */
case ASF_DEMUX_DATA_TYPE_BOOL:{
gboolean bool_val = GST_READ_UINT32_LE (value);
if (strncmp ("Stereoscopic", name_utf8, strlen (name_utf8)) == 0) {
if (bool_val) {
GST_INFO_OBJECT (demux, "This is 3D contents");
content3D = TRUE;
} else {
GST_INFO_OBJECT (demux, "This is not 3D contenst");
content3D = FALSE;
}
}
break;
}
default:{
GST_DEBUG ("Skipping tag %s of type %d", gst_tag_name, datatype);
break;
}
}
if (G_IS_VALUE (&tag_value)) {
if (gst_tag_name) {
GstTagMergeMode merge_mode = GST_TAG_MERGE_APPEND;
/* WM/TrackNumber is more reliable than WM/Track, since the latter
* is supposed to have a 0 base but is often wrongly written to start
* from 1 as well, so prefer WM/TrackNumber when we have it: either
* replace the value added earlier from WM/Track or put it first in
* the list, so that it will get picked up by _get_uint() */
if (strcmp (name_utf8, "WM/TrackNumber") == 0)
merge_mode = GST_TAG_MERGE_REPLACE;
gst_tag_list_add_values (taglist, merge_mode, gst_tag_name,
&tag_value, NULL);
} else {
GST_DEBUG ("Setting global metadata %s", name_utf8);
gst_structure_set_value (demux->global_metadata, name_utf8,
&tag_value);
}
g_value_unset (&tag_value);
}
}
g_free (name);
g_free (value);
g_free (name_utf8);
}
gst_asf_demux_add_global_tags (demux, taglist);
return GST_FLOW_OK;
/* Errors */
not_enough_data:
{
GST_WARNING ("Unexpected end of data parsing ext content desc object");
gst_tag_list_unref (taglist);
return GST_FLOW_OK; /* not really fatal */
}
}
Commit Message: asfdemux: Check that we have enough data available before parsing bool/uint extended content descriptors
https://bugzilla.gnome.org/show_bug.cgi?id=777955
CWE ID: CWE-125 | gst_asf_demux_process_ext_content_desc (GstASFDemux * demux, guint8 * data,
guint64 size)
{
/* Other known (and unused) 'text/unicode' metadata available :
*
* WM/Lyrics =
* WM/MediaPrimaryClassID = {D1607DBC-E323-4BE2-86A1-48A42A28441E}
* WMFSDKVersion = 9.00.00.2980
* WMFSDKNeeded = 0.0.0.0000
* WM/UniqueFileIdentifier = AMGa_id=R 15334;AMGp_id=P 5149;AMGt_id=T 2324984
* WM/Publisher = 4AD
* WM/Provider = AMG
* WM/ProviderRating = 8
* WM/ProviderStyle = Rock (similar to WM/Genre)
* WM/GenreID (similar to WM/Genre)
* WM/TrackNumber (same as WM/Track but as a string)
*
* Other known (and unused) 'non-text' metadata available :
*
* WM/EncodingTime
* WM/MCDI
* IsVBR
*
* We might want to read WM/TrackNumber and use atoi() if we don't have
* WM/Track
*/
GstTagList *taglist;
guint16 blockcount, i;
gboolean content3D = FALSE;
struct
{
const gchar *interleave_name;
GstASF3DMode interleaving_type;
} stereoscopic_layout_map[] = {
{
"SideBySideRF", GST_ASF_3D_SIDE_BY_SIDE_HALF_RL}, {
"SideBySideLF", GST_ASF_3D_SIDE_BY_SIDE_HALF_LR}, {
"OverUnderRT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_RL}, {
"OverUnderLT", GST_ASF_3D_TOP_AND_BOTTOM_HALF_LR}, {
"DualStream", GST_ASF_3D_DUAL_STREAM}
};
GST_INFO_OBJECT (demux, "object is an extended content description");
taglist = gst_tag_list_new_empty ();
/* Content Descriptor Count */
if (size < 2)
goto not_enough_data;
blockcount = gst_asf_demux_get_uint16 (&data, &size);
for (i = 1; i <= blockcount; ++i) {
const gchar *gst_tag_name;
guint16 datatype;
guint16 value_len;
guint16 name_len;
GValue tag_value = { 0, };
gsize in, out;
gchar *name;
gchar *name_utf8 = NULL;
gchar *value;
/* Descriptor */
if (!gst_asf_demux_get_string (&name, &name_len, &data, &size))
goto not_enough_data;
if (size < 2) {
g_free (name);
goto not_enough_data;
}
/* Descriptor Value Data Type */
datatype = gst_asf_demux_get_uint16 (&data, &size);
/* Descriptor Value (not really a string, but same thing reading-wise) */
if (!gst_asf_demux_get_string (&value, &value_len, &data, &size)) {
g_free (name);
goto not_enough_data;
}
name_utf8 =
g_convert (name, name_len, "UTF-8", "UTF-16LE", &in, &out, NULL);
if (name_utf8 != NULL) {
GST_DEBUG ("Found tag/metadata %s", name_utf8);
gst_tag_name = gst_asf_demux_get_gst_tag_from_tag_name (name_utf8);
GST_DEBUG ("gst_tag_name %s", GST_STR_NULL (gst_tag_name));
switch (datatype) {
case ASF_DEMUX_DATA_TYPE_UTF16LE_STRING:{
gchar *value_utf8;
value_utf8 = g_convert (value, value_len, "UTF-8", "UTF-16LE",
&in, &out, NULL);
/* get rid of tags with empty value */
if (value_utf8 != NULL && *value_utf8 != '\0') {
GST_DEBUG ("string value %s", value_utf8);
value_utf8[out] = '\0';
if (gst_tag_name != NULL) {
if (strcmp (gst_tag_name, GST_TAG_DATE_TIME) == 0) {
guint year = atoi (value_utf8);
if (year > 0) {
g_value_init (&tag_value, GST_TYPE_DATE_TIME);
g_value_take_boxed (&tag_value, gst_date_time_new_y (year));
}
} else if (strcmp (gst_tag_name, GST_TAG_GENRE) == 0) {
guint id3v1_genre_id;
const gchar *genre_str;
if (sscanf (value_utf8, "(%u)", &id3v1_genre_id) == 1 &&
((genre_str = gst_tag_id3_genre_get (id3v1_genre_id)))) {
GST_DEBUG ("Genre: %s -> %s", value_utf8, genre_str);
g_free (value_utf8);
value_utf8 = g_strdup (genre_str);
}
} else {
GType tag_type;
/* convert tag from string to other type if required */
tag_type = gst_tag_get_type (gst_tag_name);
g_value_init (&tag_value, tag_type);
if (!gst_value_deserialize (&tag_value, value_utf8)) {
GValue from_val = { 0, };
g_value_init (&from_val, G_TYPE_STRING);
g_value_set_string (&from_val, value_utf8);
if (!g_value_transform (&from_val, &tag_value)) {
GST_WARNING_OBJECT (demux,
"Could not transform string tag to " "%s tag type %s",
gst_tag_name, g_type_name (tag_type));
g_value_unset (&tag_value);
}
g_value_unset (&from_val);
}
}
} else {
/* metadata ! */
GST_DEBUG ("Setting metadata");
g_value_init (&tag_value, G_TYPE_STRING);
g_value_set_string (&tag_value, value_utf8);
/* If we found a stereoscopic marker, look for StereoscopicLayout
* metadata */
if (content3D) {
guint i;
if (strncmp ("StereoscopicLayout", name_utf8,
strlen (name_utf8)) == 0) {
for (i = 0; i < G_N_ELEMENTS (stereoscopic_layout_map); i++) {
if (g_str_equal (stereoscopic_layout_map[i].interleave_name,
value_utf8)) {
demux->asf_3D_mode =
stereoscopic_layout_map[i].interleaving_type;
GST_INFO ("find interleave type %u", demux->asf_3D_mode);
}
}
}
GST_INFO_OBJECT (demux, "3d type is %u", demux->asf_3D_mode);
} else {
demux->asf_3D_mode = GST_ASF_3D_NONE;
GST_INFO_OBJECT (demux, "None 3d type");
}
}
} else if (value_utf8 == NULL) {
GST_WARNING ("Failed to convert string value to UTF8, skipping");
} else {
GST_DEBUG ("Skipping empty string value for %s",
GST_STR_NULL (gst_tag_name));
}
g_free (value_utf8);
break;
}
case ASF_DEMUX_DATA_TYPE_BYTE_ARRAY:{
if (gst_tag_name) {
if (!g_str_equal (gst_tag_name, GST_TAG_IMAGE)) {
GST_FIXME ("Unhandled byte array tag %s",
GST_STR_NULL (gst_tag_name));
break;
} else {
asf_demux_parse_picture_tag (taglist, (guint8 *) value,
value_len);
}
}
break;
}
case ASF_DEMUX_DATA_TYPE_DWORD:{
guint uint_val;
if (value_len < 4)
break;
uint_val = GST_READ_UINT32_LE (value);
/* this is the track number */
g_value_init (&tag_value, G_TYPE_UINT);
/* WM/Track counts from 0 */
if (!strcmp (name_utf8, "WM/Track"))
++uint_val;
g_value_set_uint (&tag_value, uint_val);
break;
}
/* Detect 3D */
case ASF_DEMUX_DATA_TYPE_BOOL:{
gboolean bool_val;
if (value_len < 4)
break;
bool_val = GST_READ_UINT32_LE (value);
if (strncmp ("Stereoscopic", name_utf8, strlen (name_utf8)) == 0) {
if (bool_val) {
GST_INFO_OBJECT (demux, "This is 3D contents");
content3D = TRUE;
} else {
GST_INFO_OBJECT (demux, "This is not 3D contenst");
content3D = FALSE;
}
}
break;
}
default:{
GST_DEBUG ("Skipping tag %s of type %d", gst_tag_name, datatype);
break;
}
}
if (G_IS_VALUE (&tag_value)) {
if (gst_tag_name) {
GstTagMergeMode merge_mode = GST_TAG_MERGE_APPEND;
/* WM/TrackNumber is more reliable than WM/Track, since the latter
* is supposed to have a 0 base but is often wrongly written to start
* from 1 as well, so prefer WM/TrackNumber when we have it: either
* replace the value added earlier from WM/Track or put it first in
* the list, so that it will get picked up by _get_uint() */
if (strcmp (name_utf8, "WM/TrackNumber") == 0)
merge_mode = GST_TAG_MERGE_REPLACE;
gst_tag_list_add_values (taglist, merge_mode, gst_tag_name,
&tag_value, NULL);
} else {
GST_DEBUG ("Setting global metadata %s", name_utf8);
gst_structure_set_value (demux->global_metadata, name_utf8,
&tag_value);
}
g_value_unset (&tag_value);
}
}
g_free (name);
g_free (value);
g_free (name_utf8);
}
gst_asf_demux_add_global_tags (demux, taglist);
return GST_FLOW_OK;
/* Errors */
not_enough_data:
{
GST_WARNING ("Unexpected end of data parsing ext content desc object");
gst_tag_list_unref (taglist);
return GST_FLOW_OK; /* not really fatal */
}
}
| 168,378 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
int pkt_len;
char line[COSINE_LINE_LENGTH];
/* Find the next packet */
offset = cosine_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
*data_offset = offset;
/* Parse the header */
pkt_len = parse_cosine_rec_hdr(&wth->phdr, line, err, err_info);
if (pkt_len == -1)
return FALSE;
/* Convert the ASCII hex dump to binary data */
return parse_cosine_hex_dump(wth->fh, &wth->phdr, pkt_len,
wth->frame_buffer, err, err_info);
}
Commit Message: Fix packet length handling.
Treat the packet length as unsigned - it shouldn't be negative in the
file. If it is, that'll probably cause the sscanf to fail, so we'll
report the file as bad.
Check it against WTAP_MAX_PACKET_SIZE to make sure we don't try to
allocate a huge amount of memory, just as we do in other file readers.
Use the now-validated packet size as the length in
ws_buffer_assure_space(), so we are certain to have enough space, and
don't allocate too much space.
Merge the header and packet data parsing routines while we're at it.
Bug: 12395
Change-Id: Ia70f33b71ff28451190fcf144c333fd1362646b2
Reviewed-on: https://code.wireshark.org/review/15172
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-119 | static gboolean cosine_read(wtap *wth, int *err, gchar **err_info,
gint64 *data_offset)
{
gint64 offset;
char line[COSINE_LINE_LENGTH];
/* Find the next packet */
offset = cosine_seek_next_packet(wth, err, err_info, line);
if (offset < 0)
return FALSE;
*data_offset = offset;
/* Parse the header and convert the ASCII hex dump to binary data */
return parse_cosine_packet(wth->fh, &wth->phdr, wth->frame_buffer,
line, err, err_info);
}
| 169,963 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void serial_update_parameters(SerialState *s)
{
int speed, parity, data_bits, stop_bits, frame_size;
QEMUSerialSetParams ssp;
if (s->divider == 0)
return;
/* Start bit. */
frame_size = 1;
/* Parity bit. */
frame_size++;
if (s->lcr & 0x10)
parity = 'E';
else
parity = 'O';
} else {
parity = 'N';
}
Commit Message:
CWE ID: CWE-369 | static void serial_update_parameters(SerialState *s)
{
int speed, parity, data_bits, stop_bits, frame_size;
QEMUSerialSetParams ssp;
if (s->divider == 0 || s->divider > s->baudbase) {
return;
}
/* Start bit. */
frame_size = 1;
/* Parity bit. */
frame_size++;
if (s->lcr & 0x10)
parity = 'E';
else
parity = 'O';
} else {
parity = 'N';
}
| 164,910 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PrintDialogGtk::UpdateSettings(const DictionaryValue& settings,
const printing::PageRanges& ranges) {
bool collate;
int color;
bool landscape;
bool print_to_pdf;
int copies;
int duplex_mode;
std::string device_name;
if (!settings.GetBoolean(printing::kSettingLandscape, &landscape) ||
!settings.GetBoolean(printing::kSettingCollate, &collate) ||
!settings.GetInteger(printing::kSettingColor, &color) ||
!settings.GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf) ||
!settings.GetInteger(printing::kSettingDuplexMode, &duplex_mode) ||
!settings.GetInteger(printing::kSettingCopies, &copies) ||
!settings.GetString(printing::kSettingDeviceName, &device_name)) {
return false;
}
if (!print_to_pdf) {
scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList);
printer_ = printer_list->GetPrinterWithName(device_name.c_str());
if (printer_) {
g_object_ref(printer_);
gtk_print_settings_set_printer(gtk_settings_,
gtk_printer_get_name(printer_));
}
gtk_print_settings_set_n_copies(gtk_settings_, copies);
gtk_print_settings_set_collate(gtk_settings_, collate);
const char* color_mode;
switch (color) {
case printing::COLOR:
color_mode = kColor;
break;
case printing::CMYK:
color_mode = kCMYK;
break;
default:
color_mode = kGrayscale;
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSColorModel, color_mode);
if (duplex_mode != printing::UNKNOWN_DUPLEX_MODE) {
const char* cups_duplex_mode = NULL;
switch (duplex_mode) {
case printing::LONG_EDGE:
cups_duplex_mode = kDuplexNoTumble;
break;
case printing::SHORT_EDGE:
cups_duplex_mode = kDuplexTumble;
break;
case printing::SIMPLEX:
cups_duplex_mode = kDuplexNone;
break;
default: // UNKNOWN_DUPLEX_MODE
NOTREACHED();
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode);
}
}
gtk_print_settings_set_orientation(
gtk_settings_,
landscape ? GTK_PAGE_ORIENTATION_LANDSCAPE :
GTK_PAGE_ORIENTATION_PORTRAIT);
InitPrintSettings(ranges);
return true;
}
Commit Message: Fix print preview workflow to reflect settings of selected printer.
BUG=95110
TEST=none
Review URL: http://codereview.chromium.org/7831041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@102242 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool PrintDialogGtk::UpdateSettings(const DictionaryValue& settings,
const printing::PageRanges& ranges) {
bool collate;
int color;
bool landscape;
bool print_to_pdf;
int copies;
int duplex_mode;
std::string device_name;
if (!settings.GetBoolean(printing::kSettingLandscape, &landscape) ||
!settings.GetBoolean(printing::kSettingCollate, &collate) ||
!settings.GetInteger(printing::kSettingColor, &color) ||
!settings.GetBoolean(printing::kSettingPrintToPDF, &print_to_pdf) ||
!settings.GetInteger(printing::kSettingDuplexMode, &duplex_mode) ||
!settings.GetInteger(printing::kSettingCopies, &copies) ||
!settings.GetString(printing::kSettingDeviceName, &device_name)) {
return false;
}
if (!gtk_settings_)
gtk_settings_ = gtk_print_settings_new();
if (!print_to_pdf) {
scoped_ptr<GtkPrinterList> printer_list(new GtkPrinterList);
printer_ = printer_list->GetPrinterWithName(device_name.c_str());
if (printer_) {
g_object_ref(printer_);
gtk_print_settings_set_printer(gtk_settings_,
gtk_printer_get_name(printer_));
if (!page_setup_) {
page_setup_ = gtk_printer_get_default_page_size(printer_);
}
}
if (!page_setup_)
page_setup_ = gtk_page_setup_new();
gtk_print_settings_set_n_copies(gtk_settings_, copies);
gtk_print_settings_set_collate(gtk_settings_, collate);
const char* color_mode;
switch (color) {
case printing::COLOR:
color_mode = kColor;
break;
case printing::CMYK:
color_mode = kCMYK;
break;
default:
color_mode = kGrayscale;
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSColorModel, color_mode);
if (duplex_mode != printing::UNKNOWN_DUPLEX_MODE) {
const char* cups_duplex_mode = NULL;
switch (duplex_mode) {
case printing::LONG_EDGE:
cups_duplex_mode = kDuplexNoTumble;
break;
case printing::SHORT_EDGE:
cups_duplex_mode = kDuplexTumble;
break;
case printing::SIMPLEX:
cups_duplex_mode = kDuplexNone;
break;
default: // UNKNOWN_DUPLEX_MODE
NOTREACHED();
break;
}
gtk_print_settings_set(gtk_settings_, kCUPSDuplex, cups_duplex_mode);
}
}
gtk_print_settings_set_orientation(
gtk_settings_,
landscape ? GTK_PAGE_ORIENTATION_LANDSCAPE :
GTK_PAGE_ORIENTATION_PORTRAIT);
InitPrintSettings(ranges);
return true;
}
| 170,254 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int perf_trace_event_perm(struct ftrace_event_call *tp_event,
struct perf_event *p_event)
{
/* The ftrace function trace is allowed only for root. */
if (ftrace_event_is_function(tp_event) &&
perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
return -EPERM;
/* No tracing, just counting, so no obvious leak */
if (!(p_event->attr.sample_type & PERF_SAMPLE_RAW))
return 0;
/* Some events are ok to be traced by non-root users... */
if (p_event->attach_state == PERF_ATTACH_TASK) {
if (tp_event->flags & TRACE_EVENT_FL_CAP_ANY)
return 0;
}
/*
* ...otherwise raw tracepoint data can be a severe data leak,
* only allow root to have these.
*/
if (perf_paranoid_tracepoint_raw() && !capable(CAP_SYS_ADMIN))
return -EPERM;
return 0;
}
Commit Message: perf/ftrace: Fix paranoid level for enabling function tracer
The current default perf paranoid level is "1" which has
"perf_paranoid_kernel()" return false, and giving any operations that
use it, access to normal users. Unfortunately, this includes function
tracing and normal users should not be allowed to enable function
tracing by default.
The proper level is defined at "-1" (full perf access), which
"perf_paranoid_tracepoint_raw()" will only give access to. Use that
check instead for enabling function tracing.
Reported-by: Dave Jones <[email protected]>
Reported-by: Vince Weaver <[email protected]>
Tested-by: Vince Weaver <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Jiri Olsa <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: [email protected] # 3.4+
CVE: CVE-2013-2930
Fixes: ced39002f5ea ("ftrace, perf: Add support to use function tracepoint in perf")
Signed-off-by: Steven Rostedt <[email protected]>
CWE ID: CWE-264 | static int perf_trace_event_perm(struct ftrace_event_call *tp_event,
struct perf_event *p_event)
{
/* The ftrace function trace is allowed only for root. */
if (ftrace_event_is_function(tp_event) &&
perf_paranoid_tracepoint_raw() && !capable(CAP_SYS_ADMIN))
return -EPERM;
/* No tracing, just counting, so no obvious leak */
if (!(p_event->attr.sample_type & PERF_SAMPLE_RAW))
return 0;
/* Some events are ok to be traced by non-root users... */
if (p_event->attach_state == PERF_ATTACH_TASK) {
if (tp_event->flags & TRACE_EVENT_FL_CAP_ANY)
return 0;
}
/*
* ...otherwise raw tracepoint data can be a severe data leak,
* only allow root to have these.
*/
if (perf_paranoid_tracepoint_raw() && !capable(CAP_SYS_ADMIN))
return -EPERM;
return 0;
}
| 166,048 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool TaskService::UnbindInstance() {
{
base::AutoLock lock(lock_);
if (bound_instance_id_ == kInvalidInstanceId)
return false;
bound_instance_id_ = kInvalidInstanceId;
DCHECK(default_task_runner_);
default_task_runner_ = nullptr;
}
base::subtle::AutoWriteLock task_lock(task_lock_);
return true;
}
Commit Message: Change ReadWriteLock to Lock+ConditionVariable in TaskService
There are non-trivial performance implications of using shared
SRWLocking on Windows as more state has to be checked.
Since there are only two uses of the ReadWriteLock in Chromium after
over 1 year, the decision is to remove it.
BUG=758721
Change-Id: I84d1987d7b624a89e896eb37184ee50845c39d80
Reviewed-on: https://chromium-review.googlesource.com/634423
Commit-Queue: Robert Liao <[email protected]>
Reviewed-by: Takashi Toyoshima <[email protected]>
Reviewed-by: Francois Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#497632}
CWE ID: CWE-20 | bool TaskService::UnbindInstance() {
{
base::AutoLock lock(lock_);
if (bound_instance_id_ == kInvalidInstanceId)
return false;
bound_instance_id_ = kInvalidInstanceId;
DCHECK(default_task_runner_);
default_task_runner_ = nullptr;
}
// But invoked tasks might be still running here. To ensure no task runs on
// quitting this method, wait for all tasks to complete.
base::AutoLock tasks_in_flight_auto_lock(tasks_in_flight_lock_);
while (tasks_in_flight_ > 0)
no_tasks_in_flight_cv_.Wait();
return true;
}
| 172,214 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void VRDisplay::OnBlur() {
display_blurred_ = true;
vr_v_sync_provider_.reset();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayblur, true, false, this, ""));
}
Commit Message: WebVR: fix initial vsync
Applications sometimes use window.rAF while not presenting, then switch to
vrDisplay.rAF after presentation starts. Depending on the animation loop's
timing, this can cause a race condition where presentation has been started
but there's no vrDisplay.rAF pending yet. Ensure there's at least vsync
being processed after presentation starts so that a queued window.rAF
can run and schedule a vrDisplay.rAF.
BUG=711789
Review-Url: https://codereview.chromium.org/2848483003
Cr-Commit-Position: refs/heads/master@{#468167}
CWE ID: | void VRDisplay::OnBlur() {
DVLOG(1) << __FUNCTION__;
display_blurred_ = true;
vr_v_sync_provider_.reset();
navigator_vr_->EnqueueVREvent(VRDisplayEvent::Create(
EventTypeNames::vrdisplayblur, true, false, this, ""));
}
| 171,994 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void OnSuggestionModelAdded(UiScene* scene,
UiBrowserInterface* browser,
Model* model,
SuggestionBinding* element_binding) {
auto icon = base::MakeUnique<VectorIcon>(100);
icon->SetDrawPhase(kPhaseForeground);
icon->SetType(kTypeOmniboxSuggestionIcon);
icon->set_hit_testable(false);
icon->SetSize(kSuggestionIconSizeDMM, kSuggestionIconSizeDMM);
BindColor(model, icon.get(), &ColorScheme::omnibox_icon,
&VectorIcon::SetColor);
VectorIcon* p_icon = icon.get();
auto icon_box = base::MakeUnique<UiElement>();
icon_box->SetDrawPhase(kPhaseNone);
icon_box->SetType(kTypeOmniboxSuggestionIconField);
icon_box->SetSize(kSuggestionIconFieldWidthDMM, kSuggestionHeightDMM);
icon_box->AddChild(std::move(icon));
auto content_text = base::MakeUnique<Text>(kSuggestionContentTextHeightDMM);
content_text->SetDrawPhase(kPhaseForeground);
content_text->SetType(kTypeOmniboxSuggestionContentText);
content_text->set_hit_testable(false);
content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
content_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
content_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, content_text.get(), &ColorScheme::omnibox_suggestion_content,
&Text::SetColor);
Text* p_content_text = content_text.get();
auto description_text =
base::MakeUnique<Text>(kSuggestionDescriptionTextHeightDMM);
description_text->SetDrawPhase(kPhaseForeground);
description_text->SetType(kTypeOmniboxSuggestionDescriptionText);
description_text->set_hit_testable(false);
content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
description_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
description_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, description_text.get(),
&ColorScheme::omnibox_suggestion_description, &Text::SetColor);
Text* p_description_text = description_text.get();
auto text_layout = base::MakeUnique<LinearLayout>(LinearLayout::kDown);
text_layout->SetType(kTypeOmniboxSuggestionTextLayout);
text_layout->set_hit_testable(false);
text_layout->set_margin(kSuggestionLineGapDMM);
text_layout->AddChild(std::move(content_text));
text_layout->AddChild(std::move(description_text));
auto right_margin = base::MakeUnique<UiElement>();
right_margin->SetDrawPhase(kPhaseNone);
right_margin->SetSize(kSuggestionRightMarginDMM, kSuggestionHeightDMM);
auto suggestion_layout = base::MakeUnique<LinearLayout>(LinearLayout::kRight);
suggestion_layout->SetType(kTypeOmniboxSuggestionLayout);
suggestion_layout->set_hit_testable(false);
suggestion_layout->AddChild(std::move(icon_box));
suggestion_layout->AddChild(std::move(text_layout));
suggestion_layout->AddChild(std::move(right_margin));
auto background = Create<Button>(
kNone, kPhaseForeground,
base::BindRepeating(
[](UiBrowserInterface* b, Model* m, SuggestionBinding* e) {
b->Navigate(e->model()->destination);
m->omnibox_input_active = false;
},
base::Unretained(browser), base::Unretained(model),
base::Unretained(element_binding)));
background->SetType(kTypeOmniboxSuggestionBackground);
background->set_hit_testable(true);
background->set_bubble_events(true);
background->set_bounds_contain_children(true);
background->set_hover_offset(0.0);
BindButtonColors(model, background.get(),
&ColorScheme::suggestion_button_colors,
&Button::SetButtonColors);
background->AddChild(std::move(suggestion_layout));
element_binding->bindings().push_back(
VR_BIND_FUNC(base::string16, SuggestionBinding, element_binding,
model()->content, Text, p_content_text, SetText));
element_binding->bindings().push_back(
base::MakeUnique<Binding<base::string16>>(
base::BindRepeating(
[](SuggestionBinding* m) { return m->model()->description; },
base::Unretained(element_binding)),
base::BindRepeating(
[](Text* v, const base::string16& text) {
v->SetVisibleImmediately(!text.empty());
v->set_requires_layout(!text.empty());
if (!text.empty()) {
v->SetText(text);
}
},
base::Unretained(p_description_text))));
element_binding->bindings().push_back(
VR_BIND(AutocompleteMatch::Type, SuggestionBinding, element_binding,
model()->type, VectorIcon, p_icon,
SetIcon(AutocompleteMatch::TypeToVectorIcon(value))));
element_binding->set_view(background.get());
scene->AddUiElement(kOmniboxSuggestions, std::move(background));
}
Commit Message: Fix wrapping behavior of description text in omnibox suggestion
This regression is introduced by
https://chromium-review.googlesource.com/c/chromium/src/+/827033
The description text should not wrap.
Bug: NONE
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: Iaac5e6176e1730853406602835d61fe1e80ec0d0
Reviewed-on: https://chromium-review.googlesource.com/839960
Reviewed-by: Christopher Grant <[email protected]>
Commit-Queue: Biao She <[email protected]>
Cr-Commit-Position: refs/heads/master@{#525806}
CWE ID: CWE-200 | void OnSuggestionModelAdded(UiScene* scene,
UiBrowserInterface* browser,
Model* model,
SuggestionBinding* element_binding) {
auto icon = base::MakeUnique<VectorIcon>(100);
icon->SetDrawPhase(kPhaseForeground);
icon->SetType(kTypeOmniboxSuggestionIcon);
icon->set_hit_testable(false);
icon->SetSize(kSuggestionIconSizeDMM, kSuggestionIconSizeDMM);
BindColor(model, icon.get(), &ColorScheme::omnibox_icon,
&VectorIcon::SetColor);
VectorIcon* p_icon = icon.get();
auto icon_box = base::MakeUnique<UiElement>();
icon_box->SetDrawPhase(kPhaseNone);
icon_box->SetType(kTypeOmniboxSuggestionIconField);
icon_box->SetSize(kSuggestionIconFieldWidthDMM, kSuggestionHeightDMM);
icon_box->AddChild(std::move(icon));
auto content_text = base::MakeUnique<Text>(kSuggestionContentTextHeightDMM);
content_text->SetDrawPhase(kPhaseForeground);
content_text->SetType(kTypeOmniboxSuggestionContentText);
content_text->set_hit_testable(false);
content_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
content_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
content_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, content_text.get(), &ColorScheme::omnibox_suggestion_content,
&Text::SetColor);
Text* p_content_text = content_text.get();
auto description_text =
base::MakeUnique<Text>(kSuggestionDescriptionTextHeightDMM);
description_text->SetDrawPhase(kPhaseForeground);
description_text->SetType(kTypeOmniboxSuggestionDescriptionText);
description_text->set_hit_testable(false);
description_text->SetTextLayoutMode(TextLayoutMode::kSingleLineFixedWidth);
description_text->SetSize(kSuggestionTextFieldWidthDMM, 0);
description_text->SetTextAlignment(UiTexture::kTextAlignmentLeft);
BindColor(model, description_text.get(),
&ColorScheme::omnibox_suggestion_description, &Text::SetColor);
Text* p_description_text = description_text.get();
auto text_layout = base::MakeUnique<LinearLayout>(LinearLayout::kDown);
text_layout->SetType(kTypeOmniboxSuggestionTextLayout);
text_layout->set_hit_testable(false);
text_layout->set_margin(kSuggestionLineGapDMM);
text_layout->AddChild(std::move(content_text));
text_layout->AddChild(std::move(description_text));
auto right_margin = base::MakeUnique<UiElement>();
right_margin->SetDrawPhase(kPhaseNone);
right_margin->SetSize(kSuggestionRightMarginDMM, kSuggestionHeightDMM);
auto suggestion_layout = base::MakeUnique<LinearLayout>(LinearLayout::kRight);
suggestion_layout->SetType(kTypeOmniboxSuggestionLayout);
suggestion_layout->set_hit_testable(false);
suggestion_layout->AddChild(std::move(icon_box));
suggestion_layout->AddChild(std::move(text_layout));
suggestion_layout->AddChild(std::move(right_margin));
auto background = Create<Button>(
kNone, kPhaseForeground,
base::BindRepeating(
[](UiBrowserInterface* b, Model* m, SuggestionBinding* e) {
b->Navigate(e->model()->destination);
m->omnibox_input_active = false;
},
base::Unretained(browser), base::Unretained(model),
base::Unretained(element_binding)));
background->SetType(kTypeOmniboxSuggestionBackground);
background->set_hit_testable(true);
background->set_bubble_events(true);
background->set_bounds_contain_children(true);
background->set_hover_offset(0.0);
BindButtonColors(model, background.get(),
&ColorScheme::suggestion_button_colors,
&Button::SetButtonColors);
background->AddChild(std::move(suggestion_layout));
element_binding->bindings().push_back(
VR_BIND_FUNC(base::string16, SuggestionBinding, element_binding,
model()->content, Text, p_content_text, SetText));
element_binding->bindings().push_back(
base::MakeUnique<Binding<base::string16>>(
base::BindRepeating(
[](SuggestionBinding* m) { return m->model()->description; },
base::Unretained(element_binding)),
base::BindRepeating(
[](Text* v, const base::string16& text) {
v->SetVisibleImmediately(!text.empty());
v->set_requires_layout(!text.empty());
if (!text.empty()) {
v->SetText(text);
}
},
base::Unretained(p_description_text))));
element_binding->bindings().push_back(
VR_BIND(AutocompleteMatch::Type, SuggestionBinding, element_binding,
model()->type, VectorIcon, p_icon,
SetIcon(AutocompleteMatch::TypeToVectorIcon(value))));
element_binding->set_view(background.get());
scene->AddUiElement(kOmniboxSuggestions, std::move(background));
}
| 173,221 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 )
{
len ++;
}
chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 ));
len = 0;
while ( in[ len ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
return chr;
}
Commit Message: New Pre Source
CWE ID: CWE-119 | SQLWCHAR* _single_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 )
{
len ++;
}
chr = malloc( sizeof( SQLWCHAR ) * ( len + 1 ));
len = 0;
while ( in[ len ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
return chr;
}
| 169,316 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter;
#if defined(OS_MACOSX) && !defined(OS_IOS)
ip_attributes_getter = base::MakeUnique<internal::IPAttributesGetterMac>();
#endif
bool result = internal::IfaddrsToNetworkInterfaceList(
policy, interfaces, ip_attributes_getter.get(), networks);
freeifaddrs(interfaces);
return result;
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | bool GetNetworkList(NetworkInterfaceList* networks, int policy) {
if (networks == NULL)
return false;
base::ThreadRestrictions::AssertIOAllowed();
ifaddrs* interfaces;
if (getifaddrs(&interfaces) < 0) {
PLOG(ERROR) << "getifaddrs";
return false;
}
std::unique_ptr<internal::IPAttributesGetter> ip_attributes_getter;
#if defined(OS_MACOSX) && !defined(OS_IOS)
ip_attributes_getter = std::make_unique<internal::IPAttributesGetterMac>();
#endif
bool result = internal::IfaddrsToNetworkInterfaceList(
policy, interfaces, ip_attributes_getter.get(), networks);
freeifaddrs(interfaces);
return result;
}
| 173,265 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WallpaperManager::SetDefaultWallpaperPath(
const base::FilePath& default_small_wallpaper_file,
std::unique_ptr<gfx::ImageSkia> small_wallpaper_image,
const base::FilePath& default_large_wallpaper_file,
std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) {
default_small_wallpaper_file_ = default_small_wallpaper_file;
default_large_wallpaper_file_ = default_large_wallpaper_file;
ash::WallpaperController* controller =
ash::Shell::Get()->wallpaper_controller();
const bool need_update_screen =
default_wallpaper_image_.get() &&
controller->WallpaperIsAlreadyLoaded(default_wallpaper_image_->image(),
false /* compare_layouts */,
wallpaper::WALLPAPER_LAYOUT_CENTER);
default_wallpaper_image_.reset();
if (GetAppropriateResolution() == WALLPAPER_RESOLUTION_SMALL) {
if (small_wallpaper_image) {
default_wallpaper_image_.reset(
new user_manager::UserImage(*small_wallpaper_image));
default_wallpaper_image_->set_file_path(default_small_wallpaper_file);
}
} else {
if (large_wallpaper_image) {
default_wallpaper_image_.reset(
new user_manager::UserImage(*large_wallpaper_image));
default_wallpaper_image_->set_file_path(default_large_wallpaper_file);
}
}
if (need_update_screen)
DoSetDefaultWallpaper(EmptyAccountId(), MovableOnDestroyCallbackHolder());
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
CWE ID: CWE-200 | void WallpaperManager::SetDefaultWallpaperPath(
const base::FilePath& default_small_wallpaper_file,
std::unique_ptr<gfx::ImageSkia> small_wallpaper_image,
const base::FilePath& default_large_wallpaper_file,
std::unique_ptr<gfx::ImageSkia> large_wallpaper_image) {
default_small_wallpaper_file_ = default_small_wallpaper_file;
default_large_wallpaper_file_ = default_large_wallpaper_file;
ash::WallpaperController* controller =
ash::Shell::Get()->wallpaper_controller();
const bool need_update_screen =
default_wallpaper_image_.get() &&
controller->WallpaperIsAlreadyLoaded(default_wallpaper_image_->image(),
false /* compare_layouts */,
wallpaper::WALLPAPER_LAYOUT_CENTER);
default_wallpaper_image_.reset();
if (GetAppropriateResolution() == WALLPAPER_RESOLUTION_SMALL) {
if (small_wallpaper_image) {
default_wallpaper_image_.reset(
new user_manager::UserImage(*small_wallpaper_image));
default_wallpaper_image_->set_file_path(default_small_wallpaper_file);
}
} else {
if (large_wallpaper_image) {
default_wallpaper_image_.reset(
new user_manager::UserImage(*large_wallpaper_image));
default_wallpaper_image_->set_file_path(default_large_wallpaper_file);
}
}
DoSetDefaultWallpaper(EmptyAccountId(), need_update_screen,
MovableOnDestroyCallbackHolder());
}
| 171,970 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
int ulen;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
ulen = xfrm_replay_state_esn_len(up);
if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen)
return -EINVAL;
if (up->replay_window > up->bmp_len * sizeof(__u32) * 8)
return -EINVAL;
return 0;
}
Commit Message: xfrm_user: validate XFRM_MSG_NEWAE incoming ESN size harder
Kees Cook has pointed out that xfrm_replay_state_esn_len() is subject to
wrapping issues. To ensure we are correctly ensuring that the two ESN
structures are the same size compare both the overall size as reported
by xfrm_replay_state_esn_len() and the internal length are the same.
CVE-2017-7184
Signed-off-by: Andy Whitcroft <[email protected]>
Acked-by: Steffen Klassert <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: | static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn,
struct nlattr *rp)
{
struct xfrm_replay_state_esn *up;
int ulen;
if (!replay_esn || !rp)
return 0;
up = nla_data(rp);
ulen = xfrm_replay_state_esn_len(up);
/* Check the overall length and the internal bitmap length to avoid
* potential overflow. */
if (nla_len(rp) < ulen ||
xfrm_replay_state_esn_len(replay_esn) != ulen ||
replay_esn->bmp_len != up->bmp_len)
return -EINVAL;
if (up->replay_window > up->bmp_len * sizeof(__u32) * 8)
return -EINVAL;
return 0;
}
| 168,292 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CreatePersistentHistogramAllocator() {
allocator_memory_.reset(new char[kAllocatorMemorySize]);
GlobalHistogramAllocator::ReleaseForTesting();
memset(allocator_memory_.get(), 0, kAllocatorMemorySize);
GlobalHistogramAllocator::GetCreateHistogramResultHistogram();
GlobalHistogramAllocator::CreateWithPersistentMemory(
allocator_memory_.get(), kAllocatorMemorySize, 0, 0,
"PersistentHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
Commit Message: Remove UMA.CreatePersistentHistogram.Result
This histogram isn't showing anything meaningful and the problems it
could show are better observed by looking at the allocators directly.
Bug: 831013
Change-Id: Ibe968597758230192e53a7675e7390e968c9e5b9
Reviewed-on: https://chromium-review.googlesource.com/1008047
Commit-Queue: Brian White <[email protected]>
Reviewed-by: Alexei Svitkine <[email protected]>
Cr-Commit-Position: refs/heads/master@{#549986}
CWE ID: CWE-264 | void CreatePersistentHistogramAllocator() {
allocator_memory_.reset(new char[kAllocatorMemorySize]);
GlobalHistogramAllocator::ReleaseForTesting();
memset(allocator_memory_.get(), 0, kAllocatorMemorySize);
GlobalHistogramAllocator::CreateWithPersistentMemory(
allocator_memory_.get(), kAllocatorMemorySize, 0, 0,
"PersistentHistogramAllocatorTest");
allocator_ = GlobalHistogramAllocator::Get()->memory_allocator();
}
| 172,137 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb_cache_entry *ce;
struct mb_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
again:
ce = mb_cache_entry_find_first(ext4_mb_cache, inode->i_sb->s_bdev,
hash);
while (ce) {
struct buffer_head *bh;
if (IS_ERR(ce)) {
if (PTR_ERR(ce) == -EAGAIN)
goto again;
break;
}
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash);
}
return NULL;
}
Commit Message: ext4: convert to mbcache2
The conversion is generally straightforward. The only tricky part is
that xattr block corresponding to found mbcache entry can get freed
before we get buffer lock for that block. So we have to check whether
the entry is still valid after getting buffer lock.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-19 | ext4_xattr_cache_find(struct inode *inode, struct ext4_xattr_header *header,
struct mb2_cache_entry **pce)
{
__u32 hash = le32_to_cpu(header->h_hash);
struct mb2_cache_entry *ce;
struct mb2_cache *ext4_mb_cache = EXT4_GET_MB_CACHE(inode);
if (!header->h_hash)
return NULL; /* never share */
ea_idebug(inode, "looking for cached blocks [%x]", (int)hash);
ce = mb2_cache_entry_find_first(ext4_mb_cache, hash);
while (ce) {
struct buffer_head *bh;
bh = sb_bread(inode->i_sb, ce->e_block);
if (!bh) {
EXT4_ERROR_INODE(inode, "block %lu read error",
(unsigned long) ce->e_block);
} else if (le32_to_cpu(BHDR(bh)->h_refcount) >=
EXT4_XATTR_REFCOUNT_MAX) {
ea_idebug(inode, "block %lu refcount %d>=%d",
(unsigned long) ce->e_block,
le32_to_cpu(BHDR(bh)->h_refcount),
EXT4_XATTR_REFCOUNT_MAX);
} else if (ext4_xattr_cmp(header, BHDR(bh)) == 0) {
*pce = ce;
return bh;
}
brelse(bh);
ce = mb2_cache_entry_find_next(ext4_mb_cache, ce);
}
return NULL;
}
| 169,991 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GDataFileSystem::OnGetDocumentEntry(const FilePath& cache_file_path,
const GetFileFromCacheParams& params,
GDataErrorCode status,
scoped_ptr<base::Value> data) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GDataFileError error = util::GDataToGDataFileError(status);
scoped_ptr<GDataEntry> fresh_entry;
if (error == GDATA_FILE_OK) {
scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data));
if (doc_entry.get()) {
fresh_entry.reset(
GDataEntry::FromDocumentEntry(NULL, doc_entry.get(),
directory_service_.get()));
}
if (!fresh_entry.get() || !fresh_entry->AsGDataFile()) {
LOG(ERROR) << "Got invalid entry from server for " << params.resource_id;
error = GDATA_FILE_ERROR_FAILED;
}
}
if (error != GDATA_FILE_OK) {
if (!params.get_file_callback.is_null()) {
params.get_file_callback.Run(error,
cache_file_path,
params.mime_type,
REGULAR_FILE);
}
return;
}
GURL content_url = fresh_entry->content_url();
int64 file_size = fresh_entry->file_info().size;
DCHECK_EQ(params.resource_id, fresh_entry->resource_id());
scoped_ptr<GDataFile> fresh_entry_as_file(
fresh_entry.release()->AsGDataFile());
directory_service_->RefreshFile(fresh_entry_as_file.Pass());
bool* has_enough_space = new bool(false);
util::PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
blocking_task_runner_,
base::Bind(&GDataCache::FreeDiskSpaceIfNeededFor,
base::Unretained(cache_),
file_size,
has_enough_space),
base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace,
ui_weak_ptr_,
params,
content_url,
cache_file_path,
base::Owned(has_enough_space)));
}
Commit Message: Remove parent* arg from GDataEntry ctor.
* Remove static FromDocumentEntry from GDataEntry, GDataFile, GDataDirectory. Replace with InitFromDocumentEntry.
* Move common code from GDataFile::InitFromDocumentEntry and GDataDirectory::InitFromDocumentEntry to GDataEntry::InitFromDocumentEntry.
* Add GDataDirectoryService::FromDocumentEntry and use this everywhere.
* Make ctors of GDataFile, GDataDirectory private, so these must be created by GDataDirectoryService's CreateGDataFile and
CreateGDataDirectory. Make GDataEntry ctor protected.
BUG=141494
TEST=unit tests.
Review URL: https://chromiumcodereview.appspot.com/10854083
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@151008 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void GDataFileSystem::OnGetDocumentEntry(const FilePath& cache_file_path,
const GetFileFromCacheParams& params,
GDataErrorCode status,
scoped_ptr<base::Value> data) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
GDataFileError error = util::GDataToGDataFileError(status);
scoped_ptr<GDataEntry> fresh_entry;
if (error == GDATA_FILE_OK) {
scoped_ptr<DocumentEntry> doc_entry(DocumentEntry::ExtractAndParse(*data));
if (doc_entry.get()) {
fresh_entry.reset(directory_service_->FromDocumentEntry(doc_entry.get()));
}
if (!fresh_entry.get() || !fresh_entry->AsGDataFile()) {
LOG(ERROR) << "Got invalid entry from server for " << params.resource_id;
error = GDATA_FILE_ERROR_FAILED;
}
}
if (error != GDATA_FILE_OK) {
if (!params.get_file_callback.is_null()) {
params.get_file_callback.Run(error,
cache_file_path,
params.mime_type,
REGULAR_FILE);
}
return;
}
GURL content_url = fresh_entry->content_url();
int64 file_size = fresh_entry->file_info().size;
DCHECK_EQ(params.resource_id, fresh_entry->resource_id());
scoped_ptr<GDataFile> fresh_entry_as_file(
fresh_entry.release()->AsGDataFile());
directory_service_->RefreshFile(fresh_entry_as_file.Pass());
bool* has_enough_space = new bool(false);
util::PostBlockingPoolSequencedTaskAndReply(
FROM_HERE,
blocking_task_runner_,
base::Bind(&GDataCache::FreeDiskSpaceIfNeededFor,
base::Unretained(cache_),
file_size,
has_enough_space),
base::Bind(&GDataFileSystem::StartDownloadFileIfEnoughSpace,
ui_weak_ptr_,
params,
content_url,
cache_file_path,
base::Owned(has_enough_space)));
}
| 171,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ovl_copy_up_locked(struct dentry *workdir, struct dentry *upperdir,
struct dentry *dentry, struct path *lowerpath,
struct kstat *stat, struct iattr *attr,
const char *link)
{
struct inode *wdir = workdir->d_inode;
struct inode *udir = upperdir->d_inode;
struct dentry *newdentry = NULL;
struct dentry *upper = NULL;
umode_t mode = stat->mode;
int err;
newdentry = ovl_lookup_temp(workdir, dentry);
err = PTR_ERR(newdentry);
if (IS_ERR(newdentry))
goto out;
upper = lookup_one_len(dentry->d_name.name, upperdir,
dentry->d_name.len);
err = PTR_ERR(upper);
if (IS_ERR(upper))
goto out1;
/* Can't properly set mode on creation because of the umask */
stat->mode &= S_IFMT;
err = ovl_create_real(wdir, newdentry, stat, link, NULL, true);
stat->mode = mode;
if (err)
goto out2;
if (S_ISREG(stat->mode)) {
struct path upperpath;
ovl_path_upper(dentry, &upperpath);
BUG_ON(upperpath.dentry != NULL);
upperpath.dentry = newdentry;
err = ovl_copy_up_data(lowerpath, &upperpath, stat->size);
if (err)
goto out_cleanup;
}
err = ovl_copy_xattr(lowerpath->dentry, newdentry);
if (err)
goto out_cleanup;
mutex_lock(&newdentry->d_inode->i_mutex);
err = ovl_set_attr(newdentry, stat);
if (!err && attr)
err = notify_change(newdentry, attr, NULL);
mutex_unlock(&newdentry->d_inode->i_mutex);
if (err)
goto out_cleanup;
err = ovl_do_rename(wdir, newdentry, udir, upper, 0);
if (err)
goto out_cleanup;
ovl_dentry_update(dentry, newdentry);
newdentry = NULL;
/*
* Non-directores become opaque when copied up.
*/
if (!S_ISDIR(stat->mode))
ovl_dentry_set_opaque(dentry, true);
out2:
dput(upper);
out1:
dput(newdentry);
out:
return err;
out_cleanup:
ovl_cleanup(wdir, newdentry);
goto out;
}
Commit Message: ovl: fix dentry reference leak
In ovl_copy_up_locked(), newdentry is leaked if the function exits through
out_cleanup as this just to out after calling ovl_cleanup() - which doesn't
actually release the ref on newdentry.
The out_cleanup segment should instead exit through out2 as certainly
newdentry leaks - and possibly upper does also, though this isn't caught
given the catch of newdentry.
Without this fix, something like the following is seen:
BUG: Dentry ffff880023e9eb20{i=f861,n=#ffff880023e82d90} still in use (1) [unmount of tmpfs tmpfs]
BUG: Dentry ffff880023ece640{i=0,n=bigfile} still in use (1) [unmount of tmpfs tmpfs]
when unmounting the upper layer after an error occurred in copyup.
An error can be induced by creating a big file in a lower layer with
something like:
dd if=/dev/zero of=/lower/a/bigfile bs=65536 count=1 seek=$((0xf000))
to create a large file (4.1G). Overlay an upper layer that is too small
(on tmpfs might do) and then induce a copy up by opening it writably.
Reported-by: Ulrich Obergfell <[email protected]>
Signed-off-by: David Howells <[email protected]>
Signed-off-by: Miklos Szeredi <[email protected]>
Cc: <[email protected]> # v3.18+
CWE ID: CWE-399 | static int ovl_copy_up_locked(struct dentry *workdir, struct dentry *upperdir,
struct dentry *dentry, struct path *lowerpath,
struct kstat *stat, struct iattr *attr,
const char *link)
{
struct inode *wdir = workdir->d_inode;
struct inode *udir = upperdir->d_inode;
struct dentry *newdentry = NULL;
struct dentry *upper = NULL;
umode_t mode = stat->mode;
int err;
newdentry = ovl_lookup_temp(workdir, dentry);
err = PTR_ERR(newdentry);
if (IS_ERR(newdentry))
goto out;
upper = lookup_one_len(dentry->d_name.name, upperdir,
dentry->d_name.len);
err = PTR_ERR(upper);
if (IS_ERR(upper))
goto out1;
/* Can't properly set mode on creation because of the umask */
stat->mode &= S_IFMT;
err = ovl_create_real(wdir, newdentry, stat, link, NULL, true);
stat->mode = mode;
if (err)
goto out2;
if (S_ISREG(stat->mode)) {
struct path upperpath;
ovl_path_upper(dentry, &upperpath);
BUG_ON(upperpath.dentry != NULL);
upperpath.dentry = newdentry;
err = ovl_copy_up_data(lowerpath, &upperpath, stat->size);
if (err)
goto out_cleanup;
}
err = ovl_copy_xattr(lowerpath->dentry, newdentry);
if (err)
goto out_cleanup;
mutex_lock(&newdentry->d_inode->i_mutex);
err = ovl_set_attr(newdentry, stat);
if (!err && attr)
err = notify_change(newdentry, attr, NULL);
mutex_unlock(&newdentry->d_inode->i_mutex);
if (err)
goto out_cleanup;
err = ovl_do_rename(wdir, newdentry, udir, upper, 0);
if (err)
goto out_cleanup;
ovl_dentry_update(dentry, newdentry);
newdentry = NULL;
/*
* Non-directores become opaque when copied up.
*/
if (!S_ISDIR(stat->mode))
ovl_dentry_set_opaque(dentry, true);
out2:
dput(upper);
out1:
dput(newdentry);
out:
return err;
out_cleanup:
ovl_cleanup(wdir, newdentry);
goto out2;
}
| 167,469 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
SetContentViewCore(NULL);
if (!shared_surface_.is_null()) {
ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle(
shared_surface_);
}
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | RenderWidgetHostViewAndroid::~RenderWidgetHostViewAndroid() {
SetContentViewCore(NULL);
if (!shared_surface_.is_null()) {
ImageTransportFactoryAndroid::GetInstance()->DestroySharedSurfaceHandle(
shared_surface_);
}
if (texture_id_in_layer_) {
ImageTransportFactoryAndroid::GetInstance()->DeleteTexture(
texture_id_in_layer_);
}
}
| 171,371 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
Commit Message: ...
CWE ID: CWE-754 | static Image *ReadOneJNGImage(MngInfo *mng_info,
const ImageInfo *image_info, ExceptionInfo *exception)
{
Image
*alpha_image,
*color_image,
*image,
*jng_image;
ImageInfo
*alpha_image_info,
*color_image_info;
MagickBooleanType
logging;
int
unique_filenames;
ssize_t
y;
MagickBooleanType
status;
png_uint_32
jng_height,
jng_width;
png_byte
jng_color_type,
jng_image_sample_depth,
jng_image_compression_method,
jng_image_interlace_method,
jng_alpha_sample_depth,
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method;
register const PixelPacket
*s;
register ssize_t
i,
x;
register PixelPacket
*q;
register unsigned char
*p;
unsigned int
read_JSEP,
reading_idat;
size_t
length;
jng_alpha_compression_method=0;
jng_alpha_sample_depth=8;
jng_color_type=0;
jng_height=0;
jng_width=0;
alpha_image=(Image *) NULL;
color_image=(Image *) NULL;
alpha_image_info=(ImageInfo *) NULL;
color_image_info=(ImageInfo *) NULL;
unique_filenames=0;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter ReadOneJNGImage()");
image=mng_info->image;
if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL)
{
/*
Allocate next image structure.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireNextImage()");
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
mng_info->image=image;
/*
Signature bytes have already been read.
*/
read_JSEP=MagickFalse;
reading_idat=MagickFalse;
for (;;)
{
char
type[MaxTextExtent];
unsigned char
*chunk;
unsigned int
count;
/*
Read a new JNG chunk.
*/
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
break;
type[0]='\0';
(void) ConcatenateMagickString(type,"errr",MaxTextExtent);
length=ReadBlobMSBLong(image);
count=(unsigned int) ReadBlob(image,4,(unsigned char *) type);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading JNG chunk type %c%c%c%c, length: %.20g",
type[0],type[1],type[2],type[3],(double) length);
if (length > PNG_UINT_31_MAX || count == 0)
ThrowReaderException(CorruptImageError,"CorruptImage");
p=NULL;
chunk=(unsigned char *) NULL;
if (length != 0)
{
chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk));
if (chunk == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=ReadBlobByte(image);
if (c == EOF)
break;
chunk[i]=(unsigned char) c;
}
p=chunk;
}
(void) ReadBlobMSBLong(image); /* read crc word */
if (memcmp(type,mng_JHDR,4) == 0)
{
if (length == 16)
{
jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) |
(p[2] << 8) | p[3]);
jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) |
(p[6] << 8) | p[7]);
if ((jng_width == 0) || (jng_height == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
jng_color_type=p[8];
jng_image_sample_depth=p[9];
jng_image_compression_method=p[10];
jng_image_interlace_method=p[11];
image->interlace=jng_image_interlace_method != 0 ? PNGInterlace :
NoInterlace;
jng_alpha_sample_depth=p[12];
jng_alpha_compression_method=p[13];
jng_alpha_filter_method=p[14];
jng_alpha_interlace_method=p[15];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_width: %16lu, jng_height: %16lu\n"
" jng_color_type: %16d, jng_image_sample_depth: %3d\n"
" jng_image_compression_method:%3d",
(unsigned long) jng_width, (unsigned long) jng_height,
jng_color_type, jng_image_sample_depth,
jng_image_compression_method);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_image_interlace_method: %3d"
" jng_alpha_sample_depth: %3d",
jng_image_interlace_method,
jng_alpha_sample_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" jng_alpha_compression_method:%3d\n"
" jng_alpha_filter_method: %3d\n"
" jng_alpha_interlace_method: %3d",
jng_alpha_compression_method,
jng_alpha_filter_method,
jng_alpha_interlace_method);
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) &&
((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) ||
(memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0)))
{
/*
o create color_image
o open color_blob, attached to color_image
o if (color type has alpha)
open alpha_blob, attached to alpha_image
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating color_blob.");
color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo));
if (color_image_info == (ImageInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
GetImageInfo(color_image_info);
color_image=AcquireImage(color_image_info);
if (color_image == (Image *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) AcquireUniqueFilename(color_image->filename);
unique_filenames++;
status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if ((image_info->ping == MagickFalse) && (jng_color_type >= 12))
{
alpha_image_info=(ImageInfo *)
AcquireMagickMemory(sizeof(ImageInfo));
if (alpha_image_info == (ImageInfo *) NULL)
{
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
GetImageInfo(alpha_image_info);
alpha_image=AcquireImage(alpha_image_info);
if (alpha_image == (Image *) NULL)
{
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating alpha_blob.");
(void) AcquireUniqueFilename(alpha_image->filename);
unique_filenames++;
status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode,
exception);
if (status == MagickFalse)
{
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
color_image=DestroyImage(color_image);
return(DestroyImageList(image));
}
if (jng_alpha_compression_method == 0)
{
unsigned char
data[18];
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing IHDR chunk to alpha_blob.");
(void) WriteBlob(alpha_image,8,(const unsigned char *)
"\211PNG\r\n\032\n");
(void) WriteBlobMSBULong(alpha_image,13L);
PNGType(data,mng_IHDR);
LogPNGChunk(logging,mng_IHDR,13L);
PNGLong(data+4,jng_width);
PNGLong(data+8,jng_height);
data[12]=jng_alpha_sample_depth;
data[13]=0; /* color_type gray */
data[14]=0; /* compression method 0 */
data[15]=0; /* filter_method 0 */
data[16]=0; /* interlace_method 0 */
(void) WriteBlob(alpha_image,17,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,17));
}
}
reading_idat=MagickTrue;
}
if (memcmp(type,mng_JDAT,4) == 0)
{
/* Copy chunk to color_image->blob */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAT chunk data to color_blob.");
if (length != 0)
{
(void) WriteBlob(color_image,length,chunk);
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
}
continue;
}
if (memcmp(type,mng_IDAT,4) == 0)
{
png_byte
data[5];
/* Copy IDAT header and chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying IDAT chunk data to alpha_blob.");
(void) WriteBlobMSBULong(alpha_image,(size_t) length);
PNGType(data,mng_IDAT);
LogPNGChunk(logging,mng_IDAT,length);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlob(alpha_image,length,chunk);
(void) WriteBlobMSBULong(alpha_image,
crc32(crc32(0,data,4),chunk,(uInt) length));
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0))
{
/* Copy chunk data to alpha_image->blob */
if (alpha_image != NULL && image_info->ping == MagickFalse)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying JDAA chunk data to alpha_blob.");
(void) WriteBlob(alpha_image,length,chunk);
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_JSEP,4) == 0)
{
read_JSEP=MagickTrue;
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_bKGD,4) == 0)
{
if (length == 2)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=image->background_color.red;
image->background_color.blue=image->background_color.red;
}
if (length == 6)
{
image->background_color.red=ScaleCharToQuantum(p[1]);
image->background_color.green=ScaleCharToQuantum(p[3]);
image->background_color.blue=ScaleCharToQuantum(p[5]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_gAMA,4) == 0)
{
if (length == 4)
image->gamma=((float) mng_get_long(p))*0.00001;
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_cHRM,4) == 0)
{
if (length == 32)
{
image->chromaticity.white_point.x=0.00001*mng_get_long(p);
image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]);
image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]);
image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]);
image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]);
image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]);
image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]);
image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]);
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_sRGB,4) == 0)
{
if (length == 1)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]);
image->gamma=1.000f/2.200f;
image->chromaticity.red_primary.x=0.6400f;
image->chromaticity.red_primary.y=0.3300f;
image->chromaticity.green_primary.x=0.3000f;
image->chromaticity.green_primary.y=0.6000f;
image->chromaticity.blue_primary.x=0.1500f;
image->chromaticity.blue_primary.y=0.0600f;
image->chromaticity.white_point.x=0.3127f;
image->chromaticity.white_point.y=0.3290f;
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_oFFs,4) == 0)
{
if (length > 8)
{
image->page.x=(ssize_t) mng_get_long(p);
image->page.y=(ssize_t) mng_get_long(&p[4]);
if ((int) p[8] != 0)
{
image->page.x/=10000;
image->page.y/=10000;
}
}
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
if (memcmp(type,mng_pHYs,4) == 0)
{
if (length > 8)
{
image->x_resolution=(double) mng_get_long(p);
image->y_resolution=(double) mng_get_long(&p[4]);
if ((int) p[8] == PNG_RESOLUTION_METER)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=image->x_resolution/100.0f;
image->y_resolution=image->y_resolution/100.0f;
}
}
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#if 0
if (memcmp(type,mng_iCCP,4) == 0)
{
/* To do: */
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
continue;
}
#endif
if (length != 0)
chunk=(unsigned char *) RelinquishMagickMemory(chunk);
if (memcmp(type,mng_IEND,4))
continue;
break;
}
/* IEND found */
/*
Finish up reading image data:
o read main image from color_blob.
o close color_blob.
o if (color_type has alpha)
if alpha_encoding is PNG
read secondary image from alpha_blob via ReadPNG
if alpha_encoding is JPEG
read secondary image from alpha_blob via ReadJPEG
o close alpha_blob.
o copy intensity of secondary image into
opacity samples of main image.
o destroy the secondary image.
*/
if (color_image_info == (ImageInfo *) NULL)
{
assert(color_image == (Image *) NULL);
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
if (color_image == (Image *) NULL)
{
assert(alpha_image == (Image *) NULL);
return(DestroyImageList(image));
}
(void) SeekBlob(color_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading jng_image from color_blob.");
assert(color_image_info != (ImageInfo *) NULL);
(void) FormatLocaleString(color_image_info->filename,MaxTextExtent,"%s",
color_image->filename);
color_image_info->ping=MagickFalse; /* To do: avoid this */
jng_image=ReadImage(color_image_info,exception);
(void) RelinquishUniqueFileResource(color_image->filename);
unique_filenames--;
color_image=DestroyImage(color_image);
color_image_info=DestroyImageInfo(color_image_info);
if (jng_image == (Image *) NULL)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Copying jng_image pixels to main image.");
image->columns=jng_width;
image->rows=jng_height;
length=image->columns*sizeof(PixelPacket);
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
(void) CopyMagickMemory(q,s,length);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
jng_image=DestroyImage(jng_image);
if (image_info->ping == MagickFalse)
{
if (jng_color_type >= 12)
{
if (jng_alpha_compression_method == 0)
{
png_byte
data[5];
(void) WriteBlobMSBULong(alpha_image,0x00000000L);
PNGType(data,mng_IEND);
LogPNGChunk(logging,mng_IEND,0L);
(void) WriteBlob(alpha_image,4,data);
(void) WriteBlobMSBULong(alpha_image,crc32(0,data,4));
}
(void) SeekBlob(alpha_image,0,SEEK_SET);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reading opacity from alpha_blob.");
(void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent,
"%s",alpha_image->filename);
jng_image=ReadImage(alpha_image_info,exception);
if (jng_image != (Image *) NULL)
for (y=0; y < (ssize_t) image->rows; y++)
{
s=GetVirtualPixels(jng_image,0,y,image->columns,1,
&image->exception);
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (image->matte != MagickFalse)
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
SetPixelOpacity(q,QuantumRange-
GetPixelRed(s));
else
for (x=(ssize_t) image->columns; x != 0; x--,q++,s++)
{
SetPixelAlpha(q,GetPixelRed(s));
if (GetPixelOpacity(q) != OpaqueOpacity)
image->matte=MagickTrue;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
(void) RelinquishUniqueFileResource(alpha_image->filename);
unique_filenames--;
alpha_image=DestroyImage(alpha_image);
alpha_image_info=DestroyImageInfo(alpha_image_info);
if (jng_image != (Image *) NULL)
jng_image=DestroyImage(jng_image);
}
}
/* Read the JNG image. */
if (mng_info->mng_type == 0)
{
mng_info->mng_width=jng_width;
mng_info->mng_height=jng_height;
}
if (image->page.width == 0 && image->page.height == 0)
{
image->page.width=jng_width;
image->page.height=jng_height;
}
if (image->page.x == 0 && image->page.y == 0)
{
image->page.x=mng_info->x_off[mng_info->object_id];
image->page.y=mng_info->y_off[mng_info->object_id];
}
else
{
image->page.y=mng_info->y_off[mng_info->object_id];
}
mng_info->image_found++;
status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image),
2*GetBlobSize(image));
if (status == MagickFalse)
return(DestroyImageList(image));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit ReadOneJNGImage(); unique_filenames=%d",unique_filenames);
return(image);
}
| 170,025 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PageInfoUI::GetSecurityDescription(const IdentityInfo& identity_info) const {
std::unique_ptr<PageInfoUI::SecurityDescription> security_description(
new PageInfoUI::SecurityDescription());
switch (identity_info.safe_browsing_status) {
case PageInfo::SAFE_BROWSING_STATUS_NONE:
break;
case PageInfo::SAFE_BROWSING_STATUS_MALWARE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_MALWARE_SUMMARY,
IDS_PAGE_INFO_MALWARE_DETAILS);
case PageInfo::SAFE_BROWSING_STATUS_SOCIAL_ENGINEERING:
return CreateSecurityDescription(
SecuritySummaryColor::RED, IDS_PAGE_INFO_SOCIAL_ENGINEERING_SUMMARY,
IDS_PAGE_INFO_SOCIAL_ENGINEERING_DETAILS);
case PageInfo::SAFE_BROWSING_STATUS_UNWANTED_SOFTWARE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_UNWANTED_SOFTWARE_SUMMARY,
IDS_PAGE_INFO_UNWANTED_SOFTWARE_DETAILS);
case PageInfo::SAFE_BROWSING_STATUS_SIGN_IN_PASSWORD_REUSE:
#if defined(FULL_SAFE_BROWSING)
return CreateSecurityDescriptionForPasswordReuse(
/*is_enterprise_password=*/false);
#endif
NOTREACHED();
break;
case PageInfo::SAFE_BROWSING_STATUS_ENTERPRISE_PASSWORD_REUSE:
#if defined(FULL_SAFE_BROWSING)
return CreateSecurityDescriptionForPasswordReuse(
/*is_enterprise_password=*/true);
#endif
NOTREACHED();
break;
case PageInfo::SAFE_BROWSING_STATUS_BILLING:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_BILLING_SUMMARY,
IDS_PAGE_INFO_BILLING_DETAILS);
}
switch (identity_info.identity_status) {
case PageInfo::SITE_IDENTITY_STATUS_INTERNAL_PAGE:
#if defined(OS_ANDROID)
return CreateSecurityDescription(SecuritySummaryColor::GREEN,
IDS_PAGE_INFO_INTERNAL_PAGE,
IDS_PAGE_INFO_INTERNAL_PAGE);
#else
NOTREACHED();
FALLTHROUGH;
#endif
case PageInfo::SITE_IDENTITY_STATUS_EV_CERT:
FALLTHROUGH;
case PageInfo::SITE_IDENTITY_STATUS_CERT:
FALLTHROUGH;
case PageInfo::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN:
FALLTHROUGH;
case PageInfo::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT:
switch (identity_info.connection_status) {
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_FORM_ACTION:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_PASSIVE_SUBRESOURCE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_MIXED_CONTENT_DETAILS);
default:
return CreateSecurityDescription(SecuritySummaryColor::GREEN,
IDS_PAGE_INFO_SECURE_SUMMARY,
IDS_PAGE_INFO_SECURE_DETAILS);
}
case PageInfo::SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM:
case PageInfo::SITE_IDENTITY_STATUS_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_NO_CERT:
default:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
}
}
Commit Message: Revert "PageInfo: decouple safe browsing and TLS statii."
This reverts commit ee95bc44021230127c7e6e9a8cf9d3820760f77c.
Reason for revert: suspect causing unit_tests failure on Linux MSAN Tests:
https://ci.chromium.org/p/chromium/builders/ci/Linux%20MSan%20Tests/17649
PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
PageInfoBubbleViewTest.EnsureCloseCallback
PageInfoBubbleViewTest.NotificationPermissionRevokeUkm
PageInfoBubbleViewTest.OpenPageInfoBubbleAfterNavigationStart
PageInfoBubbleViewTest.SetPermissionInfo
PageInfoBubbleViewTest.SetPermissionInfoForUsbGuard
PageInfoBubbleViewTest.SetPermissionInfoWithPolicyUsbDevices
PageInfoBubbleViewTest.SetPermissionInfoWithUsbDevice
PageInfoBubbleViewTest.SetPermissionInfoWithUserAndPolicyUsbDevices
PageInfoBubbleViewTest.UpdatingSiteDataRetainsLayout
https://logs.chromium.org/logs/chromium/buildbucket/cr-buildbucket.appspot.com/8909718923797040064/+/steps/unit_tests/0/logs/Deterministic_failure:_PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered__status_CRASH_/0
[ RUN ] PageInfoBubbleViewTest.ChangingFlashSettingForSiteIsRemembered
==9056==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x561baaab15ec in PageInfoUI::GetSecurityDescription(PageInfoUI::IdentityInfo const&) const ./../../chrome/browser/ui/page_info/page_info_ui.cc:250:3
#1 0x561bab6a1548 in PageInfoBubbleView::SetIdentityInfo(PageInfoUI::IdentityInfo const&) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:802:7
#2 0x561baaaab3bb in PageInfo::PresentSiteIdentity() ./../../chrome/browser/ui/page_info/page_info.cc:969:8
#3 0x561baaaa0a21 in PageInfo::PageInfo(PageInfoUI*, Profile*, TabSpecificContentSettings*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&) ./../../chrome/browser/ui/page_info/page_info.cc:344:3
#4 0x561bab69b6dd in PageInfoBubbleView::PageInfoBubbleView(views::View*, gfx::Rect const&, aura::Window*, Profile*, content::WebContents*, GURL const&, security_state::SecurityLevel, security_state::VisibleSecurityState const&, base::OnceCallback<void (views::Widget::ClosedReason, bool)>) ./../../chrome/browser/ui/views/page_info/page_info_bubble_view.cc:576:24
...
Original change's description:
> PageInfo: decouple safe browsing and TLS statii.
>
> Previously, the Page Info bubble maintained a single variable to
> identify all reasons that a page might have a non-standard status. This
> lead to the display logic making assumptions about, for instance, the
> validity of a certificate when the page was flagged by Safe Browsing.
>
> This CL separates out the Safe Browsing status from the site identity
> status so that the page info bubble can inform the user that the site's
> certificate is invalid, even if it's also flagged by Safe Browsing.
>
> Bug: 869925
> Change-Id: I34107225b4206c8f32771ccd75e9367668d0a72b
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1662537
> Reviewed-by: Mustafa Emre Acer <[email protected]>
> Reviewed-by: Bret Sepulveda <[email protected]>
> Auto-Submit: Joe DeBlasio <[email protected]>
> Commit-Queue: Joe DeBlasio <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#671847}
[email protected],[email protected],[email protected]
Change-Id: I8be652952e7276bcc9266124693352e467159cc4
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: 869925
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1673985
Reviewed-by: Takashi Sakamoto <[email protected]>
Commit-Queue: Takashi Sakamoto <[email protected]>
Cr-Commit-Position: refs/heads/master@{#671932}
CWE ID: CWE-311 | PageInfoUI::GetSecurityDescription(const IdentityInfo& identity_info) const {
std::unique_ptr<PageInfoUI::SecurityDescription> security_description(
new PageInfoUI::SecurityDescription());
switch (identity_info.identity_status) {
case PageInfo::SITE_IDENTITY_STATUS_INTERNAL_PAGE:
#if defined(OS_ANDROID)
return CreateSecurityDescription(SecuritySummaryColor::GREEN,
IDS_PAGE_INFO_INTERNAL_PAGE,
IDS_PAGE_INFO_INTERNAL_PAGE);
#else
NOTREACHED();
FALLTHROUGH;
#endif
case PageInfo::SITE_IDENTITY_STATUS_EV_CERT:
FALLTHROUGH;
case PageInfo::SITE_IDENTITY_STATUS_CERT:
FALLTHROUGH;
case PageInfo::SITE_IDENTITY_STATUS_CERT_REVOCATION_UNKNOWN:
FALLTHROUGH;
case PageInfo::SITE_IDENTITY_STATUS_ADMIN_PROVIDED_CERT:
switch (identity_info.connection_status) {
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_ACTIVE_SUBRESOURCE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_FORM_ACTION:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
case PageInfo::SITE_CONNECTION_STATUS_INSECURE_PASSIVE_SUBRESOURCE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_MIXED_CONTENT_SUMMARY,
IDS_PAGE_INFO_MIXED_CONTENT_DETAILS);
default:
return CreateSecurityDescription(SecuritySummaryColor::GREEN,
IDS_PAGE_INFO_SECURE_SUMMARY,
IDS_PAGE_INFO_SECURE_DETAILS);
}
case PageInfo::SITE_IDENTITY_STATUS_MALWARE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_MALWARE_SUMMARY,
IDS_PAGE_INFO_MALWARE_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_SOCIAL_ENGINEERING:
return CreateSecurityDescription(
SecuritySummaryColor::RED, IDS_PAGE_INFO_SOCIAL_ENGINEERING_SUMMARY,
IDS_PAGE_INFO_SOCIAL_ENGINEERING_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_UNWANTED_SOFTWARE:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_UNWANTED_SOFTWARE_SUMMARY,
IDS_PAGE_INFO_UNWANTED_SOFTWARE_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_SIGN_IN_PASSWORD_REUSE:
#if defined(FULL_SAFE_BROWSING)
return CreateSecurityDescriptionForPasswordReuse(
/*is_enterprise_password=*/false);
#endif
case PageInfo::SITE_IDENTITY_STATUS_ENTERPRISE_PASSWORD_REUSE:
#if defined(FULL_SAFE_BROWSING)
return CreateSecurityDescriptionForPasswordReuse(
/*is_enterprise_password=*/true);
#endif
case PageInfo::SITE_IDENTITY_STATUS_BILLING:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_BILLING_SUMMARY,
IDS_PAGE_INFO_BILLING_DETAILS);
case PageInfo::SITE_IDENTITY_STATUS_DEPRECATED_SIGNATURE_ALGORITHM:
case PageInfo::SITE_IDENTITY_STATUS_UNKNOWN:
case PageInfo::SITE_IDENTITY_STATUS_NO_CERT:
default:
return CreateSecurityDescription(SecuritySummaryColor::RED,
IDS_PAGE_INFO_NOT_SECURE_SUMMARY,
IDS_PAGE_INFO_NOT_SECURE_DETAILS);
}
}
| 172,440 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int http_receive_data(HTTPContext *c)
{
HTTPContext *c1;
int len, loop_run = 0;
while (c->chunked_encoding && !c->chunk_size &&
c->buffer_end > c->buffer_ptr) {
/* read chunk header, if present */
len = recv(c->fd, c->buffer_ptr, 1, 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
/* error : close connection */
goto fail;
return 0;
} else if (len == 0) {
/* end of connection : close it */
goto fail;
} else if (c->buffer_ptr - c->buffer >= 2 &&
!memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
c->chunk_size = strtol(c->buffer, 0, 16);
if (c->chunk_size == 0) // end of stream
goto fail;
c->buffer_ptr = c->buffer;
break;
} else if (++loop_run > 10)
/* no chunk header, abort */
goto fail;
else
c->buffer_ptr++;
}
if (c->buffer_end > c->buffer_ptr) {
len = recv(c->fd, c->buffer_ptr,
FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
/* error : close connection */
goto fail;
} else if (len == 0)
/* end of connection : close it */
goto fail;
else {
c->chunk_size -= len;
c->buffer_ptr += len;
c->data_count += len;
update_datarate(&c->datarate, c->data_count);
}
}
if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
if (c->buffer[0] != 'f' ||
c->buffer[1] != 'm') {
http_log("Feed stream has become desynchronized -- disconnecting\n");
goto fail;
}
}
if (c->buffer_ptr >= c->buffer_end) {
FFServerStream *feed = c->stream;
/* a packet has been received : write it in the store, except
* if header */
if (c->data_count > FFM_PACKET_SIZE) {
/* XXX: use llseek or url_seek
* XXX: Should probably fail? */
if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
http_log("Error writing to feed file: %s\n", strerror(errno));
goto fail;
}
feed->feed_write_index += FFM_PACKET_SIZE;
/* update file size */
if (feed->feed_write_index > c->stream->feed_size)
feed->feed_size = feed->feed_write_index;
/* handle wrap around if max file size reached */
if (c->stream->feed_max_size &&
feed->feed_write_index >= c->stream->feed_max_size)
feed->feed_write_index = FFM_PACKET_SIZE;
/* write index */
if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
http_log("Error writing index to feed file: %s\n",
strerror(errno));
goto fail;
}
/* wake up any waiting connections */
for(c1 = first_http_ctx; c1; c1 = c1->next) {
if (c1->state == HTTPSTATE_WAIT_FEED &&
c1->stream->feed == c->stream->feed)
c1->state = HTTPSTATE_SEND_DATA;
}
} else {
/* We have a header in our hands that contains useful data */
AVFormatContext *s = avformat_alloc_context();
AVIOContext *pb;
AVInputFormat *fmt_in;
int i;
if (!s)
goto fail;
/* use feed output format name to find corresponding input format */
fmt_in = av_find_input_format(feed->fmt->name);
if (!fmt_in)
goto fail;
pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
0, NULL, NULL, NULL, NULL);
if (!pb)
goto fail;
pb->seekable = 0;
s->pb = pb;
if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
av_freep(&pb);
goto fail;
}
/* Now we have the actual streams */
if (s->nb_streams != feed->nb_streams) {
avformat_close_input(&s);
av_freep(&pb);
http_log("Feed '%s' stream number does not match registered feed\n",
c->stream->feed_filename);
goto fail;
}
for (i = 0; i < s->nb_streams; i++) {
LayeredAVStream *fst = feed->streams[i];
AVStream *st = s->streams[i];
avcodec_parameters_to_context(fst->codec, st->codecpar);
avcodec_parameters_from_context(fst->codecpar, fst->codec);
}
avformat_close_input(&s);
av_freep(&pb);
}
c->buffer_ptr = c->buffer;
}
return 0;
fail:
c->stream->feed_opened = 0;
close(c->feed_fd);
/* wake up any waiting connections to stop waiting for feed */
for(c1 = first_http_ctx; c1; c1 = c1->next) {
if (c1->state == HTTPSTATE_WAIT_FEED &&
c1->stream->feed == c->stream->feed)
c1->state = HTTPSTATE_SEND_DATA_TRAILER;
}
return -1;
}
Commit Message: ffserver: Check chunk size
Fixes out of array access
Fixes: poc_ffserver.py
Found-by: Paul Cher <[email protected]>
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int http_receive_data(HTTPContext *c)
{
HTTPContext *c1;
int len, loop_run = 0;
while (c->chunked_encoding && !c->chunk_size &&
c->buffer_end > c->buffer_ptr) {
/* read chunk header, if present */
len = recv(c->fd, c->buffer_ptr, 1, 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
/* error : close connection */
goto fail;
return 0;
} else if (len == 0) {
/* end of connection : close it */
goto fail;
} else if (c->buffer_ptr - c->buffer >= 2 &&
!memcmp(c->buffer_ptr - 1, "\r\n", 2)) {
c->chunk_size = strtol(c->buffer, 0, 16);
if (c->chunk_size <= 0) { // end of stream or invalid chunk size
c->chunk_size = 0;
goto fail;
}
c->buffer_ptr = c->buffer;
break;
} else if (++loop_run > 10)
/* no chunk header, abort */
goto fail;
else
c->buffer_ptr++;
}
if (c->buffer_end > c->buffer_ptr) {
len = recv(c->fd, c->buffer_ptr,
FFMIN(c->chunk_size, c->buffer_end - c->buffer_ptr), 0);
if (len < 0) {
if (ff_neterrno() != AVERROR(EAGAIN) &&
ff_neterrno() != AVERROR(EINTR))
/* error : close connection */
goto fail;
} else if (len == 0)
/* end of connection : close it */
goto fail;
else {
av_assert0(len <= c->chunk_size);
c->chunk_size -= len;
c->buffer_ptr += len;
c->data_count += len;
update_datarate(&c->datarate, c->data_count);
}
}
if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) {
if (c->buffer[0] != 'f' ||
c->buffer[1] != 'm') {
http_log("Feed stream has become desynchronized -- disconnecting\n");
goto fail;
}
}
if (c->buffer_ptr >= c->buffer_end) {
FFServerStream *feed = c->stream;
/* a packet has been received : write it in the store, except
* if header */
if (c->data_count > FFM_PACKET_SIZE) {
/* XXX: use llseek or url_seek
* XXX: Should probably fail? */
if (lseek(c->feed_fd, feed->feed_write_index, SEEK_SET) == -1)
http_log("Seek to %"PRId64" failed\n", feed->feed_write_index);
if (write(c->feed_fd, c->buffer, FFM_PACKET_SIZE) < 0) {
http_log("Error writing to feed file: %s\n", strerror(errno));
goto fail;
}
feed->feed_write_index += FFM_PACKET_SIZE;
/* update file size */
if (feed->feed_write_index > c->stream->feed_size)
feed->feed_size = feed->feed_write_index;
/* handle wrap around if max file size reached */
if (c->stream->feed_max_size &&
feed->feed_write_index >= c->stream->feed_max_size)
feed->feed_write_index = FFM_PACKET_SIZE;
/* write index */
if (ffm_write_write_index(c->feed_fd, feed->feed_write_index) < 0) {
http_log("Error writing index to feed file: %s\n",
strerror(errno));
goto fail;
}
/* wake up any waiting connections */
for(c1 = first_http_ctx; c1; c1 = c1->next) {
if (c1->state == HTTPSTATE_WAIT_FEED &&
c1->stream->feed == c->stream->feed)
c1->state = HTTPSTATE_SEND_DATA;
}
} else {
/* We have a header in our hands that contains useful data */
AVFormatContext *s = avformat_alloc_context();
AVIOContext *pb;
AVInputFormat *fmt_in;
int i;
if (!s)
goto fail;
/* use feed output format name to find corresponding input format */
fmt_in = av_find_input_format(feed->fmt->name);
if (!fmt_in)
goto fail;
pb = avio_alloc_context(c->buffer, c->buffer_end - c->buffer,
0, NULL, NULL, NULL, NULL);
if (!pb)
goto fail;
pb->seekable = 0;
s->pb = pb;
if (avformat_open_input(&s, c->stream->feed_filename, fmt_in, NULL) < 0) {
av_freep(&pb);
goto fail;
}
/* Now we have the actual streams */
if (s->nb_streams != feed->nb_streams) {
avformat_close_input(&s);
av_freep(&pb);
http_log("Feed '%s' stream number does not match registered feed\n",
c->stream->feed_filename);
goto fail;
}
for (i = 0; i < s->nb_streams; i++) {
LayeredAVStream *fst = feed->streams[i];
AVStream *st = s->streams[i];
avcodec_parameters_to_context(fst->codec, st->codecpar);
avcodec_parameters_from_context(fst->codecpar, fst->codec);
}
avformat_close_input(&s);
av_freep(&pb);
}
c->buffer_ptr = c->buffer;
}
return 0;
fail:
c->stream->feed_opened = 0;
close(c->feed_fd);
/* wake up any waiting connections to stop waiting for feed */
for(c1 = first_http_ctx; c1; c1 = c1->next) {
if (c1->state == HTTPSTATE_WAIT_FEED &&
c1->stream->feed == c->stream->feed)
c1->state = HTTPSTATE_SEND_DATA_TRAILER;
}
return -1;
}
| 168,494 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void sctp_generate_proto_unreach_event(unsigned long data)
{
struct sctp_transport *transport = (struct sctp_transport *) data;
struct sctp_association *asoc = transport->asoc;
struct net *net = sock_net(asoc->base.sk);
bh_lock_sock(asoc->base.sk);
if (sock_owned_by_user(asoc->base.sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->proto_unreach_timer,
jiffies + (HZ/20)))
sctp_association_hold(asoc);
goto out_unlock;
}
/* Is this structure just waiting around for us to actually
* get destroyed?
*/
if (asoc->base.dead)
goto out_unlock;
sctp_do_sm(net, SCTP_EVENT_T_OTHER,
SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),
asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC);
out_unlock:
bh_unlock_sock(asoc->base.sk);
sctp_association_put(asoc);
}
Commit Message: sctp: Prevent soft lockup when sctp_accept() is called during a timeout event
A case can occur when sctp_accept() is called by the user during
a heartbeat timeout event after the 4-way handshake. Since
sctp_assoc_migrate() changes both assoc->base.sk and assoc->ep, the
bh_sock_lock in sctp_generate_heartbeat_event() will be taken with
the listening socket but released with the new association socket.
The result is a deadlock on any future attempts to take the listening
socket lock.
Note that this race can occur with other SCTP timeouts that take
the bh_lock_sock() in the event sctp_accept() is called.
BUG: soft lockup - CPU#9 stuck for 67s! [swapper:0]
...
RIP: 0010:[<ffffffff8152d48e>] [<ffffffff8152d48e>] _spin_lock+0x1e/0x30
RSP: 0018:ffff880028323b20 EFLAGS: 00000206
RAX: 0000000000000002 RBX: ffff880028323b20 RCX: 0000000000000000
RDX: 0000000000000000 RSI: ffff880028323be0 RDI: ffff8804632c4b48
RBP: ffffffff8100bb93 R08: 0000000000000000 R09: 0000000000000000
R10: ffff880610662280 R11: 0000000000000100 R12: ffff880028323aa0
R13: ffff8804383c3880 R14: ffff880028323a90 R15: ffffffff81534225
FS: 0000000000000000(0000) GS:ffff880028320000(0000) knlGS:0000000000000000
CS: 0010 DS: 0018 ES: 0018 CR0: 000000008005003b
CR2: 00000000006df528 CR3: 0000000001a85000 CR4: 00000000000006e0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000ffff0ff0 DR7: 0000000000000400
Process swapper (pid: 0, threadinfo ffff880616b70000, task ffff880616b6cab0)
Stack:
ffff880028323c40 ffffffffa01c2582 ffff880614cfb020 0000000000000000
<d> 0100000000000000 00000014383a6c44 ffff8804383c3880 ffff880614e93c00
<d> ffff880614e93c00 0000000000000000 ffff8804632c4b00 ffff8804383c38b8
Call Trace:
<IRQ>
[<ffffffffa01c2582>] ? sctp_rcv+0x492/0xa10 [sctp]
[<ffffffff8148c559>] ? nf_iterate+0x69/0xb0
[<ffffffff814974a0>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8148c716>] ? nf_hook_slow+0x76/0x120
[<ffffffff814974a0>] ? ip_local_deliver_finish+0x0/0x2d0
[<ffffffff8149757d>] ? ip_local_deliver_finish+0xdd/0x2d0
[<ffffffff81497808>] ? ip_local_deliver+0x98/0xa0
[<ffffffff81496ccd>] ? ip_rcv_finish+0x12d/0x440
[<ffffffff81497255>] ? ip_rcv+0x275/0x350
[<ffffffff8145cfeb>] ? __netif_receive_skb+0x4ab/0x750
...
With lockdep debugging:
=====================================
[ BUG: bad unlock balance detected! ]
-------------------------------------
CslRx/12087 is trying to release lock (slock-AF_INET) at:
[<ffffffffa01bcae0>] sctp_generate_timeout_event+0x40/0xe0 [sctp]
but there are no more locks to release!
other info that might help us debug this:
2 locks held by CslRx/12087:
#0: (&asoc->timers[i]){+.-...}, at: [<ffffffff8108ce1f>] run_timer_softirq+0x16f/0x3e0
#1: (slock-AF_INET){+.-...}, at: [<ffffffffa01bcac3>] sctp_generate_timeout_event+0x23/0xe0 [sctp]
Ensure the socket taken is also the same one that is released by
saving a copy of the socket before entering the timeout event
critical section.
Signed-off-by: Karl Heiss <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | void sctp_generate_proto_unreach_event(unsigned long data)
{
struct sctp_transport *transport = (struct sctp_transport *) data;
struct sctp_association *asoc = transport->asoc;
struct sock *sk = asoc->base.sk;
struct net *net = sock_net(sk);
bh_lock_sock(sk);
if (sock_owned_by_user(sk)) {
pr_debug("%s: sock is busy\n", __func__);
/* Try again later. */
if (!mod_timer(&transport->proto_unreach_timer,
jiffies + (HZ/20)))
sctp_association_hold(asoc);
goto out_unlock;
}
/* Is this structure just waiting around for us to actually
* get destroyed?
*/
if (asoc->base.dead)
goto out_unlock;
sctp_do_sm(net, SCTP_EVENT_T_OTHER,
SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),
asoc->state, asoc->ep, asoc, transport, GFP_ATOMIC);
out_unlock:
bh_unlock_sock(sk);
sctp_association_put(asoc);
}
| 167,501 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,
struct cmsghdr *cmsg)
{
struct page *page = NULL;
struct rds_atomic_args *args;
int ret = 0;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))
|| rm->atomic.op_active)
return -EINVAL;
args = CMSG_DATA(cmsg);
/* Nonmasked & masked cmsg ops converted to masked hw ops */
switch (cmsg->cmsg_type) {
case RDS_CMSG_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = 0;
break;
case RDS_CMSG_MASKED_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->m_fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;
break;
case RDS_CMSG_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->cswp.compare;
rm->atomic.op_m_cswp.swap = args->cswp.swap;
rm->atomic.op_m_cswp.compare_mask = ~0;
rm->atomic.op_m_cswp.swap_mask = ~0;
break;
case RDS_CMSG_MASKED_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->m_cswp.compare;
rm->atomic.op_m_cswp.swap = args->m_cswp.swap;
rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;
rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;
break;
default:
BUG(); /* should never happen */
}
rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);
rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);
rm->atomic.op_active = 1;
rm->atomic.op_recverr = rs->rs_recverr;
rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);
if (!rm->atomic.op_sg) {
ret = -ENOMEM;
goto err;
}
/* verify 8 byte-aligned */
if (args->local_addr & 0x7) {
ret = -EFAULT;
goto err;
}
ret = rds_pin_pages(args->local_addr, 1, &page, 1);
if (ret != 1)
goto err;
ret = 0;
sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
if (rm->atomic.op_notify || rm->atomic.op_recverr) {
/* We allocate an uninitialized notifier here, because
* we don't want to do that in the completion handler. We
* would have to use GFP_ATOMIC there, and don't want to deal
* with failed allocations.
*/
rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);
if (!rm->atomic.op_notifier) {
ret = -ENOMEM;
goto err;
}
rm->atomic.op_notifier->n_user_token = args->user_token;
rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;
}
rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);
rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);
return ret;
err:
if (page)
put_page(page);
kfree(rm->atomic.op_notifier);
return ret;
}
Commit Message: RDS: null pointer dereference in rds_atomic_free_op
set rm->atomic.op_active to 0 when rds_pin_pages() fails
or the user supplied address is invalid,
this prevents a NULL pointer usage in rds_atomic_free_op()
Signed-off-by: Mohamed Ghannam <[email protected]>
Acked-by: Santosh Shilimkar <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-476 | int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,
struct cmsghdr *cmsg)
{
struct page *page = NULL;
struct rds_atomic_args *args;
int ret = 0;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))
|| rm->atomic.op_active)
return -EINVAL;
args = CMSG_DATA(cmsg);
/* Nonmasked & masked cmsg ops converted to masked hw ops */
switch (cmsg->cmsg_type) {
case RDS_CMSG_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = 0;
break;
case RDS_CMSG_MASKED_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->m_fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;
break;
case RDS_CMSG_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->cswp.compare;
rm->atomic.op_m_cswp.swap = args->cswp.swap;
rm->atomic.op_m_cswp.compare_mask = ~0;
rm->atomic.op_m_cswp.swap_mask = ~0;
break;
case RDS_CMSG_MASKED_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->m_cswp.compare;
rm->atomic.op_m_cswp.swap = args->m_cswp.swap;
rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;
rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;
break;
default:
BUG(); /* should never happen */
}
rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);
rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);
rm->atomic.op_active = 1;
rm->atomic.op_recverr = rs->rs_recverr;
rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);
if (!rm->atomic.op_sg) {
ret = -ENOMEM;
goto err;
}
/* verify 8 byte-aligned */
if (args->local_addr & 0x7) {
ret = -EFAULT;
goto err;
}
ret = rds_pin_pages(args->local_addr, 1, &page, 1);
if (ret != 1)
goto err;
ret = 0;
sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
if (rm->atomic.op_notify || rm->atomic.op_recverr) {
/* We allocate an uninitialized notifier here, because
* we don't want to do that in the completion handler. We
* would have to use GFP_ATOMIC there, and don't want to deal
* with failed allocations.
*/
rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);
if (!rm->atomic.op_notifier) {
ret = -ENOMEM;
goto err;
}
rm->atomic.op_notifier->n_user_token = args->user_token;
rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;
}
rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);
rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);
return ret;
err:
if (page)
put_page(page);
rm->atomic.op_active = 0;
kfree(rm->atomic.op_notifier);
return ret;
}
| 169,353 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static ssize_t ib_ucm_write(struct file *filp, const char __user *buf,
size_t len, loff_t *pos)
{
struct ib_ucm_file *file = filp->private_data;
struct ib_ucm_cmd_hdr hdr;
ssize_t result;
if (len < sizeof(hdr))
return -EINVAL;
if (copy_from_user(&hdr, buf, sizeof(hdr)))
return -EFAULT;
if (hdr.cmd >= ARRAY_SIZE(ucm_cmd_table))
return -EINVAL;
if (hdr.in + sizeof(hdr) > len)
return -EINVAL;
result = ucm_cmd_table[hdr.cmd](file, buf + sizeof(hdr),
hdr.in, hdr.out);
if (!result)
result = len;
return result;
}
Commit Message: IB/security: Restrict use of the write() interface
The drivers/infiniband stack uses write() as a replacement for
bi-directional ioctl(). This is not safe. There are ways to
trigger write calls that result in the return structure that
is normally written to user space being shunted off to user
specified kernel memory instead.
For the immediate repair, detect and deny suspicious accesses to
the write API.
For long term, update the user space libraries and the kernel API
to something that doesn't present the same security vulnerabilities
(likely a structured ioctl() interface).
The impacted uAPI interfaces are generally only available if
hardware from drivers/infiniband is installed in the system.
Reported-by: Jann Horn <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Signed-off-by: Jason Gunthorpe <[email protected]>
[ Expanded check to all known write() entry points ]
Cc: [email protected]
Signed-off-by: Doug Ledford <[email protected]>
CWE ID: CWE-264 | static ssize_t ib_ucm_write(struct file *filp, const char __user *buf,
size_t len, loff_t *pos)
{
struct ib_ucm_file *file = filp->private_data;
struct ib_ucm_cmd_hdr hdr;
ssize_t result;
if (WARN_ON_ONCE(!ib_safe_file_access(filp)))
return -EACCES;
if (len < sizeof(hdr))
return -EINVAL;
if (copy_from_user(&hdr, buf, sizeof(hdr)))
return -EFAULT;
if (hdr.cmd >= ARRAY_SIZE(ucm_cmd_table))
return -EINVAL;
if (hdr.in + sizeof(hdr) > len)
return -EINVAL;
result = ucm_cmd_table[hdr.cmd](file, buf + sizeof(hdr),
hdr.in, hdr.out);
if (!result)
result = len;
return result;
}
| 167,238 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct inet_sock *inet = inet_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
__be16 orig_sport, orig_dport;
__be32 daddr, nexthop;
struct flowi4 fl4;
struct rtable *rt;
int err;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
if (inet->opt != NULL && inet->opt->srr) {
if (daddr == 0)
return -EINVAL;
nexthop = inet->opt->faddr;
}
orig_sport = inet->inet_sport;
orig_dport = usin->sin_port;
rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_DCCP,
orig_sport, orig_dport, sk, true);
if (IS_ERR(rt))
return PTR_ERR(rt);
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (inet->opt == NULL || !inet->opt->srr)
daddr = rt->rt_dst;
if (inet->inet_saddr == 0)
inet->inet_saddr = rt->rt_src;
inet->inet_rcv_saddr = inet->inet_saddr;
inet->inet_dport = usin->sin_port;
inet->inet_daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet->opt != NULL)
inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen;
/*
* Socket identity is still unknown (sport may be zero).
* However we set state to DCCP_REQUESTING and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
dccp_set_state(sk, DCCP_REQUESTING);
err = inet_hash_connect(&dccp_death_row, sk);
if (err != 0)
goto failure;
rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport,
inet->inet_sport, inet->inet_dport, sk);
if (IS_ERR(rt)) {
rt = NULL;
goto failure;
}
/* OK, now commit destination to socket. */
sk_setup_caps(sk, &rt->dst);
dp->dccps_iss = secure_dccp_sequence_number(inet->inet_saddr,
inet->inet_daddr,
inet->inet_sport,
inet->inet_dport);
inet->inet_id = dp->dccps_iss ^ jiffies;
err = dccp_connect(sk);
rt = NULL;
if (err != 0)
goto failure;
out:
return err;
failure:
/*
* This unhashes the socket and releases the local port, if necessary.
*/
dccp_set_state(sk, DCCP_CLOSED);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->inet_dport = 0;
goto out;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
struct inet_sock *inet = inet_sk(sk);
struct dccp_sock *dp = dccp_sk(sk);
__be16 orig_sport, orig_dport;
__be32 daddr, nexthop;
struct flowi4 fl4;
struct rtable *rt;
int err;
struct ip_options_rcu *inet_opt;
dp->dccps_role = DCCP_ROLE_CLIENT;
if (addr_len < sizeof(struct sockaddr_in))
return -EINVAL;
if (usin->sin_family != AF_INET)
return -EAFNOSUPPORT;
nexthop = daddr = usin->sin_addr.s_addr;
inet_opt = rcu_dereference_protected(inet->inet_opt,
sock_owned_by_user(sk));
if (inet_opt != NULL && inet_opt->opt.srr) {
if (daddr == 0)
return -EINVAL;
nexthop = inet_opt->opt.faddr;
}
orig_sport = inet->inet_sport;
orig_dport = usin->sin_port;
rt = ip_route_connect(&fl4, nexthop, inet->inet_saddr,
RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
IPPROTO_DCCP,
orig_sport, orig_dport, sk, true);
if (IS_ERR(rt))
return PTR_ERR(rt);
if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
ip_rt_put(rt);
return -ENETUNREACH;
}
if (inet_opt == NULL || !inet_opt->opt.srr)
daddr = rt->rt_dst;
if (inet->inet_saddr == 0)
inet->inet_saddr = rt->rt_src;
inet->inet_rcv_saddr = inet->inet_saddr;
inet->inet_dport = usin->sin_port;
inet->inet_daddr = daddr;
inet_csk(sk)->icsk_ext_hdr_len = 0;
if (inet_opt)
inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen;
/*
* Socket identity is still unknown (sport may be zero).
* However we set state to DCCP_REQUESTING and not releasing socket
* lock select source port, enter ourselves into the hash tables and
* complete initialization after this.
*/
dccp_set_state(sk, DCCP_REQUESTING);
err = inet_hash_connect(&dccp_death_row, sk);
if (err != 0)
goto failure;
rt = ip_route_newports(&fl4, rt, orig_sport, orig_dport,
inet->inet_sport, inet->inet_dport, sk);
if (IS_ERR(rt)) {
rt = NULL;
goto failure;
}
/* OK, now commit destination to socket. */
sk_setup_caps(sk, &rt->dst);
dp->dccps_iss = secure_dccp_sequence_number(inet->inet_saddr,
inet->inet_daddr,
inet->inet_sport,
inet->inet_dport);
inet->inet_id = dp->dccps_iss ^ jiffies;
err = dccp_connect(sk);
rt = NULL;
if (err != 0)
goto failure;
out:
return err;
failure:
/*
* This unhashes the socket and releases the local port, if necessary.
*/
dccp_set_state(sk, DCCP_CLOSED);
ip_rt_put(rt);
sk->sk_route_caps = 0;
inet->inet_dport = 0;
goto out;
}
| 165,540 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
Commit Message: Camera: Disallow dumping clients directly
Camera service dumps should only be initiated through
ICameraService::dump.
Bug: 26265403
Change-Id: If3ca4718ed74bf33ad8a416192689203029e2803
CWE ID: CWE-264 | status_t ProCamera2Client::dump(int fd, const Vector<String16>& args) {
return BasicClient::dump(fd, args);
}
status_t ProCamera2Client::dumpClient(int fd, const Vector<String16>& args) {
String8 result;
result.appendFormat("ProCamera2Client[%d] (%p) PID: %d, dump:\n",
mCameraId,
getRemoteCallback()->asBinder().get(),
mClientPid);
result.append(" State: ");
mFrameProcessor->dump(fd, args);
return dumpDevice(fd, args);
}
| 173,940 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool omx_vdec::release_output_done(void)
{
bool bRet = false;
unsigned i=0,j=0;
DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_inp_mem_ptr);
if (m_out_mem_ptr) {
for (; j < drv_ctx.op_buf.actualcount ; j++) {
if (BITMASK_PRESENT(&m_out_bm_count,j)) {
break;
}
}
if (j == drv_ctx.op_buf.actualcount) {
m_out_bm_count = 0;
bRet = true;
}
} else {
m_out_bm_count = 0;
bRet = true;
}
return bRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: vdec: add safety checks for freeing buffers
Allow only up to 64 buffers on input/output port (since the
allocation bitmap is only 64-wide).
Do not allow changing theactual buffer count while still
holding allocation (Client can technically negotiate
buffer count on a free/disabled port)
Add safety checks to free only as many buffers were allocated.
Fixes: Security Vulnerability - Heap Overflow and Possible Local
Privilege Escalation in MediaServer (libOmxVdec problem #3)
Bug: 27532282 27661749
Change-Id: I06dd680d43feaef3efdc87311e8a6703e234b523
CWE ID: CWE-119 | bool omx_vdec::release_output_done(void)
{
bool bRet = false;
unsigned i=0,j=0;
DEBUG_PRINT_LOW("Value of m_out_mem_ptr %p",m_out_mem_ptr);
if (m_out_mem_ptr) {
for (; j < drv_ctx.op_buf.actualcount ; j++) {
if (BITMASK_PRESENT(&m_out_bm_count,j)) {
break;
}
}
if (j == drv_ctx.op_buf.actualcount) {
m_out_bm_count = 0;
bRet = true;
}
} else {
m_out_bm_count = 0;
bRet = true;
}
return bRet;
}
| 173,786 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"
R"([a-z][\u0585\u0581]+[a-z]|)"
R"(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"
R"([\p{scx=armn}][og]+[\p{scx=armn}]|)"
R"([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"
R"([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([^\p{scx=arab}][\u064b-\u0655\u0670]|)"
R"([^\p{scx=hebr}]\u05b4|)"
R"([ijl\u0131]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
Commit Message: Change the script mixing policy to highly restrictive
The current script mixing policy (moderately restricitive) allows
mixing of Latin-ASCII and one non-Latin script (unless the non-Latin
script is Cyrillic or Greek).
This CL tightens up the policy to block mixing of Latin-ASCII and
a non-Latin script unless the non-Latin script is Chinese (Hanzi,
Bopomofo), Japanese (Kanji, Hiragana, Katakana) or Korean (Hangul,
Hanja).
Major gTLDs (.net/.org/.com) do not allow the registration of
a domain that has both Latin and a non-Latin script. The only
exception is names with Latin + Chinese/Japanese/Korean scripts.
The same is true of ccTLDs with IDNs.
Given the above registration rules of major gTLDs and ccTLDs, allowing
mixing of Latin and non-Latin other than CJK has no practical effect. In
the meantime, domain names in TLDs with a laxer policy on script mixing
would be subject to a potential spoofing attempt with the current
moderately restrictive script mixing policy. To protect users from those
risks, there are a few ad-hoc rules in place.
By switching to highly restrictive those ad-hoc rules can be removed
simplifying the IDN display policy implementation a bit.
This is also coordinated with Mozilla. See
https://bugzilla.mozilla.org/show_bug.cgi?id=1399939 .
BUG=726950, 756226, 756456, 756735, 770465
TEST=components_unittests --gtest_filter=*IDN*
Change-Id: Ib96d0d588f7fcda38ffa0ce59e98a5bd5b439116
Reviewed-on: https://chromium-review.googlesource.com/688825
Reviewed-by: Brett Wilson <[email protected]>
Reviewed-by: Lucas Garron <[email protected]>
Commit-Queue: Jungshik Shin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#506561}
CWE ID: CWE-20 | bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label,
bool is_tld_ascii) {
UErrorCode status = U_ZERO_ERROR;
int32_t result =
uspoof_check(checker_, label.data(),
base::checked_cast<int32_t>(label.size()), NULL, &status);
if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS))
return false;
icu::UnicodeString label_string(FALSE, label.data(),
base::checked_cast<int32_t>(label.size()));
if (deviation_characters_.containsSome(label_string))
return false;
result &= USPOOF_RESTRICTION_LEVEL_MASK;
if (result == USPOOF_ASCII)
return true;
if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE &&
kana_letters_exceptions_.containsNone(label_string) &&
combining_diacritics_exceptions_.containsNone(label_string)) {
return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string);
}
if (non_ascii_latin_letters_.containsSome(label_string) &&
!lgc_letters_n_ascii_.containsAll(label_string))
return false;
if (!tls_index.initialized())
tls_index.Initialize(&OnThreadTermination);
icu::RegexMatcher* dangerous_pattern =
reinterpret_cast<icu::RegexMatcher*>(tls_index.Get());
if (!dangerous_pattern) {
icu::UnicodeString(
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"
R"([\u30ce\u30f3\u30bd\u30be])"
R"([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"
R"([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"
R"([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"
R"(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"
R"(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"
R"([a-z]\u30fb|\u30fb[a-z]|)"
R"([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339]|)"
R"([ijl\u0131]\u0307)",
-1, US_INV),
0, status);
tls_index.Set(dangerous_pattern);
}
dangerous_pattern->reset(label_string);
return !dangerous_pattern->find();
}
| 172,936 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cypress_generic_port_probe(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct cypress_private *priv;
priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->comm_is_ok = !0;
spin_lock_init(&priv->lock);
if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) {
kfree(priv);
return -ENOMEM;
}
/* Skip reset for FRWD device. It is a workaound:
device hangs if it receives SET_CONFIGURE in Configured
state. */
if (!is_frwd(serial->dev))
usb_reset_configuration(serial->dev);
priv->cmd_ctrl = 0;
priv->line_control = 0;
priv->termios_initialized = 0;
priv->rx_flags = 0;
/* Default packet format setting is determined by packet size.
Anything with a size larger then 9 must have a separate
count field since the 3 bit count field is otherwise too
small. Otherwise we can use the slightly more compact
format. This is in accordance with the cypress_m8 serial
converter app note. */
if (port->interrupt_out_size > 9)
priv->pkt_fmt = packet_format_1;
else
priv->pkt_fmt = packet_format_2;
if (interval > 0) {
priv->write_urb_interval = interval;
priv->read_urb_interval = interval;
dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n",
__func__, interval);
} else {
priv->write_urb_interval = port->interrupt_out_urb->interval;
priv->read_urb_interval = port->interrupt_in_urb->interval;
dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n",
__func__, priv->read_urb_interval,
priv->write_urb_interval);
}
usb_set_serial_port_data(port, priv);
port->port.drain_delay = 256;
return 0;
}
Commit Message: USB: cypress_m8: add endpoint sanity check
An attack using missing endpoints exists.
CVE-2016-3137
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
Signed-off-by: Johan Hovold <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static int cypress_generic_port_probe(struct usb_serial_port *port)
{
struct usb_serial *serial = port->serial;
struct cypress_private *priv;
if (!port->interrupt_out_urb || !port->interrupt_in_urb) {
dev_err(&port->dev, "required endpoint is missing\n");
return -ENODEV;
}
priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->comm_is_ok = !0;
spin_lock_init(&priv->lock);
if (kfifo_alloc(&priv->write_fifo, CYPRESS_BUF_SIZE, GFP_KERNEL)) {
kfree(priv);
return -ENOMEM;
}
/* Skip reset for FRWD device. It is a workaound:
device hangs if it receives SET_CONFIGURE in Configured
state. */
if (!is_frwd(serial->dev))
usb_reset_configuration(serial->dev);
priv->cmd_ctrl = 0;
priv->line_control = 0;
priv->termios_initialized = 0;
priv->rx_flags = 0;
/* Default packet format setting is determined by packet size.
Anything with a size larger then 9 must have a separate
count field since the 3 bit count field is otherwise too
small. Otherwise we can use the slightly more compact
format. This is in accordance with the cypress_m8 serial
converter app note. */
if (port->interrupt_out_size > 9)
priv->pkt_fmt = packet_format_1;
else
priv->pkt_fmt = packet_format_2;
if (interval > 0) {
priv->write_urb_interval = interval;
priv->read_urb_interval = interval;
dev_dbg(&port->dev, "%s - read & write intervals forced to %d\n",
__func__, interval);
} else {
priv->write_urb_interval = port->interrupt_out_urb->interval;
priv->read_urb_interval = port->interrupt_in_urb->interval;
dev_dbg(&port->dev, "%s - intervals: read=%d write=%d\n",
__func__, priv->read_urb_interval,
priv->write_urb_interval);
}
usb_set_serial_port_data(port, priv);
port->port.drain_delay = 256;
return 0;
}
| 167,359 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void SetUpTestCase() {
source_data_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kDataBlockSize));
reference_data_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kDataBufferSize));
}
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 | static void SetUpTestCase() {
source_data8_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kDataBlockSize));
reference_data8_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, kDataBufferSize));
second_pred8_ = reinterpret_cast<uint8_t*>(
vpx_memalign(kDataAlignment, 64*64));
source_data16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, kDataBlockSize*sizeof(uint16_t)));
reference_data16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, kDataBufferSize*sizeof(uint16_t)));
second_pred16_ = reinterpret_cast<uint16_t*>(
vpx_memalign(kDataAlignment, 64*64*sizeof(uint16_t)));
}
| 174,578 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ChromeMockRenderThread::OnCheckForCancel(
const std::string& preview_ui_addr,
int preview_request_id,
bool* cancel) {
*cancel =
(print_preview_pages_remaining_ == print_preview_cancel_page_number_);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | void ChromeMockRenderThread::OnCheckForCancel(
void ChromeMockRenderThread::OnCheckForCancel(int32 preview_ui_id,
int preview_request_id,
bool* cancel) {
*cancel =
(print_preview_pages_remaining_ == print_preview_cancel_page_number_);
}
| 170,847 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_akcipher rakcipher;
strlcpy(rakcipher.type, "akcipher", sizeof(rakcipher.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER,
sizeof(struct crypto_report_akcipher), &rakcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_akcipher rakcipher;
strncpy(rakcipher.type, "akcipher", sizeof(rakcipher.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER,
sizeof(struct crypto_report_akcipher), &rakcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 168,964 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = (r->glyph_data.bits.size - r->pos < n ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
Commit Message:
CWE ID: CWE-125 | static void gx_ttfReader__Read(ttfReader *self, void *p, int n)
{
gx_ttfReader *r = (gx_ttfReader *)self;
const byte *q;
if (!r->error) {
if (r->extra_glyph_index != -1) {
q = r->glyph_data.bits.data + r->pos;
r->error = ((r->pos >= r->glyph_data.bits.size ||
r->glyph_data.bits.size - r->pos < n) ?
gs_note_error(gs_error_invalidfont) : 0);
if (r->error == 0)
memcpy(p, q, n);
unsigned int cnt;
for (cnt = 0; cnt < (uint)n; cnt += r->error) {
r->error = r->pfont->data.string_proc(r->pfont, (ulong)r->pos + cnt, (ulong)n - cnt, &q);
if (r->error < 0)
break;
else if ( r->error == 0) {
memcpy((char *)p + cnt, q, n - cnt);
break;
} else {
memcpy((char *)p + cnt, q, r->error);
}
}
}
}
if (r->error) {
memset(p, 0, n);
return;
}
r->pos += n;
}
| 164,779 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void numtostr(js_State *J, const char *fmt, int w, double n)
{
char buf[32], *e;
sprintf(buf, fmt, w, n);
e = strchr(buf, 'e');
if (e) {
int exp = atoi(e+1);
sprintf(e, "e%+d", exp);
}
js_pushstring(J, buf);
}
Commit Message: Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed().
32 is not enough to fit sprintf("%.20f", 1e20).
We need at least 43 bytes to fit that format.
Bump the static buffer size.
CWE ID: CWE-119 | static void numtostr(js_State *J, const char *fmt, int w, double n)
{
/* buf needs to fit printf("%.20f", 1e20) */
char buf[50], *e;
sprintf(buf, fmt, w, n);
e = strchr(buf, 'e');
if (e) {
int exp = atoi(e+1);
sprintf(e, "e%+d", exp);
}
js_pushstring(J, buf);
}
| 169,704 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: mark_trusted_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
Commit Message: mime-actions: use file metadata for trusting desktop files
Currently we only trust desktop files that have the executable bit
set, and don't replace the displayed icon or the displayed name until
it's trusted, which prevents for running random programs by a malicious
desktop file.
However, the executable permission is preserved if the desktop file
comes from a compressed file.
To prevent this, add a metadata::trusted metadata to the file once the
user acknowledges the file as trusted. This adds metadata to the file,
which cannot be added unless it has access to the computer.
Also remove the SHEBANG "trusted" content we were putting inside the
desktop file, since that doesn't add more security since it can come
with the file itself.
https://bugzilla.gnome.org/show_bug.cgi?id=777991
CWE ID: CWE-20 | mark_trusted_task_done (GObject *source_object,
mark_desktop_file_executable_task_done (GObject *source_object,
GAsyncResult *res,
gpointer user_data)
{
MarkTrustedJob *job = user_data;
g_object_unref (job->file);
if (job->done_callback)
{
job->done_callback (!job_aborted ((CommonJob *) job),
job->done_callback_data);
}
finalize_common ((CommonJob *) job);
}
| 167,749 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int uinput_create(char *name)
{
struct uinput_dev dev;
int fd, x = 0;
for(x=0; x < MAX_UINPUT_PATHS; x++)
{
fd = open(uinput_dev_path[x], O_RDWR);
if (fd < 0)
continue;
break;
}
if (x == MAX_UINPUT_PATHS) {
BTIF_TRACE_ERROR("%s ERROR: uinput device open failed", __FUNCTION__);
return -1;
}
memset(&dev, 0, sizeof(dev));
if (name)
strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE-1);
dev.id.bustype = BUS_BLUETOOTH;
dev.id.vendor = 0x0000;
dev.id.product = 0x0000;
dev.id.version = 0x0000;
if (write(fd, &dev, sizeof(dev)) < 0) {
BTIF_TRACE_ERROR("%s Unable to write device information", __FUNCTION__);
close(fd);
return -1;
}
ioctl(fd, UI_SET_EVBIT, EV_KEY);
ioctl(fd, UI_SET_EVBIT, EV_REL);
ioctl(fd, UI_SET_EVBIT, EV_SYN);
for (x = 0; key_map[x].name != NULL; x++)
ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id);
if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) {
BTIF_TRACE_ERROR("%s Unable to create uinput device", __FUNCTION__);
close(fd);
return -1;
}
return fd;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | int uinput_create(char *name)
{
struct uinput_dev dev;
int fd, x = 0;
for(x=0; x < MAX_UINPUT_PATHS; x++)
{
fd = TEMP_FAILURE_RETRY(open(uinput_dev_path[x], O_RDWR));
if (fd < 0)
continue;
break;
}
if (x == MAX_UINPUT_PATHS) {
BTIF_TRACE_ERROR("%s ERROR: uinput device open failed", __FUNCTION__);
return -1;
}
memset(&dev, 0, sizeof(dev));
if (name)
strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE-1);
dev.id.bustype = BUS_BLUETOOTH;
dev.id.vendor = 0x0000;
dev.id.product = 0x0000;
dev.id.version = 0x0000;
if (TEMP_FAILURE_RETRY(write(fd, &dev, sizeof(dev))) < 0) {
BTIF_TRACE_ERROR("%s Unable to write device information", __FUNCTION__);
close(fd);
return -1;
}
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_KEY));
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_REL));
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_SYN));
for (x = 0; key_map[x].name != NULL; x++)
TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id));
if (TEMP_FAILURE_RETRY(ioctl(fd, UI_DEV_CREATE, NULL)) < 0) {
BTIF_TRACE_ERROR("%s Unable to create uinput device", __FUNCTION__);
close(fd);
return -1;
}
return fd;
}
| 173,452 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_err("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
Commit Message: netfilter: x_tables: fix unconditional helper
Ben Hawkes says:
In the mark_source_chains function (net/ipv4/netfilter/ip_tables.c) it
is possible for a user-supplied ipt_entry structure to have a large
next_offset field. This field is not bounds checked prior to writing a
counter value at the supplied offset.
Problem is that mark_source_chains should not have been called --
the rule doesn't have a next entry, so its supposed to return
an absolute verdict of either ACCEPT or DROP.
However, the function conditional() doesn't work as the name implies.
It only checks that the rule is using wildcard address matching.
However, an unconditional rule must also not be using any matches
(no -m args).
The underflow validator only checked the addresses, therefore
passing the 'unconditional absolute verdict' test, while
mark_source_chains also tested for presence of matches, and thus
proceeeded to the next (not-existent) rule.
Unify this so that all the callers have same idea of 'unconditional rule'.
Reported-by: Ben Hawkes <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Pablo Neira Ayuso <[email protected]>
CWE ID: CWE-119 | check_entry_size_and_hooks(struct ipt_entry *e,
struct xt_table_info *newinfo,
const unsigned char *base,
const unsigned char *limit,
const unsigned int *hook_entries,
const unsigned int *underflows,
unsigned int valid_hooks)
{
unsigned int h;
int err;
if ((unsigned long)e % __alignof__(struct ipt_entry) != 0 ||
(unsigned char *)e + sizeof(struct ipt_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ipt_entry) + sizeof(struct xt_entry_target)) {
duprintf("checking: element %p size %u\n",
e, e->next_offset);
return -EINVAL;
}
err = check_entry(e);
if (err)
return err;
/* Check hooks & underflows */
for (h = 0; h < NF_INET_NUMHOOKS; h++) {
if (!(valid_hooks & (1 << h)))
continue;
if ((unsigned char *)e - base == hook_entries[h])
newinfo->hook_entry[h] = hook_entries[h];
if ((unsigned char *)e - base == underflows[h]) {
if (!check_underflow(e)) {
pr_debug("Underflows must be unconditional and "
"use the STANDARD target with "
"ACCEPT/DROP\n");
return -EINVAL;
}
newinfo->underflow[h] = underflows[h];
}
}
/* Clear counters and comefrom */
e->counters = ((struct xt_counters) { 0, 0 });
e->comefrom = 0;
return 0;
}
| 167,367 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::Load(long long& pos, long& len) const
{
assert(m_pSegment);
assert(m_pos >= m_element_start);
if (m_timecode >= 0) //at least partially loaded
return 0;
assert(m_pos == m_element_start);
assert(m_element_size < 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
const int status = pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
assert((total < 0) || (m_pos <= total)); //TODO: verify this
pos = m_pos;
long long cluster_size = -1;
{
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error or underflow
return static_cast<long>(result);
if (result > 0) //underflow (weird)
return E_BUFFER_NOT_FULL;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id_ = ReadUInt(pReader, pos, len);
if (id_ < 0) //error
return static_cast<long>(id_);
if (id_ != 0x0F43B675) //Cluster ID
return E_FILE_FORMAT_INVALID;
pos += len; //consume id
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(cluster_size);
if (size == 0)
return E_FILE_FORMAT_INVALID; //TODO: verify this
pos += len; //consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size != unknown_size)
cluster_size = size;
}
//// pos points to start of payload
#if 0
len = static_cast<long>(size_);
if (cluster_stop > avail)
return E_BUFFER_NOT_FULL;
#endif
long long timecode = -1;
long long new_pos = -1;
bool bBlock = false;
long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size;
for (;;)
{
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return static_cast<long>(id);
if (id == 0)
return E_FILE_FORMAT_INVALID;
if (id == 0x0F43B675) //Cluster ID
break;
if (id == 0x0C53BB6B) //Cues ID
break;
pos += len; //consume ID field
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; //consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) //weird
continue;
if ((cluster_stop >= 0) && ((pos + size) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (id == 0x67) //TimeCode ID
{
len = static_cast<long>(size);
if ((pos + size) > avail)
return E_BUFFER_NOT_FULL;
timecode = UnserializeUInt(pReader, pos, size);
if (timecode < 0) //error (or underflow)
return static_cast<long>(timecode);
new_pos = pos + size;
if (bBlock)
break;
}
else if (id == 0x20) //BlockGroup ID
{
bBlock = true;
break;
}
else if (id == 0x23) //SimpleBlock ID
{
bBlock = true;
break;
}
pos += size; //consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert((cluster_stop < 0) || (pos <= cluster_stop));
if (timecode < 0) //no timecode found
return E_FILE_FORMAT_INVALID;
if (!bBlock)
return E_FILE_FORMAT_INVALID;
m_pos = new_pos; //designates position just beyond timecode payload
m_timecode = timecode; // m_timecode >= 0 means we're partially loaded
if (cluster_size >= 0)
m_element_size = cluster_stop - m_element_start;
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 Cluster::Load(long long& pos, long& len) const
if (m_timecode >= 0) // at least partially loaded
return 0;
assert(m_pos == m_element_start);
assert(m_element_size < 0);
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
const int status = pReader->Length(&total, &avail);
if (status < 0) // error
return status;
assert((total < 0) || (avail <= total));
assert((total < 0) || (m_pos <= total)); // TODO: verify this
pos = m_pos;
long long cluster_size = -1;
{
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) // error or underflow
return static_cast<long>(result);
if (result > 0) // underflow (weird)
return E_BUFFER_NOT_FULL;
// if ((pos + len) > segment_stop)
// return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id_ = ReadUInt(pReader, pos, len);
if (id_ < 0) // error
return static_cast<long>(id_);
if (id_ != 0x0F43B675) // Cluster ID
return E_FILE_FORMAT_INVALID;
pos += len; // consume id
// read cluster size
if ((pos + 1) > avail) {
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) // error
return static_cast<long>(result);
if (result > 0) // weird
return E_BUFFER_NOT_FULL;
// if ((pos + len) > segment_stop)
// return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) // error
return static_cast<long>(cluster_size);
if (size == 0)
return E_FILE_FORMAT_INVALID; // TODO: verify this
pos += len; // consume length of size of element
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size != unknown_size)
cluster_size = size;
}
//// pos points to start of payload
#if 0
len = static_cast<long>(size_);
if (cluster_stop > avail)
return E_BUFFER_NOT_FULL;
#endif
long long timecode = -1;
long long new_pos = -1;
bool bBlock = false;
long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size;
for (;;) {
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
// Parse ID
| 174,393 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UrlData::set_has_opaque_data(bool has_opaque_data) {
if (has_opaque_data_)
return;
has_opaque_data_ = has_opaque_data;
}
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 UrlData::set_has_opaque_data(bool has_opaque_data) {
void UrlData::set_is_cors_cross_origin(bool is_cors_cross_origin) {
if (is_cors_cross_origin_)
return;
is_cors_cross_origin_ = is_cors_cross_origin;
}
| 172,629 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const CuePoint* Cues::GetLast() const
{
if (m_cue_points == NULL)
return NULL;
if (m_count <= 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
const size_t index = count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
pCP->Load(m_pSegment->m_pReader);
assert(pCP->GetTimeCode() >= 0);
#else
const long index = m_count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
#endif
return pCP;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const CuePoint* Cues::GetLast() const
if (m_count <= 0)
return NULL;
#if 0
LoadCuePoint(); //init cues
const size_t count = m_count + m_preload_count;
if (count == 0) //weird
return NULL;
const size_t index = count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
pCP->Load(m_pSegment->m_pReader);
assert(pCP->GetTimeCode() >= 0);
#else
const long index = m_count - 1;
CuePoint* const* const pp = m_cue_points;
assert(pp);
CuePoint* const pCP = pp[index];
assert(pCP);
assert(pCP->GetTimeCode() >= 0);
#endif
return pCP;
}
| 174,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags)
{
char *norm_path_old;
char *norm_path_new;
char *join_path_old;
char *join_path_new;
M_fs_dir_entries_t *entries;
const M_fs_dir_entry_t *entry;
M_fs_info_t *info;
M_fs_progress_t *progress = NULL;
M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE;
M_fs_type_t type;
size_t len;
size_t i;
M_uint64 total_count = 0;
M_uint64 total_size = 0;
M_uint64 total_size_progress = 0;
M_uint64 entry_size;
M_fs_error_t res;
if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') {
return M_FS_ERROR_INVALID;
}
/* It's okay if new path doesn't exist. */
res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
return res;
}
/* If a path is a file and the destination is a directory the file should be copied
* into the directory. E.g. /file.txt -> /dir = /dir/file.txt */
if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) {
M_free(norm_path_new);
res = M_fs_copy(path_old, norm_path_old, mode, cb, progress_flags);
M_free(norm_path_old);
return res;
}
/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path
* existing to rename because any check we perform may not be true when rename is called. */
res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
progress = M_fs_progress_create();
res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
type = M_fs_info_get_type(info);
/* There is a race condition where the path could not exist but be created between the exists check and calling
* rename to move the file but there isn't much we can do in this case. copy will delete and the file so this
* situation won't cause an error. */
if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return M_FS_ERROR_FILE_EXISTS;
}
entries = M_fs_dir_entries_create();
/* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed.
* M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is
* stored in the entry. */
M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC));
if (type == M_FS_TYPE_DIR) {
if (mode & M_FS_FILE_MODE_PRESERVE_PERMS) {
filter |= M_FS_DIR_WALK_FILTER_READ_INFO_FULL;
} else if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) {
filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC;
}
/* Get all the files under the dir. */
M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path_old, NULL, filter));
}
/* Put all dirs first. We need to ensure the dir(s) exist before we can copy files. */
M_fs_dir_entries_sort(entries, M_FS_DIR_SORT_ISDIR, M_TRUE, M_FS_DIR_SORT_NAME_CASECMP, M_TRUE);
len = M_fs_dir_entries_len(entries);
if (cb) {
total_size = 0;
for (i=0; i<len; i++) {
entry = M_fs_dir_entries_at(entries, i);
entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry));
total_size += entry_size;
type = M_fs_dir_entry_get_type(entry);
/* The total isn't the total number of files but the total number of operations.
* Making dirs and symlinks is one operation and copying a file will be split into
* multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in
* chunks. We determine how many chunks will be needed to read the entire file and
* use that for the number of operations for the file. */
if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) {
total_count++;
} else {
total_count += (entry_size + M_FS_BUF_SIZE - 1) / M_FS_BUF_SIZE;
}
}
/* Change the progress total size to reflect all entries. */
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total(progress, total_size);
}
/* Change the progress count to reflect the count. */
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count_total(progress, total_count);
}
}
for (i=0; i<len; i++) {
entry = M_fs_dir_entries_at(entries, i);
type = M_fs_dir_entry_get_type(entry);
join_path_old = M_fs_path_join(norm_path_old, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO);
join_path_new = M_fs_path_join(norm_path_new, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO);
entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry));
total_size_progress += entry_size;
if (cb) {
M_fs_progress_set_path(progress, join_path_new);
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current(progress, entry_size);
}
}
/* op */
if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) {
if (type == M_FS_TYPE_DIR) {
res = M_fs_dir_mkdir(join_path_new, M_FALSE, NULL);
} else if (type == M_FS_TYPE_SYMLINK) {
res = M_fs_symlink(join_path_new, M_fs_dir_entry_get_resolved_name(entry));
}
if (res == M_FS_ERROR_SUCCESS && (mode & M_FS_FILE_MODE_PRESERVE_PERMS)) {
res = M_fs_perms_set_perms(M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)), join_path_new);
}
} else {
res = M_fs_copy_file(join_path_old, join_path_new, mode, cb, progress_flags, progress, M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)));
}
M_free(join_path_old);
M_free(join_path_new);
/* Call the callback and stop processing if requested. */
if ((type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) && cb) {
M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry));
M_fs_progress_set_result(progress, res);
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total_progess(progress, total_size_progress);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current_progress(progress, entry_size);
}
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1);
}
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
/* Delete the file(s) if it could not be copied properly, but only if we are not overwriting.
* If we're overwriting then there could be other files in that location (especially if it's a dir). */
if (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) {
M_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);
}
M_fs_dir_entries_destroy(entries);
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data.
CWE ID: CWE-732 | M_fs_error_t M_fs_copy(const char *path_old, const char *path_new, M_uint32 mode, M_fs_progress_cb_t cb, M_uint32 progress_flags)
{
char *norm_path_old;
char *norm_path_new;
char *join_path_old;
char *join_path_new;
M_fs_dir_entries_t *entries;
const M_fs_dir_entry_t *entry;
M_fs_info_t *info;
M_fs_progress_t *progress = NULL;
M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE;
M_fs_type_t type;
size_t len;
size_t i;
M_uint64 total_count = 0;
M_uint64 total_size = 0;
M_uint64 total_size_progress = 0;
M_uint64 entry_size;
M_fs_error_t res;
if (path_old == NULL || *path_old == '\0' || path_new == NULL || *path_new == '\0') {
return M_FS_ERROR_INVALID;
}
/* It's okay if new path doesn't exist. */
res = M_fs_path_norm(&norm_path_new, path_new, M_FS_PATH_NORM_RESDIR, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
return res;
}
/* If a path is a file and the destination is a directory the file should be copied
* into the directory. E.g. /file.txt -> /dir = /dir/file.txt */
if (M_fs_isfileintodir(path_old, path_new, &norm_path_old)) {
M_free(norm_path_new);
res = M_fs_copy(path_old, norm_path_old, mode, cb, progress_flags);
M_free(norm_path_old);
return res;
}
/* Normalize the old path and do basic checks that it exists. We'll leave really checking that the old path
* existing to rename because any check we perform may not be true when rename is called. */
res = M_fs_path_norm(&norm_path_old, path_old, M_FS_PATH_NORM_RESALL, M_FS_SYSTEM_AUTO);
if (res != M_FS_ERROR_SUCCESS) {
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
progress = M_fs_progress_create();
res = M_fs_info(&info, path_old, (mode & M_FS_FILE_MODE_PRESERVE_PERMS)?M_FS_PATH_INFO_FLAGS_NONE:M_FS_PATH_INFO_FLAGS_BASIC);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
type = M_fs_info_get_type(info);
/* There is a race condition where the path could not exist but be created between the exists check and calling
* rename to move the file but there isn't much we can do in this case. copy will delete and the file so this
* situation won't cause an error. */
if (!M_fs_check_overwrite_allowed(norm_path_old, norm_path_new, mode)) {
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return M_FS_ERROR_FILE_EXISTS;
}
entries = M_fs_dir_entries_create();
/* No need to destroy info because it's now owned by entries and will be destroyed when entries is destroyed.
* M_FS_DIR_WALK_FILTER_READ_INFO_BASIC doesn't actually get the perms it's just there to ensure the info is
* stored in the entry. */
M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path_new, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC));
if (type == M_FS_TYPE_DIR) {
if (mode & M_FS_FILE_MODE_PRESERVE_PERMS) {
filter |= M_FS_DIR_WALK_FILTER_READ_INFO_FULL;
} else if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) {
filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC;
}
/* Get all the files under the dir. */
M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path_old, NULL, filter));
}
/* Put all dirs first. We need to ensure the dir(s) exist before we can copy files. */
M_fs_dir_entries_sort(entries, M_FS_DIR_SORT_ISDIR, M_TRUE, M_FS_DIR_SORT_NAME_CASECMP, M_TRUE);
len = M_fs_dir_entries_len(entries);
if (cb) {
total_size = 0;
for (i=0; i<len; i++) {
entry = M_fs_dir_entries_at(entries, i);
entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry));
total_size += entry_size;
type = M_fs_dir_entry_get_type(entry);
/* The total isn't the total number of files but the total number of operations.
* Making dirs and symlinks is one operation and copying a file will be split into
* multiple operations. Copying uses the M_FS_BUF_SIZE to read and write in
* chunks. We determine how many chunks will be needed to read the entire file and
* use that for the number of operations for the file. */
if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) {
total_count++;
} else {
total_count += (entry_size + M_FS_BUF_SIZE - 1) / M_FS_BUF_SIZE;
}
}
/* Change the progress total size to reflect all entries. */
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total(progress, total_size);
}
/* Change the progress count to reflect the count. */
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count_total(progress, total_count);
}
}
for (i=0; i<len; i++) {
entry = M_fs_dir_entries_at(entries, i);
type = M_fs_dir_entry_get_type(entry);
join_path_old = M_fs_path_join(norm_path_old, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO);
join_path_new = M_fs_path_join(norm_path_new, M_fs_dir_entry_get_name(entry), M_FS_SYSTEM_AUTO);
entry_size = M_fs_info_get_size(M_fs_dir_entry_get_info(entry));
total_size_progress += entry_size;
if (cb) {
M_fs_progress_set_path(progress, join_path_new);
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current(progress, entry_size);
}
}
/* op */
if (type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) {
if (type == M_FS_TYPE_DIR) {
res = M_fs_dir_mkdir(join_path_new, M_FALSE, NULL);
} else if (type == M_FS_TYPE_SYMLINK) {
res = M_fs_symlink(join_path_new, M_fs_dir_entry_get_resolved_name(entry));
}
if (res == M_FS_ERROR_SUCCESS && (mode & M_FS_FILE_MODE_PRESERVE_PERMS)) {
res = M_fs_perms_set_perms(M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)), join_path_new);
}
} else {
res = M_fs_copy_file(join_path_old, join_path_new, mode, cb, progress_flags, progress, M_fs_info_get_perms(M_fs_dir_entry_get_info(entry)));
}
M_free(join_path_old);
M_free(join_path_new);
/* Call the callback and stop processing if requested. */
if ((type == M_FS_TYPE_DIR || type == M_FS_TYPE_SYMLINK) && cb) {
M_fs_progress_set_type(progress, M_fs_dir_entry_get_type(entry));
M_fs_progress_set_result(progress, res);
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total_progess(progress, total_size_progress);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current_progress(progress, entry_size);
}
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1);
}
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
/* Delete the file(s) if it could not be copied properly, but only if we are not overwriting.
* If we're overwriting then there could be other files in that location (especially if it's a dir). */
if (res != M_FS_ERROR_SUCCESS && !(mode & M_FS_FILE_MODE_OVERWRITE)) {
M_fs_delete(path_new, M_TRUE, NULL, M_FS_PROGRESS_NOEXTRA);
}
M_fs_dir_entries_destroy(entries);
M_fs_progress_destroy(progress);
M_free(norm_path_new);
M_free(norm_path_old);
return res;
}
| 169,141 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_, params.route_id, params.surface_id,
true, base::TimeTicks(), base::TimeDelta()));
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (!handle) {
TRACE_EVENT1("gpu", "SurfaceIDNotFound_RoutingToUI",
"surface_id", params.surface_id);
#if defined(USE_AURA)
scoped_completion_runner.Release();
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
#endif
return;
}
scoped_refptr<AcceleratedPresenter> presenter(
AcceleratedPresenter::GetForWindow(handle));
if (!presenter) {
TRACE_EVENT1("gpu", "EarlyOut_NativeWindowNotFound", "handle", handle);
return;
}
scoped_completion_runner.Release();
presenter->AsyncPresentAndAcknowledge(
params.size,
params.surface_handle,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_,
params.route_id,
params.surface_id));
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped(
const GpuHostMsg_AcceleratedSurfaceBuffersSwapped_Params& params) {
TRACE_EVENT0("gpu", "GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped");
base::ScopedClosureRunner scoped_completion_runner(
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_, params.route_id, params.surface_id, params.surface_handle,
true, base::TimeTicks(), base::TimeDelta()));
gfx::PluginWindowHandle handle =
GpuSurfaceTracker::Get()->GetSurfaceWindowHandle(params.surface_id);
if (!handle) {
TRACE_EVENT1("gpu", "SurfaceIDNotFound_RoutingToUI",
"surface_id", params.surface_id);
#if defined(USE_AURA)
scoped_completion_runner.Release();
RouteOnUIThread(GpuHostMsg_AcceleratedSurfaceBuffersSwapped(params));
#endif
return;
}
scoped_refptr<AcceleratedPresenter> presenter(
AcceleratedPresenter::GetForWindow(handle));
if (!presenter) {
TRACE_EVENT1("gpu", "EarlyOut_NativeWindowNotFound", "handle", handle);
return;
}
scoped_completion_runner.Release();
presenter->AsyncPresentAndAcknowledge(
params.size,
params.surface_handle,
base::Bind(&AcceleratedSurfaceBuffersSwappedCompleted,
host_id_,
params.route_id,
params.surface_id,
params.surface_handle));
}
| 171,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.i = new->peer.i;
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC);
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_ssnmap_clear(asoc->ssnmap);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports) {
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))
sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state);
}
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (!asoc->ssnmap) {
/* Move the ssnmap. */
asoc->ssnmap = new->ssnmap;
new->ssnmap = NULL;
}
if (!asoc->assoc_id) {
/* get a new association id since we don't have one
* yet.
*/
sctp_assoc_set_id(asoc, GFP_ATOMIC);
}
}
/* SCTP-AUTH: Save the peer parameters from the new associations
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
Commit Message: net: sctp: inherit auth_capable on INIT collisions
Jason reported an oops caused by SCTP on his ARM machine with
SCTP authentication enabled:
Internal error: Oops: 17 [#1] ARM
CPU: 0 PID: 104 Comm: sctp-test Not tainted 3.13.0-68744-g3632f30c9b20-dirty #1
task: c6eefa40 ti: c6f52000 task.ti: c6f52000
PC is at sctp_auth_calculate_hmac+0xc4/0x10c
LR is at sg_init_table+0x20/0x38
pc : [<c024bb80>] lr : [<c00f32dc>] psr: 40000013
sp : c6f538e8 ip : 00000000 fp : c6f53924
r10: c6f50d80 r9 : 00000000 r8 : 00010000
r7 : 00000000 r6 : c7be4000 r5 : 00000000 r4 : c6f56254
r3 : c00c8170 r2 : 00000001 r1 : 00000008 r0 : c6f1e660
Flags: nZcv IRQs on FIQs on Mode SVC_32 ISA ARM Segment user
Control: 0005397f Table: 06f28000 DAC: 00000015
Process sctp-test (pid: 104, stack limit = 0xc6f521c0)
Stack: (0xc6f538e8 to 0xc6f54000)
[...]
Backtrace:
[<c024babc>] (sctp_auth_calculate_hmac+0x0/0x10c) from [<c0249af8>] (sctp_packet_transmit+0x33c/0x5c8)
[<c02497bc>] (sctp_packet_transmit+0x0/0x5c8) from [<c023e96c>] (sctp_outq_flush+0x7fc/0x844)
[<c023e170>] (sctp_outq_flush+0x0/0x844) from [<c023ef78>] (sctp_outq_uncork+0x24/0x28)
[<c023ef54>] (sctp_outq_uncork+0x0/0x28) from [<c0234364>] (sctp_side_effects+0x1134/0x1220)
[<c0233230>] (sctp_side_effects+0x0/0x1220) from [<c02330b0>] (sctp_do_sm+0xac/0xd4)
[<c0233004>] (sctp_do_sm+0x0/0xd4) from [<c023675c>] (sctp_assoc_bh_rcv+0x118/0x160)
[<c0236644>] (sctp_assoc_bh_rcv+0x0/0x160) from [<c023d5bc>] (sctp_inq_push+0x6c/0x74)
[<c023d550>] (sctp_inq_push+0x0/0x74) from [<c024a6b0>] (sctp_rcv+0x7d8/0x888)
While we already had various kind of bugs in that area
ec0223ec48a9 ("net: sctp: fix sctp_sf_do_5_1D_ce to verify if
we/peer is AUTH capable") and b14878ccb7fa ("net: sctp: cache
auth_enable per endpoint"), this one is a bit of a different
kind.
Giving a bit more background on why SCTP authentication is
needed can be found in RFC4895:
SCTP uses 32-bit verification tags to protect itself against
blind attackers. These values are not changed during the
lifetime of an SCTP association.
Looking at new SCTP extensions, there is the need to have a
method of proving that an SCTP chunk(s) was really sent by
the original peer that started the association and not by a
malicious attacker.
To cause this bug, we're triggering an INIT collision between
peers; normal SCTP handshake where both sides intent to
authenticate packets contains RANDOM; CHUNKS; HMAC-ALGO
parameters that are being negotiated among peers:
---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ---------->
<------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] ---------
-------------------- COOKIE-ECHO -------------------->
<-------------------- COOKIE-ACK ---------------------
RFC4895 says that each endpoint therefore knows its own random
number and the peer's random number *after* the association
has been established. The local and peer's random number along
with the shared key are then part of the secret used for
calculating the HMAC in the AUTH chunk.
Now, in our scenario, we have 2 threads with 1 non-blocking
SEQ_PACKET socket each, setting up common shared SCTP_AUTH_KEY
and SCTP_AUTH_ACTIVE_KEY properly, and each of them calling
sctp_bindx(3), listen(2) and connect(2) against each other,
thus the handshake looks similar to this, e.g.:
---------- INIT[RANDOM; CHUNKS; HMAC-ALGO] ---------->
<------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] ---------
<--------- INIT[RANDOM; CHUNKS; HMAC-ALGO] -----------
-------- INIT-ACK[RANDOM; CHUNKS; HMAC-ALGO] -------->
...
Since such collisions can also happen with verification tags,
the RFC4895 for AUTH rather vaguely says under section 6.1:
In case of INIT collision, the rules governing the handling
of this Random Number follow the same pattern as those for
the Verification Tag, as explained in Section 5.2.4 of
RFC 2960 [5]. Therefore, each endpoint knows its own Random
Number and the peer's Random Number after the association
has been established.
In RFC2960, section 5.2.4, we're eventually hitting Action B:
B) In this case, both sides may be attempting to start an
association at about the same time but the peer endpoint
started its INIT after responding to the local endpoint's
INIT. Thus it may have picked a new Verification Tag not
being aware of the previous Tag it had sent this endpoint.
The endpoint should stay in or enter the ESTABLISHED
state but it MUST update its peer's Verification Tag from
the State Cookie, stop any init or cookie timers that may
running and send a COOKIE ACK.
In other words, the handling of the Random parameter is the
same as behavior for the Verification Tag as described in
Action B of section 5.2.4.
Looking at the code, we exactly hit the sctp_sf_do_dupcook_b()
case which triggers an SCTP_CMD_UPDATE_ASSOC command to the
side effect interpreter, and in fact it properly copies over
peer_{random, hmacs, chunks} parameters from the newly created
association to update the existing one.
Also, the old asoc_shared_key is being released and based on
the new params, sctp_auth_asoc_init_active_key() updated.
However, the issue observed in this case is that the previous
asoc->peer.auth_capable was 0, and has *not* been updated, so
that instead of creating a new secret, we're doing an early
return from the function sctp_auth_asoc_init_active_key()
leaving asoc->asoc_shared_key as NULL. However, we now have to
authenticate chunks from the updated chunk list (e.g. COOKIE-ACK).
That in fact causes the server side when responding with ...
<------------------ AUTH; COOKIE-ACK -----------------
... to trigger a NULL pointer dereference, since in
sctp_packet_transmit(), it discovers that an AUTH chunk is
being queued for xmit, and thus it calls sctp_auth_calculate_hmac().
Since the asoc->active_key_id is still inherited from the
endpoint, and the same as encoded into the chunk, it uses
asoc->asoc_shared_key, which is still NULL, as an asoc_key
and dereferences it in ...
crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len)
... causing an oops. All this happens because sctp_make_cookie_ack()
called with the *new* association has the peer.auth_capable=1
and therefore marks the chunk with auth=1 after checking
sctp_auth_send_cid(), but it is *actually* sent later on over
the then *updated* association's transport that didn't initialize
its shared key due to peer.auth_capable=0. Since control chunks
in that case are not sent by the temporary association which
are scheduled for deletion, they are issued for xmit via
SCTP_CMD_REPLY in the interpreter with the context of the
*updated* association. peer.auth_capable was 0 in the updated
association (which went from COOKIE_WAIT into ESTABLISHED state),
since all previous processing that performed sctp_process_init()
was being done on temporary associations, that we eventually
throw away each time.
The correct fix is to update to the new peer.auth_capable
value as well in the collision case via sctp_assoc_update(),
so that in case the collision migrated from 0 -> 1,
sctp_auth_asoc_init_active_key() can properly recalculate
the secret. This therefore fixes the observed server panic.
Fixes: 730fc3d05cd4 ("[SCTP]: Implete SCTP-AUTH parameter processing")
Reported-by: Jason Gunthorpe <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
Tested-by: Jason Gunthorpe <[email protected]>
Cc: Vlad Yasevich <[email protected]>
Acked-by: Vlad Yasevich <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | void sctp_assoc_update(struct sctp_association *asoc,
struct sctp_association *new)
{
struct sctp_transport *trans;
struct list_head *pos, *temp;
/* Copy in new parameters of peer. */
asoc->c = new->c;
asoc->peer.rwnd = new->peer.rwnd;
asoc->peer.sack_needed = new->peer.sack_needed;
asoc->peer.auth_capable = new->peer.auth_capable;
asoc->peer.i = new->peer.i;
sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
asoc->peer.i.initial_tsn, GFP_ATOMIC);
/* Remove any peer addresses not present in the new association. */
list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
trans = list_entry(pos, struct sctp_transport, transports);
if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {
sctp_assoc_rm_peer(asoc, trans);
continue;
}
if (asoc->state >= SCTP_STATE_ESTABLISHED)
sctp_transport_reset(trans);
}
/* If the case is A (association restart), use
* initial_tsn as next_tsn. If the case is B, use
* current next_tsn in case data sent to peer
* has been discarded and needs retransmission.
*/
if (asoc->state >= SCTP_STATE_ESTABLISHED) {
asoc->next_tsn = new->next_tsn;
asoc->ctsn_ack_point = new->ctsn_ack_point;
asoc->adv_peer_ack_point = new->adv_peer_ack_point;
/* Reinitialize SSN for both local streams
* and peer's streams.
*/
sctp_ssnmap_clear(asoc->ssnmap);
/* Flush the ULP reassembly and ordered queue.
* Any data there will now be stale and will
* cause problems.
*/
sctp_ulpq_flush(&asoc->ulpq);
/* reset the overall association error count so
* that the restarted association doesn't get torn
* down on the next retransmission timer.
*/
asoc->overall_error_count = 0;
} else {
/* Add any peer addresses from the new association. */
list_for_each_entry(trans, &new->peer.transport_addr_list,
transports) {
if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))
sctp_assoc_add_peer(asoc, &trans->ipaddr,
GFP_ATOMIC, trans->state);
}
asoc->ctsn_ack_point = asoc->next_tsn - 1;
asoc->adv_peer_ack_point = asoc->ctsn_ack_point;
if (!asoc->ssnmap) {
/* Move the ssnmap. */
asoc->ssnmap = new->ssnmap;
new->ssnmap = NULL;
}
if (!asoc->assoc_id) {
/* get a new association id since we don't have one
* yet.
*/
sctp_assoc_set_id(asoc, GFP_ATOMIC);
}
}
/* SCTP-AUTH: Save the peer parameters from the new associations
* and also move the association shared keys over
*/
kfree(asoc->peer.peer_random);
asoc->peer.peer_random = new->peer.peer_random;
new->peer.peer_random = NULL;
kfree(asoc->peer.peer_chunks);
asoc->peer.peer_chunks = new->peer.peer_chunks;
new->peer.peer_chunks = NULL;
kfree(asoc->peer.peer_hmacs);
asoc->peer.peer_hmacs = new->peer.peer_hmacs;
new->peer.peer_hmacs = NULL;
sctp_auth_key_put(asoc->asoc_shared_key);
sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);
}
| 166,284 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && (params.url.GetOrigin() != url_.GetOrigin())) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284 | void ExtensionViewGuest::DidNavigateMainFrame(
const content::LoadCommittedDetails& details,
const content::FrameNavigateParams& params) {
if (attached() && !url::IsSameOriginWith(params.url, url_)) {
bad_message::ReceivedBadMessage(web_contents()->GetRenderProcessHost(),
bad_message::EVG_BAD_ORIGIN);
}
}
| 172,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_palette_to_rgb_set(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_palette_to_rgb(pp);
this->next->set(this->next, that, pp, pi);
}
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_palette_to_rgb_set(PNG_CONST image_transform *this,
image_transform_png_set_palette_to_rgb_set(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
png_set_palette_to_rgb(pp);
this->next->set(this->next, that, pp, pi);
}
| 173,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_INTEGER:
case V_ASN1_NEG_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_NEG_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
Commit Message:
CWE ID: CWE-119 | int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case V_ASN1_OBJECT:
result = OBJ_cmp(a->value.object, b->value.object);
break;
case V_ASN1_BOOLEAN:
result = a->value.boolean - b->value.boolean;
break;
case V_ASN1_NULL:
result = 0; /* They do not have content. */
break;
case V_ASN1_INTEGER:
case V_ASN1_ENUMERATED:
case V_ASN1_BIT_STRING:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_OCTET_STRING:
case V_ASN1_SEQUENCE:
case V_ASN1_SET:
case V_ASN1_NUMERICSTRING:
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_VIDEOTEXSTRING:
case V_ASN1_IA5STRING:
case V_ASN1_UTCTIME:
case V_ASN1_GENERALIZEDTIME:
case V_ASN1_GRAPHICSTRING:
case V_ASN1_VISIBLESTRING:
case V_ASN1_GENERALSTRING:
case V_ASN1_UNIVERSALSTRING:
case V_ASN1_BMPSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_OTHER:
default:
result = ASN1_STRING_cmp((ASN1_STRING *)a->value.ptr,
(ASN1_STRING *)b->value.ptr);
break;
}
return result;
}
| 165,211 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplDoublyLinkedList, offsetSet)
{
zval *zindex, *value;
spl_dllist_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) {
return;
}
intern = Z_SPLDLLIST_P(getThis());
if (Z_TYPE_P(zindex) == IS_NULL) {
/* $obj[] = ... */
spl_ptr_llist_push(intern->llist, value);
} else {
/* $obj[$foo] = ... */
zend_long index;
spl_ptr_llist_element *element;
index = spl_offset_convert_to_long(zindex);
if (index < 0 || index >= intern->llist->count) {
zval_ptr_dtor(value);
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0);
return;
}
element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);
if (element != NULL) {
/* call dtor on the old element as in spl_ptr_llist_pop */
if (intern->llist->dtor) {
intern->llist->dtor(element);
}
/* the element is replaced, delref the old one as in
* SplDoublyLinkedList::pop() */
zval_ptr_dtor(&element->data);
ZVAL_COPY_VALUE(&element->data, value);
/* new element, call ctor as in spl_ptr_llist_push */
if (intern->llist->ctor) {
intern->llist->ctor(element);
}
} else {
zval_ptr_dtor(value);
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0);
return;
}
}
} /* }}} */
/* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)
Commit Message: Fix bug #71735: Double-free in SplDoublyLinkedList::offsetSet
CWE ID: CWE-415 | SPL_METHOD(SplDoublyLinkedList, offsetSet)
{
zval *zindex, *value;
spl_dllist_object *intern;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &zindex, &value) == FAILURE) {
return;
}
intern = Z_SPLDLLIST_P(getThis());
if (Z_TYPE_P(zindex) == IS_NULL) {
/* $obj[] = ... */
spl_ptr_llist_push(intern->llist, value);
} else {
/* $obj[$foo] = ... */
zend_long index;
spl_ptr_llist_element *element;
index = spl_offset_convert_to_long(zindex);
if (index < 0 || index >= intern->llist->count) {
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid or out of range", 0);
return;
}
element = spl_ptr_llist_offset(intern->llist, index, intern->flags & SPL_DLLIST_IT_LIFO);
if (element != NULL) {
/* call dtor on the old element as in spl_ptr_llist_pop */
if (intern->llist->dtor) {
intern->llist->dtor(element);
}
/* the element is replaced, delref the old one as in
* SplDoublyLinkedList::pop() */
zval_ptr_dtor(&element->data);
ZVAL_COPY_VALUE(&element->data, value);
/* new element, call ctor as in spl_ptr_llist_push */
if (intern->llist->ctor) {
intern->llist->ctor(element);
}
} else {
zval_ptr_dtor(value);
zend_throw_exception(spl_ce_OutOfRangeException, "Offset invalid", 0);
return;
}
}
} /* }}} */
/* {{{ proto void SplDoublyLinkedList::offsetUnset(mixed index)
| 167,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXObject::isMultiline() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLTextAreaElement(*node))
return true;
if (hasEditableStyle(*node))
return true;
if (!isNativeTextControl() && !isNonNativeTextControl())
return false;
return equalIgnoringCase(getAttribute(aria_multilineAttr), "true");
}
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::isMultiline() const {
Node* node = this->getNode();
if (!node)
return false;
if (isHTMLTextAreaElement(*node))
return true;
if (hasEditableStyle(*node))
return true;
if (!isNativeTextControl() && !isNonNativeTextControl())
return false;
return equalIgnoringASCIICase(getAttribute(aria_multilineAttr), "true");
}
| 171,928 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderWidgetHostViewAura::CreateDelegatedFrameHostClient() {
if (IsMus())
return;
cc::FrameSinkId frame_sink_id =
host_->AllocateFrameSinkId(is_guest_view_hack_);
if (!delegated_frame_host_client_) {
delegated_frame_host_client_ =
base::MakeUnique<DelegatedFrameHostClientAura>(this);
}
delegated_frame_host_ = base::MakeUnique<DelegatedFrameHost>(
frame_sink_id, delegated_frame_host_client_.get());
if (renderer_compositor_frame_sink_) {
delegated_frame_host_->DidCreateNewRendererCompositorFrameSink(
renderer_compositor_frame_sink_);
}
UpdateNeedsBeginFramesInternal();
if (host_->delegate() && host_->delegate()->GetInputEventRouter()) {
host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
GetFrameSinkId(), this);
}
}
Commit Message: Allocate a FrameSinkId for RenderWidgetHostViewAura in mus+ash
RenderWidgetHostViewChildFrame expects its parent to have a valid
FrameSinkId. Make sure RenderWidgetHostViewAura has a FrameSinkId even
if DelegatedFrameHost is not used (in mus+ash).
BUG=706553
[email protected]
Review-Url: https://codereview.chromium.org/2847253003
Cr-Commit-Position: refs/heads/master@{#468179}
CWE ID: CWE-254 | void RenderWidgetHostViewAura::CreateDelegatedFrameHostClient() {
if (IsMus())
return;
if (!delegated_frame_host_client_) {
delegated_frame_host_client_ =
base::MakeUnique<DelegatedFrameHostClientAura>(this);
}
delegated_frame_host_ = base::MakeUnique<DelegatedFrameHost>(
frame_sink_id_, delegated_frame_host_client_.get());
if (renderer_compositor_frame_sink_) {
delegated_frame_host_->DidCreateNewRendererCompositorFrameSink(
renderer_compositor_frame_sink_);
}
UpdateNeedsBeginFramesInternal();
if (host_->delegate() && host_->delegate()->GetInputEventRouter()) {
host_->delegate()->GetInputEventRouter()->AddFrameSinkIdOwner(
GetFrameSinkId(), this);
}
}
| 172,233 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: cJSON *cJSON_GetObjectItem( cJSON *object, const char *string )
{
cJSON *c = object->child;
while ( c && cJSON_strcasecmp( c->string, string ) )
c = c->next;
return c;
}
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_GetObjectItem( cJSON *object, const char *string )
| 167,289 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int32_t PPB_Flash_MessageLoop_Impl::InternalRun(
const RunFromHostProxyCallback& callback) {
if (state_->run_called()) {
if (!callback.is_null())
callback.Run(PP_ERROR_FAILED);
return PP_ERROR_FAILED;
}
state_->set_run_called();
state_->set_run_callback(callback);
scoped_refptr<State> state_protector(state_);
{
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
base::MessageLoop::current()->Run();
}
return state_protector->result();
}
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 | int32_t PPB_Flash_MessageLoop_Impl::InternalRun(
const RunFromHostProxyCallback& callback) {
if (state_->run_called()) {
if (!callback.is_null())
callback.Run(PP_ERROR_FAILED);
return PP_ERROR_FAILED;
}
state_->set_run_called();
state_->set_run_callback(callback);
scoped_refptr<State> state_protector(state_);
{
base::MessageLoop::ScopedNestableTaskAllower allow(
base::MessageLoop::current());
blink::WebView::willEnterModalLoop();
base::MessageLoop::current()->Run();
blink::WebView::didExitModalLoop();
}
return state_protector->result();
}
| 172,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetupMockGroup() {
std::unique_ptr<net::HttpResponseInfo> info(MakeMockResponseInfo());
const int kMockInfoSize = GetResponseInfoSize(info.get());
scoped_refptr<AppCacheGroup> group(
new AppCacheGroup(service_->storage(), kManifestUrl, kMockGroupId));
scoped_refptr<AppCache> cache(
new AppCache(service_->storage(), kMockCacheId));
cache->AddEntry(
kManifestUrl,
AppCacheEntry(AppCacheEntry::MANIFEST, kMockResponseId,
kMockInfoSize + kMockBodySize));
cache->set_complete(true);
group->AddCache(cache.get());
mock_storage()->AddStoredGroup(group.get());
mock_storage()->AddStoredCache(cache.get());
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void SetupMockGroup() {
std::unique_ptr<net::HttpResponseInfo> info(MakeMockResponseInfo());
const int kMockInfoSize = GetResponseInfoSize(info.get());
scoped_refptr<AppCacheGroup> group(
new AppCacheGroup(service_->storage(), kManifestUrl, kMockGroupId));
scoped_refptr<AppCache> cache(
new AppCache(service_->storage(), kMockCacheId));
cache->AddEntry(
kManifestUrl,
AppCacheEntry(AppCacheEntry::MANIFEST, kMockResponseId,
kMockInfoSize + kMockBodySize, /*padding_size=*/0));
cache->set_complete(true);
group->AddCache(cache.get());
mock_storage()->AddStoredGroup(group.get());
mock_storage()->AddStoredCache(cache.get());
}
| 172,984 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand,
const char *option,const char *arg1n,const char *arg2n)
{
const char /* percent escaped versions of the args */
*arg1,
*arg2;
Image
*new_images;
MagickStatusType
status;
ssize_t
parse;
#define _image_info (cli_wand->wand.image_info)
#define _images (cli_wand->wand.images)
#define _exception (cli_wand->wand.exception)
#define _draw_info (cli_wand->draw_info)
#define _quantize_info (cli_wand->quantize_info)
#define _process_flags (cli_wand->process_flags)
#define _option_type ((CommandOptionFlags) cli_wand->command->flags)
#define IfNormalOp (*option=='-')
#define IfPlusOp (*option!='-')
#define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse
assert(cli_wand != (MagickCLI *) NULL);
assert(cli_wand->signature == MagickWandSignature);
assert(cli_wand->wand.signature == MagickWandSignature);
assert(_images != (Image *) NULL); /* _images must be present */
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- List Operator: %s \"%s\" \"%s\"", option,
arg1n == (const char *) NULL ? "null" : arg1n,
arg2n == (const char *) NULL ? "null" : arg2n);
arg1 = arg1n;
arg2 = arg2n;
/* Interpret Percent Escapes in Arguments - using first image */
if ( (((_process_flags & ProcessInterpretProperities) != 0 )
|| ((_option_type & AlwaysInterpretArgsFlag) != 0)
) && ((_option_type & NeverInterpretArgsFlag) == 0) ) {
/* Interpret Percent escapes in argument 1 */
if (arg1n != (char *) NULL) {
arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);
if (arg1 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg1=arg1n; /* use the given argument as is */
}
}
if (arg2n != (char *) NULL) {
arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);
if (arg2 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg2=arg2n; /* use the given argument as is */
}
}
}
#undef _process_flags
#undef _option_type
status=MagickTrue;
new_images=NewImageList();
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("append",option+1) == 0)
{
new_images=AppendImages(_images,IsNormalOp,_exception);
break;
}
if (LocaleCompare("average",option+1) == 0)
{
CLIWandWarnReplaced("-evaluate-sequence Mean");
(void) CLIListOperatorImages(cli_wand,"-evaluate-sequence","Mean",
NULL);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'c':
{
if (LocaleCompare("channel-fx",option+1) == 0)
{
new_images=ChannelFxImage(_images,arg1,_exception);
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image;
/* FUTURE - make this a compose option, and thus can be used
with layers compose or even compose last image over all other
_images.
*/
new_images=RemoveFirstImageFromList(&_images);
clut_image=RemoveLastImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (clut_image == (Image *) NULL)
break;
(void) ClutImage(new_images,clut_image,new_images->interpolate,
_exception);
clut_image=DestroyImage(clut_image);
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
new_images=CoalesceImages(_images,_exception);
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
parse=(ssize_t) _images->colorspace;
if (_images->number_channels < GetImageListLength(_images))
parse=sRGBColorspace;
if ( IfPlusOp )
parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedColorspace",option,
arg1);
new_images=CombineImages(_images,(ColorspaceType) parse,_exception);
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
double
distortion;
Image
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
image=RemoveFirstImageFromList(&_images);
reconstruct_image=RemoveFirstImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (reconstruct_image == (Image *) NULL)
break;
metric=UndefinedErrorMetric;
option=GetImageOption(_image_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
new_images=CompareImages(image,reconstruct_image,metric,&distortion,
_exception);
(void) distortion;
reconstruct_image=DestroyImage(reconstruct_image);
image=DestroyImage(image);
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator",
option,arg1);
new_images=ComplexImages(_images,(ComplexOperator) parse,_exception);
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
CompositeOperator
compose;
const char*
value;
MagickBooleanType
clip_to_self;
Image
*mask_image,
*source_image;
RectangleInfo
geometry;
/* Compose value from "-compose" option only */
value=GetImageOption(_image_info,"compose");
if (value == (const char *) NULL)
compose=OverCompositeOp; /* use Over not source_image->compose */
else
compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,
MagickFalse,value);
/* Get "clip-to-self" expert setting (false is normal) */
clip_to_self=GetCompositeClipToSelf(compose);
value=GetImageOption(_image_info,"compose:clip-to-self");
if (value != (const char *) NULL)
clip_to_self=IsStringTrue(value);
value=GetImageOption(_image_info,"compose:outside-overlay");
if (value != (const char *) NULL)
clip_to_self=IsStringFalse(value); /* deprecated */
new_images=RemoveFirstImageFromList(&_images);
source_image=RemoveFirstImageFromList(&_images);
if (source_image == (Image *) NULL)
break; /* FUTURE - produce Exception, rather than silent fail */
/* FUTURE - this should not be here! - should be part of -geometry */
if (source_image->geometry != (char *) NULL)
{
RectangleInfo
resize_geometry;
(void) ParseRegionGeometry(source_image,source_image->geometry,
&resize_geometry,_exception);
if ((source_image->columns != resize_geometry.width) ||
(source_image->rows != resize_geometry.height))
{
Image
*resize_image;
resize_image=ResizeImage(source_image,resize_geometry.width,
resize_geometry.height,source_image->filter,_exception);
if (resize_image != (Image *) NULL)
{
source_image=DestroyImage(source_image);
source_image=resize_image;
}
}
}
SetGeometry(source_image,&geometry);
(void) ParseAbsoluteGeometry(source_image->geometry,&geometry);
GravityAdjustGeometry(new_images->columns,new_images->rows,
new_images->gravity, &geometry);
mask_image=RemoveFirstImageFromList(&_images);
if (mask_image == (Image *) NULL)
status&=CompositeImage(new_images,source_image,compose,clip_to_self,
geometry.x,geometry.y,_exception);
else
{
if ((compose == DisplaceCompositeOp) ||
(compose == DistortCompositeOp))
{
status&=CompositeImage(source_image,mask_image,
CopyGreenCompositeOp,MagickTrue,0,0,_exception);
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,_exception);
}
else
{
Image
*clone_image;
clone_image=CloneImage(new_images,0,0,MagickTrue,_exception);
if (clone_image == (Image *) NULL)
break;
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,_exception);
status&=CompositeImage(new_images,mask_image,
CopyAlphaCompositeOp,MagickTrue,0,0,_exception);
status&=CompositeImage(clone_image,new_images,OverCompositeOp,
clip_to_self,0,0,_exception);
new_images=DestroyImage(new_images);
new_images=clone_image;
}
mask_image=DestroyImage(mask_image);
}
source_image=DestroyImage(source_image);
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
if (IsGeometry(arg2) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
(void) ParsePageGeometry(_images,arg2,&geometry,_exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=_images;
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,arg1,&geometry,_exception);
(void) CopyImagePixels(_images,source_image,&geometry,&offset,
_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
CLIWandWarnReplaced("-layer CompareAny");
(void) CLIListOperatorImages(cli_wand,"-layer","CompareAny",NULL);
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (IfNormalOp)
DeleteImages(&_images,arg1,_exception);
else
DeleteImages(&_images,"-1",_exception);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
if (IfNormalOp)
{
const char
*p;
size_t
number_duplicates;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,
arg1);
number_duplicates=(size_t) StringToLong(arg1);
p=strchr(arg1,',');
if (p == (const char *) NULL)
new_images=DuplicateImages(_images,number_duplicates,"-1",
_exception);
else
new_images=DuplicateImages(_images,number_duplicates,p,
_exception);
}
else
new_images=DuplicateImages(_images,1,"-1",_exception);
AppendImageToList(&_images, new_images);
new_images=(Image *) NULL;
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator",
option,arg1);
new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse,
_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
new_images=ForwardFourierTransformImage(_images,IsNormalOp,
_exception);
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
/* REDIRECTED to use -layers flatten instead */
(void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL);
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
new_images=FxImage(_images,arg1,_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
/* FUTURE - make this a compose option (and thus layers compose )
or perhaps compose last image over all other _images.
*/
Image
*hald_image;
new_images=RemoveFirstImageFromList(&_images);
hald_image=RemoveLastImageFromList(&_images);
if (hald_image == (Image *) NULL)
break;
(void) HaldClutImage(new_images,hald_image,_exception);
hald_image=DestroyImage(hald_image);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*magnitude_image,
*phase_image;
magnitude_image=RemoveFirstImageFromList(&_images);
phase_image=RemoveFirstImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (phase_image == (Image *) NULL)
break;
new_images=InverseFourierTransformImage(magnitude_image,phase_image,
IsNormalOp,_exception);
magnitude_image=DestroyImage(magnitude_image);
phase_image=DestroyImage(phase_image);
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*insert_image,
*index_image;
ssize_t
index;
if (IfNormalOp && (IsGeometry(arg1) == MagickFalse))
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
index=0;
insert_image=RemoveLastImageFromList(&_images);
if (IfNormalOp)
index=(ssize_t) StringToLong(arg1);
index_image=insert_image;
if (index == 0)
PrependImageToList(&_images,insert_image);
else if (index == (ssize_t) GetImageListLength(_images))
AppendImageToList(&_images,insert_image);
else
{
index_image=GetImageFromList(_images,index-1);
if (index_image == (Image *) NULL)
CLIWandExceptArgBreak(OptionError,"NoSuchImage",option,arg1);
InsertImageInList(&index_image,insert_image);
}
_images=GetFirstImageInList(index_image);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1);
if ( parse < 0 )
CLIWandExceptArgBreak(OptionError,"UnrecognizedLayerMethod",
option,arg1);
switch ((LayerMethod) parse)
{
case CoalesceLayer:
{
new_images=CoalesceImages(_images,_exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
new_images=CompareImagesLayers(_images,(LayerMethod) parse,
_exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
new_images=MergeImageLayers(_images,(LayerMethod) parse,
_exception);
break;
}
case DisposeLayer:
{
new_images=DisposeImages(_images,_exception);
break;
}
case OptimizeImageLayer:
{
new_images=OptimizeImageLayers(_images,_exception);
break;
}
case OptimizePlusLayer:
{
new_images=OptimizePlusImageLayers(_images,_exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(_images,_exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(&_images,_exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(&_images,_exception);
break;
}
case OptimizeLayer:
{ /* General Purpose, GIF Animation Optimizer. */
new_images=CoalesceImages(_images,_exception);
if (new_images == (Image *) NULL)
break;
_images=DestroyImageList(_images);
_images=OptimizeImageLayers(new_images,_exception);
if (_images == (Image *) NULL)
break;
new_images=DestroyImageList(new_images);
OptimizeImageTransparency(_images,_exception);
(void) RemapImages(_quantize_info,_images,(Image *) NULL,
_exception);
break;
}
case CompositeLayer:
{
Image
*source;
RectangleInfo
geometry;
CompositeOperator
compose;
const char*
value;
value=GetImageOption(_image_info,"compose");
compose=OverCompositeOp; /* Default to Over */
if (value != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,value);
/* Split image sequence at the first 'NULL:' image. */
source=_images;
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{ /* Separate the two lists, junk the null: image. */
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(_exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
break;
}
/* Adjust offset with gravity and virtual canvas. */
SetGeometry(_images,&geometry);
(void) ParseAbsoluteGeometry(_images->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry(_images->page.width != 0 ?
_images->page.width : _images->columns,
_images->page.height != 0 ? _images->page.height :
_images->rows,_images->gravity,&geometry);
/* Compose the two image sequences together */
CompositeLayers(_images,compose,source,geometry.x,geometry.y,
_exception);
source=DestroyImageList(source);
break;
}
}
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
CLIWandWarnReplaced("+remap");
(void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);
break;
}
if (LocaleCompare("metric",option+1) == 0)
{
(void) SetImageOption(_image_info,option+1,arg1);
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
morph_image=MorphImages(_images,StringToUnsignedLong(arg1),
_exception);
if (morph_image == (Image *) NULL)
break;
_images=DestroyImageList(_images);
_images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
/* REDIRECTED to use -layers mosaic instead */
(void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
double
*args;
ssize_t
count;
/* convert argument string into an array of doubles */
args = StringToArrayOfDoubles(arg1,&count,_exception);
if (args == (double *) NULL )
CLIWandExceptArgBreak(OptionError,"InvalidNumberList",option,arg1);
new_images=PolynomialImage(_images,(size_t) (count >> 1),args,
_exception);
args=(double *) RelinquishMagickMemory(args);
break;
}
if (LocaleCompare("process",option+1) == 0)
{
/* FUTURE: better parsing using ScriptToken() from string ??? */
char
**arguments;
int
j,
number_arguments;
arguments=StringToArgv(arg1,&number_arguments);
if (arguments == (char **) NULL)
break;
if (strchr(arguments[1],'=') != (char *) NULL)
{
char
breaker,
quote,
*token;
const char
*arguments;
int
next,
status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg1".
*/
assert(arg1 != (const char *) NULL);
length=strlen(arg1);
token=(char *) NULL;
if (~length >= (MagickPathExtent-1))
token=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
arguments=arg1;
token_info=AcquireTokenInfo();
status=Tokenizer(token_info,0,token,length,arguments,"","=",
"\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (status == 0)
{
const char
*argv;
argv=(&(arguments[next]));
(void) InvokeDynamicImageFilter(token,&_images,1,&argv,
_exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&_images,
number_arguments-2,(const char **) arguments+2,_exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'r':
{
if (LocaleCompare("remap",option+1) == 0)
{
(void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);
break;
}
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(&_images);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
/* FUTURE: this option needs more work to make better */
ssize_t
offset;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
offset=(ssize_t) StringToLong(arg1);
new_images=SmushImages(_images,IsNormalOp,offset,_exception);
break;
}
if (LocaleCompare("subimage",option+1) == 0)
{
Image
*base_image,
*compare_image;
const char
*value;
MetricType
metric;
double
similarity;
RectangleInfo
offset;
base_image=GetImageFromList(_images,0);
compare_image=GetImageFromList(_images,1);
/* Comparision Metric */
metric=UndefinedErrorMetric;
value=GetImageOption(_image_info,"metric");
if (value != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,value);
new_images=SimilarityImage(base_image,compare_image,metric,0.0,
&offset,&similarity,_exception);
if (new_images != (Image *) NULL)
{
char
result[MagickPathExtent];
(void) FormatLocaleString(result,MagickPathExtent,"%lf",
similarity);
(void) SetImageProperty(new_images,"subimage:similarity",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long)
offset.x);
(void) SetImageProperty(new_images,"subimage:x",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long)
offset.y);
(void) SetImageProperty(new_images,"subimage:y",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,
"%lux%lu%+ld%+ld",(unsigned long) offset.width,(unsigned long)
offset.height,(long) offset.x,(long) offset.y);
(void) SetImageProperty(new_images,"subimage:offset",result,
_exception);
}
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*swap;
ssize_t
index,
swap_index;
index=(-1);
swap_index=(-2);
if (IfNormalOp) {
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(arg1,&geometry_info);
if ((flags & RhoValue) == 0)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(_images,index);
q=GetImageFromList(_images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL)) {
if (IfNormalOp)
CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1)
else
CLIWandExceptionBreak(OptionError,"TwoOrMoreImagesRequired",option);
}
if (p == q)
CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1);
swap=CloneImage(p,0,0,MagickTrue,_exception);
if (swap == (Image *) NULL)
CLIWandExceptArgBreak(ResourceLimitError,"MemoryAllocationFailed",
option,GetExceptionMessage(errno));
ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception));
ReplaceImageInList(&q,swap);
_images=GetFirstImageInList(q);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
default:
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
/* clean up percent escape interpreted strings */
if (arg1 != arg1n )
arg1=DestroyString((char *)arg1);
if (arg2 != arg2n )
arg2=DestroyString((char *)arg2);
/* if new image list generated, replace existing image list */
if (new_images == (Image *) NULL)
return(status == 0 ? MagickFalse : MagickTrue);
_images=DestroyImageList(_images);
_images=GetFirstImageInList(new_images);
return(status == 0 ? MagickFalse : MagickTrue);
#undef _image_info
#undef _images
#undef _exception
#undef _draw_info
#undef _quantize_info
#undef IfNormalOp
#undef IfPlusOp
#undef IsNormalOp
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1604
CWE ID: CWE-399 | WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand,
const char *option,const char *arg1n,const char *arg2n)
{
const char /* percent escaped versions of the args */
*arg1,
*arg2;
Image
*new_images;
MagickStatusType
status;
ssize_t
parse;
#define _image_info (cli_wand->wand.image_info)
#define _images (cli_wand->wand.images)
#define _exception (cli_wand->wand.exception)
#define _draw_info (cli_wand->draw_info)
#define _quantize_info (cli_wand->quantize_info)
#define _process_flags (cli_wand->process_flags)
#define _option_type ((CommandOptionFlags) cli_wand->command->flags)
#define IfNormalOp (*option=='-')
#define IfPlusOp (*option!='-')
#define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse
assert(cli_wand != (MagickCLI *) NULL);
assert(cli_wand->signature == MagickWandSignature);
assert(cli_wand->wand.signature == MagickWandSignature);
assert(_images != (Image *) NULL); /* _images must be present */
if (cli_wand->wand.debug != MagickFalse)
(void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
"- List Operator: %s \"%s\" \"%s\"", option,
arg1n == (const char *) NULL ? "null" : arg1n,
arg2n == (const char *) NULL ? "null" : arg2n);
arg1 = arg1n;
arg2 = arg2n;
/* Interpret Percent Escapes in Arguments - using first image */
if ( (((_process_flags & ProcessInterpretProperities) != 0 )
|| ((_option_type & AlwaysInterpretArgsFlag) != 0)
) && ((_option_type & NeverInterpretArgsFlag) == 0) ) {
/* Interpret Percent escapes in argument 1 */
if (arg1n != (char *) NULL) {
arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception);
if (arg1 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg1=arg1n; /* use the given argument as is */
}
}
if (arg2n != (char *) NULL) {
arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception);
if (arg2 == (char *) NULL) {
CLIWandException(OptionWarning,"InterpretPropertyFailure",option);
arg2=arg2n; /* use the given argument as is */
}
}
}
#undef _process_flags
#undef _option_type
status=MagickTrue;
new_images=NewImageList();
switch (*(option+1))
{
case 'a':
{
if (LocaleCompare("append",option+1) == 0)
{
new_images=AppendImages(_images,IsNormalOp,_exception);
break;
}
if (LocaleCompare("average",option+1) == 0)
{
CLIWandWarnReplaced("-evaluate-sequence Mean");
(void) CLIListOperatorImages(cli_wand,"-evaluate-sequence","Mean",
NULL);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'c':
{
if (LocaleCompare("channel-fx",option+1) == 0)
{
new_images=ChannelFxImage(_images,arg1,_exception);
break;
}
if (LocaleCompare("clut",option+1) == 0)
{
Image
*clut_image;
/* FUTURE - make this a compose option, and thus can be used
with layers compose or even compose last image over all other
_images.
*/
new_images=RemoveFirstImageFromList(&_images);
clut_image=RemoveLastImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (clut_image == (Image *) NULL)
break;
(void) ClutImage(new_images,clut_image,new_images->interpolate,
_exception);
clut_image=DestroyImage(clut_image);
break;
}
if (LocaleCompare("coalesce",option+1) == 0)
{
new_images=CoalesceImages(_images,_exception);
break;
}
if (LocaleCompare("combine",option+1) == 0)
{
parse=(ssize_t) _images->colorspace;
if (_images->number_channels < GetImageListLength(_images))
parse=sRGBColorspace;
if ( IfPlusOp )
parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedColorspace",option,
arg1);
new_images=CombineImages(_images,(ColorspaceType) parse,_exception);
break;
}
if (LocaleCompare("compare",option+1) == 0)
{
double
distortion;
Image
*image,
*reconstruct_image;
MetricType
metric;
/*
Mathematically and visually annotate the difference between an
image and its reconstruction.
*/
image=RemoveFirstImageFromList(&_images);
reconstruct_image=RemoveFirstImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (reconstruct_image == (Image *) NULL)
{
image=DestroyImage(image);
break;
}
metric=UndefinedErrorMetric;
option=GetImageOption(_image_info,"metric");
if (option != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,option);
new_images=CompareImages(image,reconstruct_image,metric,&distortion,
_exception);
(void) distortion;
reconstruct_image=DestroyImage(reconstruct_image);
image=DestroyImage(image);
break;
}
if (LocaleCompare("complex",option+1) == 0)
{
parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator",
option,arg1);
new_images=ComplexImages(_images,(ComplexOperator) parse,_exception);
break;
}
if (LocaleCompare("composite",option+1) == 0)
{
CompositeOperator
compose;
const char*
value;
MagickBooleanType
clip_to_self;
Image
*mask_image,
*source_image;
RectangleInfo
geometry;
/* Compose value from "-compose" option only */
value=GetImageOption(_image_info,"compose");
if (value == (const char *) NULL)
compose=OverCompositeOp; /* use Over not source_image->compose */
else
compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions,
MagickFalse,value);
/* Get "clip-to-self" expert setting (false is normal) */
clip_to_self=GetCompositeClipToSelf(compose);
value=GetImageOption(_image_info,"compose:clip-to-self");
if (value != (const char *) NULL)
clip_to_self=IsStringTrue(value);
value=GetImageOption(_image_info,"compose:outside-overlay");
if (value != (const char *) NULL)
clip_to_self=IsStringFalse(value); /* deprecated */
new_images=RemoveFirstImageFromList(&_images);
source_image=RemoveFirstImageFromList(&_images);
if (source_image == (Image *) NULL)
break; /* FUTURE - produce Exception, rather than silent fail */
/* FUTURE - this should not be here! - should be part of -geometry */
if (source_image->geometry != (char *) NULL)
{
RectangleInfo
resize_geometry;
(void) ParseRegionGeometry(source_image,source_image->geometry,
&resize_geometry,_exception);
if ((source_image->columns != resize_geometry.width) ||
(source_image->rows != resize_geometry.height))
{
Image
*resize_image;
resize_image=ResizeImage(source_image,resize_geometry.width,
resize_geometry.height,source_image->filter,_exception);
if (resize_image != (Image *) NULL)
{
source_image=DestroyImage(source_image);
source_image=resize_image;
}
}
}
SetGeometry(source_image,&geometry);
(void) ParseAbsoluteGeometry(source_image->geometry,&geometry);
GravityAdjustGeometry(new_images->columns,new_images->rows,
new_images->gravity, &geometry);
mask_image=RemoveFirstImageFromList(&_images);
if (mask_image == (Image *) NULL)
status&=CompositeImage(new_images,source_image,compose,clip_to_self,
geometry.x,geometry.y,_exception);
else
{
if ((compose == DisplaceCompositeOp) ||
(compose == DistortCompositeOp))
{
status&=CompositeImage(source_image,mask_image,
CopyGreenCompositeOp,MagickTrue,0,0,_exception);
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,_exception);
}
else
{
Image
*clone_image;
clone_image=CloneImage(new_images,0,0,MagickTrue,_exception);
if (clone_image == (Image *) NULL)
break;
status&=CompositeImage(new_images,source_image,compose,
clip_to_self,geometry.x,geometry.y,_exception);
status&=CompositeImage(new_images,mask_image,
CopyAlphaCompositeOp,MagickTrue,0,0,_exception);
status&=CompositeImage(clone_image,new_images,OverCompositeOp,
clip_to_self,0,0,_exception);
new_images=DestroyImage(new_images);
new_images=clone_image;
}
mask_image=DestroyImage(mask_image);
}
source_image=DestroyImage(source_image);
break;
}
if (LocaleCompare("copy",option+1) == 0)
{
Image
*source_image;
OffsetInfo
offset;
RectangleInfo
geometry;
/*
Copy image pixels.
*/
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
if (IsGeometry(arg2) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
(void) ParsePageGeometry(_images,arg2,&geometry,_exception);
offset.x=geometry.x;
offset.y=geometry.y;
source_image=_images;
if (source_image->next != (Image *) NULL)
source_image=source_image->next;
(void) ParsePageGeometry(source_image,arg1,&geometry,_exception);
(void) CopyImagePixels(_images,source_image,&geometry,&offset,
_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'd':
{
if (LocaleCompare("deconstruct",option+1) == 0)
{
CLIWandWarnReplaced("-layer CompareAny");
(void) CLIListOperatorImages(cli_wand,"-layer","CompareAny",NULL);
break;
}
if (LocaleCompare("delete",option+1) == 0)
{
if (IfNormalOp)
DeleteImages(&_images,arg1,_exception);
else
DeleteImages(&_images,"-1",_exception);
break;
}
if (LocaleCompare("duplicate",option+1) == 0)
{
if (IfNormalOp)
{
const char
*p;
size_t
number_duplicates;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,
arg1);
number_duplicates=(size_t) StringToLong(arg1);
p=strchr(arg1,',');
if (p == (const char *) NULL)
new_images=DuplicateImages(_images,number_duplicates,"-1",
_exception);
else
new_images=DuplicateImages(_images,number_duplicates,p,
_exception);
}
else
new_images=DuplicateImages(_images,1,"-1",_exception);
AppendImageToList(&_images, new_images);
new_images=(Image *) NULL;
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'e':
{
if (LocaleCompare("evaluate-sequence",option+1) == 0)
{
parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1);
if (parse < 0)
CLIWandExceptArgBreak(OptionError,"UnrecognizedEvaluateOperator",
option,arg1);
new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse,
_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'f':
{
if (LocaleCompare("fft",option+1) == 0)
{
new_images=ForwardFourierTransformImage(_images,IsNormalOp,
_exception);
break;
}
if (LocaleCompare("flatten",option+1) == 0)
{
/* REDIRECTED to use -layers flatten instead */
(void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL);
break;
}
if (LocaleCompare("fx",option+1) == 0)
{
new_images=FxImage(_images,arg1,_exception);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'h':
{
if (LocaleCompare("hald-clut",option+1) == 0)
{
/* FUTURE - make this a compose option (and thus layers compose )
or perhaps compose last image over all other _images.
*/
Image
*hald_image;
new_images=RemoveFirstImageFromList(&_images);
hald_image=RemoveLastImageFromList(&_images);
if (hald_image == (Image *) NULL)
break;
(void) HaldClutImage(new_images,hald_image,_exception);
hald_image=DestroyImage(hald_image);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'i':
{
if (LocaleCompare("ift",option+1) == 0)
{
Image
*magnitude_image,
*phase_image;
magnitude_image=RemoveFirstImageFromList(&_images);
phase_image=RemoveFirstImageFromList(&_images);
/* FUTURE - produce Exception, rather than silent fail */
if (phase_image == (Image *) NULL)
break;
new_images=InverseFourierTransformImage(magnitude_image,phase_image,
IsNormalOp,_exception);
magnitude_image=DestroyImage(magnitude_image);
phase_image=DestroyImage(phase_image);
break;
}
if (LocaleCompare("insert",option+1) == 0)
{
Image
*insert_image,
*index_image;
ssize_t
index;
if (IfNormalOp && (IsGeometry(arg1) == MagickFalse))
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
index=0;
insert_image=RemoveLastImageFromList(&_images);
if (IfNormalOp)
index=(ssize_t) StringToLong(arg1);
index_image=insert_image;
if (index == 0)
PrependImageToList(&_images,insert_image);
else if (index == (ssize_t) GetImageListLength(_images))
AppendImageToList(&_images,insert_image);
else
{
index_image=GetImageFromList(_images,index-1);
if (index_image == (Image *) NULL)
CLIWandExceptArgBreak(OptionError,"NoSuchImage",option,arg1);
InsertImageInList(&index_image,insert_image);
}
_images=GetFirstImageInList(index_image);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'l':
{
if (LocaleCompare("layers",option+1) == 0)
{
parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1);
if ( parse < 0 )
CLIWandExceptArgBreak(OptionError,"UnrecognizedLayerMethod",
option,arg1);
switch ((LayerMethod) parse)
{
case CoalesceLayer:
{
new_images=CoalesceImages(_images,_exception);
break;
}
case CompareAnyLayer:
case CompareClearLayer:
case CompareOverlayLayer:
default:
{
new_images=CompareImagesLayers(_images,(LayerMethod) parse,
_exception);
break;
}
case MergeLayer:
case FlattenLayer:
case MosaicLayer:
case TrimBoundsLayer:
{
new_images=MergeImageLayers(_images,(LayerMethod) parse,
_exception);
break;
}
case DisposeLayer:
{
new_images=DisposeImages(_images,_exception);
break;
}
case OptimizeImageLayer:
{
new_images=OptimizeImageLayers(_images,_exception);
break;
}
case OptimizePlusLayer:
{
new_images=OptimizePlusImageLayers(_images,_exception);
break;
}
case OptimizeTransLayer:
{
OptimizeImageTransparency(_images,_exception);
break;
}
case RemoveDupsLayer:
{
RemoveDuplicateLayers(&_images,_exception);
break;
}
case RemoveZeroLayer:
{
RemoveZeroDelayLayers(&_images,_exception);
break;
}
case OptimizeLayer:
{ /* General Purpose, GIF Animation Optimizer. */
new_images=CoalesceImages(_images,_exception);
if (new_images == (Image *) NULL)
break;
_images=DestroyImageList(_images);
_images=OptimizeImageLayers(new_images,_exception);
if (_images == (Image *) NULL)
break;
new_images=DestroyImageList(new_images);
OptimizeImageTransparency(_images,_exception);
(void) RemapImages(_quantize_info,_images,(Image *) NULL,
_exception);
break;
}
case CompositeLayer:
{
Image
*source;
RectangleInfo
geometry;
CompositeOperator
compose;
const char*
value;
value=GetImageOption(_image_info,"compose");
compose=OverCompositeOp; /* Default to Over */
if (value != (const char *) NULL)
compose=(CompositeOperator) ParseCommandOption(
MagickComposeOptions,MagickFalse,value);
/* Split image sequence at the first 'NULL:' image. */
source=_images;
while (source != (Image *) NULL)
{
source=GetNextImageInList(source);
if ((source != (Image *) NULL) &&
(LocaleCompare(source->magick,"NULL") == 0))
break;
}
if (source != (Image *) NULL)
{
if ((GetPreviousImageInList(source) == (Image *) NULL) ||
(GetNextImageInList(source) == (Image *) NULL))
source=(Image *) NULL;
else
{ /* Separate the two lists, junk the null: image. */
source=SplitImageList(source->previous);
DeleteImageFromList(&source);
}
}
if (source == (Image *) NULL)
{
(void) ThrowMagickException(_exception,GetMagickModule(),
OptionError,"MissingNullSeparator","layers Composite");
break;
}
/* Adjust offset with gravity and virtual canvas. */
SetGeometry(_images,&geometry);
(void) ParseAbsoluteGeometry(_images->geometry,&geometry);
geometry.width=source->page.width != 0 ?
source->page.width : source->columns;
geometry.height=source->page.height != 0 ?
source->page.height : source->rows;
GravityAdjustGeometry(_images->page.width != 0 ?
_images->page.width : _images->columns,
_images->page.height != 0 ? _images->page.height :
_images->rows,_images->gravity,&geometry);
/* Compose the two image sequences together */
CompositeLayers(_images,compose,source,geometry.x,geometry.y,
_exception);
source=DestroyImageList(source);
break;
}
}
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'm':
{
if (LocaleCompare("map",option+1) == 0)
{
CLIWandWarnReplaced("+remap");
(void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);
break;
}
if (LocaleCompare("metric",option+1) == 0)
{
(void) SetImageOption(_image_info,option+1,arg1);
break;
}
if (LocaleCompare("morph",option+1) == 0)
{
Image
*morph_image;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
morph_image=MorphImages(_images,StringToUnsignedLong(arg1),
_exception);
if (morph_image == (Image *) NULL)
break;
_images=DestroyImageList(_images);
_images=morph_image;
break;
}
if (LocaleCompare("mosaic",option+1) == 0)
{
/* REDIRECTED to use -layers mosaic instead */
(void) CLIListOperatorImages(cli_wand,"-layers",option+1,NULL);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'p':
{
if (LocaleCompare("poly",option+1) == 0)
{
double
*args;
ssize_t
count;
/* convert argument string into an array of doubles */
args = StringToArrayOfDoubles(arg1,&count,_exception);
if (args == (double *) NULL )
CLIWandExceptArgBreak(OptionError,"InvalidNumberList",option,arg1);
new_images=PolynomialImage(_images,(size_t) (count >> 1),args,
_exception);
args=(double *) RelinquishMagickMemory(args);
break;
}
if (LocaleCompare("process",option+1) == 0)
{
/* FUTURE: better parsing using ScriptToken() from string ??? */
char
**arguments;
int
j,
number_arguments;
arguments=StringToArgv(arg1,&number_arguments);
if (arguments == (char **) NULL)
break;
if (strchr(arguments[1],'=') != (char *) NULL)
{
char
breaker,
quote,
*token;
const char
*arguments;
int
next,
status;
size_t
length;
TokenInfo
*token_info;
/*
Support old style syntax, filter="-option arg1".
*/
assert(arg1 != (const char *) NULL);
length=strlen(arg1);
token=(char *) NULL;
if (~length >= (MagickPathExtent-1))
token=(char *) AcquireQuantumMemory(length+MagickPathExtent,
sizeof(*token));
if (token == (char *) NULL)
break;
next=0;
arguments=arg1;
token_info=AcquireTokenInfo();
status=Tokenizer(token_info,0,token,length,arguments,"","=",
"\"",'\0',&breaker,&next,"e);
token_info=DestroyTokenInfo(token_info);
if (status == 0)
{
const char
*argv;
argv=(&(arguments[next]));
(void) InvokeDynamicImageFilter(token,&_images,1,&argv,
_exception);
}
token=DestroyString(token);
break;
}
(void) SubstituteString(&arguments[1],"-","");
(void) InvokeDynamicImageFilter(arguments[1],&_images,
number_arguments-2,(const char **) arguments+2,_exception);
for (j=0; j < number_arguments; j++)
arguments[j]=DestroyString(arguments[j]);
arguments=(char **) RelinquishMagickMemory(arguments);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 'r':
{
if (LocaleCompare("remap",option+1) == 0)
{
(void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception);
break;
}
if (LocaleCompare("reverse",option+1) == 0)
{
ReverseImageList(&_images);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
case 's':
{
if (LocaleCompare("smush",option+1) == 0)
{
/* FUTURE: this option needs more work to make better */
ssize_t
offset;
if (IsGeometry(arg1) == MagickFalse)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
offset=(ssize_t) StringToLong(arg1);
new_images=SmushImages(_images,IsNormalOp,offset,_exception);
break;
}
if (LocaleCompare("subimage",option+1) == 0)
{
Image
*base_image,
*compare_image;
const char
*value;
MetricType
metric;
double
similarity;
RectangleInfo
offset;
base_image=GetImageFromList(_images,0);
compare_image=GetImageFromList(_images,1);
/* Comparision Metric */
metric=UndefinedErrorMetric;
value=GetImageOption(_image_info,"metric");
if (value != (const char *) NULL)
metric=(MetricType) ParseCommandOption(MagickMetricOptions,
MagickFalse,value);
new_images=SimilarityImage(base_image,compare_image,metric,0.0,
&offset,&similarity,_exception);
if (new_images != (Image *) NULL)
{
char
result[MagickPathExtent];
(void) FormatLocaleString(result,MagickPathExtent,"%lf",
similarity);
(void) SetImageProperty(new_images,"subimage:similarity",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long)
offset.x);
(void) SetImageProperty(new_images,"subimage:x",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,"%+ld",(long)
offset.y);
(void) SetImageProperty(new_images,"subimage:y",result,
_exception);
(void) FormatLocaleString(result,MagickPathExtent,
"%lux%lu%+ld%+ld",(unsigned long) offset.width,(unsigned long)
offset.height,(long) offset.x,(long) offset.y);
(void) SetImageProperty(new_images,"subimage:offset",result,
_exception);
}
break;
}
if (LocaleCompare("swap",option+1) == 0)
{
Image
*p,
*q,
*swap;
ssize_t
index,
swap_index;
index=(-1);
swap_index=(-2);
if (IfNormalOp) {
GeometryInfo
geometry_info;
MagickStatusType
flags;
swap_index=(-1);
flags=ParseGeometry(arg1,&geometry_info);
if ((flags & RhoValue) == 0)
CLIWandExceptArgBreak(OptionError,"InvalidArgument",option,arg1);
index=(ssize_t) geometry_info.rho;
if ((flags & SigmaValue) != 0)
swap_index=(ssize_t) geometry_info.sigma;
}
p=GetImageFromList(_images,index);
q=GetImageFromList(_images,swap_index);
if ((p == (Image *) NULL) || (q == (Image *) NULL)) {
if (IfNormalOp)
CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1)
else
CLIWandExceptionBreak(OptionError,"TwoOrMoreImagesRequired",option);
}
if (p == q)
CLIWandExceptArgBreak(OptionError,"InvalidImageIndex",option,arg1);
swap=CloneImage(p,0,0,MagickTrue,_exception);
if (swap == (Image *) NULL)
CLIWandExceptArgBreak(ResourceLimitError,"MemoryAllocationFailed",
option,GetExceptionMessage(errno));
ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception));
ReplaceImageInList(&q,swap);
_images=GetFirstImageInList(q);
break;
}
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
default:
CLIWandExceptionBreak(OptionError,"UnrecognizedOption",option);
}
/* clean up percent escape interpreted strings */
if (arg1 != arg1n )
arg1=DestroyString((char *)arg1);
if (arg2 != arg2n )
arg2=DestroyString((char *)arg2);
/* if new image list generated, replace existing image list */
if (new_images == (Image *) NULL)
return(status == 0 ? MagickFalse : MagickTrue);
_images=DestroyImageList(_images);
_images=GetFirstImageInList(new_images);
return(status == 0 ? MagickFalse : MagickTrue);
#undef _image_info
#undef _images
#undef _exception
#undef _draw_info
#undef _quantize_info
#undef IfNormalOp
#undef IfPlusOp
#undef IsNormalOp
}
| 169,604 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int nfs4_do_close(struct path *path, struct nfs4_state *state, int wait)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_closedata *calldata;
struct nfs4_state_owner *sp = state->owner;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE],
.rpc_cred = state->owner->so_cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_close_ops,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
int status = -ENOMEM;
calldata = kmalloc(sizeof(*calldata), GFP_KERNEL);
if (calldata == NULL)
goto out;
calldata->inode = state->inode;
calldata->state = state;
calldata->arg.fh = NFS_FH(state->inode);
calldata->arg.stateid = &state->open_stateid;
/* Serialization for the sequence id */
calldata->arg.seqid = nfs_alloc_seqid(&state->owner->so_seqid);
if (calldata->arg.seqid == NULL)
goto out_free_calldata;
calldata->arg.open_flags = 0;
calldata->arg.bitmask = server->attr_bitmask;
calldata->res.fattr = &calldata->fattr;
calldata->res.seqid = calldata->arg.seqid;
calldata->res.server = server;
calldata->path.mnt = mntget(path->mnt);
calldata->path.dentry = dget(path->dentry);
msg.rpc_argp = &calldata->arg,
msg.rpc_resp = &calldata->res,
task_setup_data.callback_data = calldata;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
status = 0;
if (wait)
status = rpc_wait_for_completion_task(task);
rpc_put_task(task);
return status;
out_free_calldata:
kfree(calldata);
out:
nfs4_put_open_state(state);
nfs4_put_state_owner(sp);
return status;
}
Commit Message: NFSv4: Convert the open and close ops to use fmode
Signed-off-by: Trond Myklebust <[email protected]>
CWE ID: | int nfs4_do_close(struct path *path, struct nfs4_state *state, int wait)
{
struct nfs_server *server = NFS_SERVER(state->inode);
struct nfs4_closedata *calldata;
struct nfs4_state_owner *sp = state->owner;
struct rpc_task *task;
struct rpc_message msg = {
.rpc_proc = &nfs4_procedures[NFSPROC4_CLNT_CLOSE],
.rpc_cred = state->owner->so_cred,
};
struct rpc_task_setup task_setup_data = {
.rpc_client = server->client,
.rpc_message = &msg,
.callback_ops = &nfs4_close_ops,
.workqueue = nfsiod_workqueue,
.flags = RPC_TASK_ASYNC,
};
int status = -ENOMEM;
calldata = kmalloc(sizeof(*calldata), GFP_KERNEL);
if (calldata == NULL)
goto out;
calldata->inode = state->inode;
calldata->state = state;
calldata->arg.fh = NFS_FH(state->inode);
calldata->arg.stateid = &state->open_stateid;
/* Serialization for the sequence id */
calldata->arg.seqid = nfs_alloc_seqid(&state->owner->so_seqid);
if (calldata->arg.seqid == NULL)
goto out_free_calldata;
calldata->arg.fmode = 0;
calldata->arg.bitmask = server->attr_bitmask;
calldata->res.fattr = &calldata->fattr;
calldata->res.seqid = calldata->arg.seqid;
calldata->res.server = server;
calldata->path.mnt = mntget(path->mnt);
calldata->path.dentry = dget(path->dentry);
msg.rpc_argp = &calldata->arg,
msg.rpc_resp = &calldata->res,
task_setup_data.callback_data = calldata;
task = rpc_run_task(&task_setup_data);
if (IS_ERR(task))
return PTR_ERR(task);
status = 0;
if (wait)
status = rpc_wait_for_completion_task(task);
rpc_put_task(task);
return status;
out_free_calldata:
kfree(calldata);
out:
nfs4_put_open_state(state);
nfs4_put_state_owner(sp);
return status;
}
| 165,691 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static v8::Handle<v8::Value> optionsObjectCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.optionsObject");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError();
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(Dictionary, oo, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
if (args.Length() > 0 && !oo.isUndefinedOrNull() && !oo.isObject()) {
return V8Proxy::throwTypeError("Not an object.");
}
if (args.Length() <= 1) {
imp->optionsObject(oo);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(Dictionary, ooo, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
if (args.Length() > 1 && !ooo.isUndefinedOrNull() && !ooo.isObject()) {
return V8Proxy::throwTypeError("Not an object.");
}
imp->optionsObject(oo, ooo);
return v8::Handle<v8::Value>();
}
Commit Message: [V8] Pass Isolate to throwNotEnoughArgumentsError()
https://bugs.webkit.org/show_bug.cgi?id=86983
Reviewed by Adam Barth.
The objective is to pass Isolate around in V8 bindings.
This patch passes Isolate to throwNotEnoughArgumentsError().
No tests. No change in behavior.
* bindings/scripts/CodeGeneratorV8.pm:
(GenerateArgumentsCountCheck):
(GenerateEventConstructorCallback):
* bindings/scripts/test/V8/V8Float64Array.cpp:
(WebCore::Float64ArrayV8Internal::fooCallback):
* bindings/scripts/test/V8/V8TestActiveDOMObject.cpp:
(WebCore::TestActiveDOMObjectV8Internal::excitingFunctionCallback):
(WebCore::TestActiveDOMObjectV8Internal::postMessageCallback):
* bindings/scripts/test/V8/V8TestCustomNamedGetter.cpp:
(WebCore::TestCustomNamedGetterV8Internal::anotherFunctionCallback):
* bindings/scripts/test/V8/V8TestEventConstructor.cpp:
(WebCore::V8TestEventConstructor::constructorCallback):
* bindings/scripts/test/V8/V8TestEventTarget.cpp:
(WebCore::TestEventTargetV8Internal::itemCallback):
(WebCore::TestEventTargetV8Internal::dispatchEventCallback):
* bindings/scripts/test/V8/V8TestInterface.cpp:
(WebCore::TestInterfaceV8Internal::supplementalMethod2Callback):
(WebCore::V8TestInterface::constructorCallback):
* bindings/scripts/test/V8/V8TestMediaQueryListListener.cpp:
(WebCore::TestMediaQueryListListenerV8Internal::methodCallback):
* bindings/scripts/test/V8/V8TestNamedConstructor.cpp:
(WebCore::V8TestNamedConstructorConstructorCallback):
* bindings/scripts/test/V8/V8TestObj.cpp:
(WebCore::TestObjV8Internal::voidMethodWithArgsCallback):
(WebCore::TestObjV8Internal::intMethodWithArgsCallback):
(WebCore::TestObjV8Internal::objMethodWithArgsCallback):
(WebCore::TestObjV8Internal::methodWithSequenceArgCallback):
(WebCore::TestObjV8Internal::methodReturningSequenceCallback):
(WebCore::TestObjV8Internal::methodThatRequiresAllArgsAndThrowsCallback):
(WebCore::TestObjV8Internal::serializedValueCallback):
(WebCore::TestObjV8Internal::idbKeyCallback):
(WebCore::TestObjV8Internal::optionsObjectCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndOptionalArgCallback):
(WebCore::TestObjV8Internal::methodWithNonOptionalArgAndTwoOptionalArgsCallback):
(WebCore::TestObjV8Internal::methodWithCallbackArgCallback):
(WebCore::TestObjV8Internal::methodWithNonCallbackArgAndCallbackArgCallback):
(WebCore::TestObjV8Internal::overloadedMethod1Callback):
(WebCore::TestObjV8Internal::overloadedMethod2Callback):
(WebCore::TestObjV8Internal::overloadedMethod3Callback):
(WebCore::TestObjV8Internal::overloadedMethod4Callback):
(WebCore::TestObjV8Internal::overloadedMethod5Callback):
(WebCore::TestObjV8Internal::overloadedMethod6Callback):
(WebCore::TestObjV8Internal::overloadedMethod7Callback):
(WebCore::TestObjV8Internal::overloadedMethod11Callback):
(WebCore::TestObjV8Internal::overloadedMethod12Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod1Callback):
(WebCore::TestObjV8Internal::enabledAtRuntimeMethod2Callback):
(WebCore::TestObjV8Internal::convert1Callback):
(WebCore::TestObjV8Internal::convert2Callback):
(WebCore::TestObjV8Internal::convert3Callback):
(WebCore::TestObjV8Internal::convert4Callback):
(WebCore::TestObjV8Internal::convert5Callback):
(WebCore::TestObjV8Internal::strictFunctionCallback):
(WebCore::V8TestObj::constructorCallback):
* bindings/scripts/test/V8/V8TestSerializedScriptValueInterface.cpp:
(WebCore::TestSerializedScriptValueInterfaceV8Internal::acceptTransferListCallback):
(WebCore::V8TestSerializedScriptValueInterface::constructorCallback):
* bindings/v8/ScriptController.cpp:
(WebCore::setValueAndClosePopupCallback):
* bindings/v8/V8Proxy.cpp:
(WebCore::V8Proxy::throwNotEnoughArgumentsError):
* bindings/v8/V8Proxy.h:
(V8Proxy):
* bindings/v8/custom/V8AudioContextCustom.cpp:
(WebCore::V8AudioContext::constructorCallback):
* bindings/v8/custom/V8DataViewCustom.cpp:
(WebCore::V8DataView::getInt8Callback):
(WebCore::V8DataView::getUint8Callback):
(WebCore::V8DataView::setInt8Callback):
(WebCore::V8DataView::setUint8Callback):
* bindings/v8/custom/V8DirectoryEntryCustom.cpp:
(WebCore::V8DirectoryEntry::getDirectoryCallback):
(WebCore::V8DirectoryEntry::getFileCallback):
* bindings/v8/custom/V8IntentConstructor.cpp:
(WebCore::V8Intent::constructorCallback):
* bindings/v8/custom/V8SVGLengthCustom.cpp:
(WebCore::V8SVGLength::convertToSpecifiedUnitsCallback):
* bindings/v8/custom/V8WebGLRenderingContextCustom.cpp:
(WebCore::getObjectParameter):
(WebCore::V8WebGLRenderingContext::getAttachedShadersCallback):
(WebCore::V8WebGLRenderingContext::getExtensionCallback):
(WebCore::V8WebGLRenderingContext::getFramebufferAttachmentParameterCallback):
(WebCore::V8WebGLRenderingContext::getParameterCallback):
(WebCore::V8WebGLRenderingContext::getProgramParameterCallback):
(WebCore::V8WebGLRenderingContext::getShaderParameterCallback):
(WebCore::V8WebGLRenderingContext::getUniformCallback):
(WebCore::vertexAttribAndUniformHelperf):
(WebCore::uniformHelperi):
(WebCore::uniformMatrixHelper):
* bindings/v8/custom/V8WebKitMutationObserverCustom.cpp:
(WebCore::V8WebKitMutationObserver::constructorCallback):
(WebCore::V8WebKitMutationObserver::observeCallback):
* bindings/v8/custom/V8WebSocketCustom.cpp:
(WebCore::V8WebSocket::constructorCallback):
(WebCore::V8WebSocket::sendCallback):
* bindings/v8/custom/V8XMLHttpRequestCustom.cpp:
(WebCore::V8XMLHttpRequest::openCallback):
git-svn-id: svn://svn.chromium.org/blink/trunk@117736 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static v8::Handle<v8::Value> optionsObjectCallback(const v8::Arguments& args)
{
INC_STATS("DOM.TestObj.optionsObject");
if (args.Length() < 1)
return V8Proxy::throwNotEnoughArgumentsError(args.GetIsolate());
TestObj* imp = V8TestObj::toNative(args.Holder());
EXCEPTION_BLOCK(Dictionary, oo, MAYBE_MISSING_PARAMETER(args, 0, DefaultIsUndefined));
if (args.Length() > 0 && !oo.isUndefinedOrNull() && !oo.isObject()) {
return V8Proxy::throwTypeError("Not an object.");
}
if (args.Length() <= 1) {
imp->optionsObject(oo);
return v8::Handle<v8::Value>();
}
EXCEPTION_BLOCK(Dictionary, ooo, MAYBE_MISSING_PARAMETER(args, 1, DefaultIsUndefined));
if (args.Length() > 1 && !ooo.isUndefinedOrNull() && !ooo.isObject()) {
return V8Proxy::throwTypeError("Not an object.");
}
imp->optionsObject(oo, ooo);
return v8::Handle<v8::Value>();
}
| 171,094 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FileUtilProxy::Write(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
const char* buffer,
int bytes_to_write,
WriteCallback* callback) {
if (bytes_to_write <= 0)
return false;
return Start(FROM_HERE, message_loop_proxy,
new RelayWrite(file, offset, buffer, bytes_to_write, callback));
}
Commit Message: Fix a small leak in FileUtilProxy
BUG=none
TEST=green mem bots
Review URL: http://codereview.chromium.org/7669046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool FileUtilProxy::Write(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
const char* buffer,
int bytes_to_write,
WriteCallback* callback) {
if (bytes_to_write <= 0) {
delete callback;
return false;
}
return Start(FROM_HERE, message_loop_proxy,
new RelayWrite(file, offset, buffer, bytes_to_write, callback));
}
| 170,274 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() {
return &shutdown_event_;
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | base::WaitableEvent* ProxyChannelDelegate::GetShutdownEvent() {
| 170,734 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderFrameHostManager::DetermineSiteInstanceForURL(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* current_instance,
SiteInstance* dest_instance,
ui::PageTransition transition,
bool dest_is_restore,
bool dest_is_view_source_mode,
bool force_browsing_instance_swap,
bool was_server_redirect) {
SiteInstanceImpl* current_instance_impl =
static_cast<SiteInstanceImpl*>(current_instance);
NavigationControllerImpl& controller =
delegate_->GetControllerForRenderManager();
BrowserContext* browser_context = controller.GetBrowserContext();
if (dest_instance) {
if (force_browsing_instance_swap) {
CHECK(!dest_instance->IsRelatedSiteInstance(
render_frame_host_->GetSiteInstance()));
}
return SiteInstanceDescriptor(dest_instance);
}
if (force_browsing_instance_swap)
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kProcessPerSite) &&
ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
return SiteInstanceDescriptor(current_instance_impl);
}
if (SiteIsolationPolicy::AreCrossProcessFramesPossible() &&
!frame_tree_node_->IsMainFrame()) {
SiteInstance* parent_site_instance =
frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) &&
dest_url.SchemeIs(kChromeUIScheme)) {
return SiteInstanceDescriptor(parent_site_instance);
}
}
if (!current_instance_impl->HasSite()) {
bool use_process_per_site =
RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
use_process_per_site) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
}
if (current_instance_impl->HasWrongProcessForURL(dest_url))
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
if (dest_is_view_source_mode)
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, dest_url)) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
}
if (dest_is_restore &&
GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
current_instance_impl->SetSite(dest_url);
}
return SiteInstanceDescriptor(current_instance_impl);
}
NavigationEntry* current_entry = controller.GetLastCommittedEntry();
if (interstitial_page_) {
current_entry = controller.GetEntryAtOffset(-1);
}
if (current_entry &&
current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
!IsRendererDebugURL(dest_url)) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
}
GURL about_blank(url::kAboutBlankURL);
GURL about_srcdoc(content::kAboutSrcDocURL);
bool dest_is_data_or_about = dest_url == about_srcdoc ||
dest_url == about_blank ||
dest_url.scheme() == url::kDataScheme;
if (source_instance && dest_is_data_or_about && !was_server_redirect)
return SiteInstanceDescriptor(source_instance);
if (IsCurrentlySameSite(render_frame_host_.get(), dest_url))
return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance());
if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) {
if (!frame_tree_node_->IsMainFrame()) {
RenderFrameHostImpl* main_frame =
frame_tree_node_->frame_tree()->root()->current_frame_host();
if (IsCurrentlySameSite(main_frame, dest_url))
return SiteInstanceDescriptor(main_frame->GetSiteInstance());
}
if (frame_tree_node_->opener()) {
RenderFrameHostImpl* opener_frame =
frame_tree_node_->opener()->current_frame_host();
if (IsCurrentlySameSite(opener_frame, dest_url))
return SiteInstanceDescriptor(opener_frame->GetSiteInstance());
}
}
if (!frame_tree_node_->IsMainFrame() &&
SiteIsolationPolicy::IsTopDocumentIsolationEnabled() &&
!SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context,
dest_url)) {
if (GetContentClient()
->browser()
->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation(
dest_url, current_instance)) {
return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance());
}
return SiteInstanceDescriptor(
browser_context, dest_url,
SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME);
}
if (!frame_tree_node_->IsMainFrame()) {
RenderFrameHostImpl* parent =
frame_tree_node_->parent()->current_frame_host();
bool dest_url_requires_dedicated_process =
SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context,
dest_url);
if (!parent->GetSiteInstance()->RequiresDedicatedProcess() &&
!dest_url_requires_dedicated_process) {
return SiteInstanceDescriptor(parent->GetSiteInstance());
}
}
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | RenderFrameHostManager::DetermineSiteInstanceForURL(
const GURL& dest_url,
SiteInstance* source_instance,
SiteInstance* current_instance,
SiteInstance* dest_instance,
ui::PageTransition transition,
bool dest_is_restore,
bool dest_is_view_source_mode,
bool force_browsing_instance_swap,
bool was_server_redirect) {
SiteInstanceImpl* current_instance_impl =
static_cast<SiteInstanceImpl*>(current_instance);
NavigationControllerImpl& controller =
delegate_->GetControllerForRenderManager();
BrowserContext* browser_context = controller.GetBrowserContext();
if (dest_instance) {
if (force_browsing_instance_swap) {
CHECK(!dest_instance->IsRelatedSiteInstance(
render_frame_host_->GetSiteInstance()));
}
return SiteInstanceDescriptor(dest_instance);
}
if (force_browsing_instance_swap)
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kProcessPerSite) &&
ui::PageTransitionCoreTypeIs(transition, ui::PAGE_TRANSITION_GENERATED)) {
return SiteInstanceDescriptor(current_instance_impl);
}
if (SiteIsolationPolicy::AreCrossProcessFramesPossible() &&
!frame_tree_node_->IsMainFrame()) {
SiteInstance* parent_site_instance =
frame_tree_node_->parent()->current_frame_host()->GetSiteInstance();
if (parent_site_instance->GetSiteURL().SchemeIs(kChromeUIScheme) &&
dest_url.SchemeIs(kChromeUIScheme)) {
return SiteInstanceDescriptor(parent_site_instance);
}
}
if (!current_instance_impl->HasSite()) {
bool use_process_per_site =
RenderProcessHost::ShouldUseProcessPerSite(browser_context, dest_url) &&
RenderProcessHostImpl::GetProcessHostForSite(browser_context, dest_url);
if (current_instance_impl->HasRelatedSiteInstance(dest_url) ||
use_process_per_site) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
}
if (current_instance_impl->HasWrongProcessForURL(dest_url))
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
if (dest_is_view_source_mode)
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
if (WebUIControllerFactoryRegistry::GetInstance()->UseWebUIForURL(
browser_context, dest_url)) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
}
if (dest_is_restore &&
GetContentClient()->browser()->ShouldAssignSiteForURL(dest_url)) {
current_instance_impl->SetSite(dest_url);
}
return SiteInstanceDescriptor(current_instance_impl);
}
NavigationEntry* current_entry = controller.GetLastCommittedEntry();
if (delegate_->GetInterstitialForRenderManager()) {
current_entry = controller.GetEntryAtOffset(-1);
}
if (current_entry &&
current_entry->IsViewSourceMode() != dest_is_view_source_mode &&
!IsRendererDebugURL(dest_url)) {
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::UNRELATED);
}
GURL about_blank(url::kAboutBlankURL);
GURL about_srcdoc(content::kAboutSrcDocURL);
bool dest_is_data_or_about = dest_url == about_srcdoc ||
dest_url == about_blank ||
dest_url.scheme() == url::kDataScheme;
if (source_instance && dest_is_data_or_about && !was_server_redirect)
return SiteInstanceDescriptor(source_instance);
if (IsCurrentlySameSite(render_frame_host_.get(), dest_url))
return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance());
if (SiteIsolationPolicy::IsTopDocumentIsolationEnabled()) {
if (!frame_tree_node_->IsMainFrame()) {
RenderFrameHostImpl* main_frame =
frame_tree_node_->frame_tree()->root()->current_frame_host();
if (IsCurrentlySameSite(main_frame, dest_url))
return SiteInstanceDescriptor(main_frame->GetSiteInstance());
}
if (frame_tree_node_->opener()) {
RenderFrameHostImpl* opener_frame =
frame_tree_node_->opener()->current_frame_host();
if (IsCurrentlySameSite(opener_frame, dest_url))
return SiteInstanceDescriptor(opener_frame->GetSiteInstance());
}
}
if (!frame_tree_node_->IsMainFrame() &&
SiteIsolationPolicy::IsTopDocumentIsolationEnabled() &&
!SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context,
dest_url)) {
if (GetContentClient()
->browser()
->ShouldFrameShareParentSiteInstanceDespiteTopDocumentIsolation(
dest_url, current_instance)) {
return SiteInstanceDescriptor(render_frame_host_->GetSiteInstance());
}
return SiteInstanceDescriptor(
browser_context, dest_url,
SiteInstanceRelation::RELATED_DEFAULT_SUBFRAME);
}
if (!frame_tree_node_->IsMainFrame()) {
RenderFrameHostImpl* parent =
frame_tree_node_->parent()->current_frame_host();
bool dest_url_requires_dedicated_process =
SiteInstanceImpl::DoesSiteRequireDedicatedProcess(browser_context,
dest_url);
if (!parent->GetSiteInstance()->RequiresDedicatedProcess() &&
!dest_url_requires_dedicated_process) {
return SiteInstanceDescriptor(parent->GetSiteInstance());
}
}
return SiteInstanceDescriptor(browser_context, dest_url,
SiteInstanceRelation::RELATED);
}
| 172,320 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415 | static php_mb_regex_t *php_mbregex_compile_pattern(const char *pattern, int patlen, OnigOptionType options, OnigEncoding enc, OnigSyntaxType *syntax TSRMLS_DC)
{
int err_code = 0;
int found = 0;
php_mb_regex_t *retval = NULL, **rc = NULL;
OnigErrorInfo err_info;
OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
found = zend_hash_find(&MBREX(ht_rc), (char *)pattern, patlen+1, (void **) &rc);
if (found == FAILURE || (*rc)->options != options || (*rc)->enc != enc || (*rc)->syntax != syntax) {
if ((err_code = onig_new(&retval, (OnigUChar *)pattern, (OnigUChar *)(pattern + patlen), options, enc, syntax, &err_info)) != ONIG_NORMAL) {
onig_error_code_to_str(err_str, err_code, err_info);
php_error_docref(NULL TSRMLS_CC, E_WARNING, "mbregex compile err: %s", err_str);
retval = NULL;
goto out;
}
zend_hash_update(&MBREX(ht_rc), (char *) pattern, patlen + 1, (void *) &retval, sizeof(retval), NULL);
} else if (found == SUCCESS) {
retval = *rc;
}
out:
return retval;
}
| 167,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftHEVC::onQueueFilled(OMX_U32 portIndex) {
UNUSED(portIndex);
if (mSignalledError) {
return;
}
if (mOutputPortSettingsChange != NONE) {
return;
}
if (NULL == mCodecCtx) {
if (OK != initDecoder()) {
return;
}
}
if (outputBufferWidth() != mStride) {
/* Set the run-time (dynamic) parameters */
mStride = outputBufferWidth();
setParams(mStride);
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
/* If input EOS is seen and decoder is not in flush mode,
* set the decoder in flush mode.
* There can be a case where EOS is sent along with last picture data
* In that case, only after decoding that input data, decoder has to be
* put in flush. This case is handled here */
if (mReceivedEOS && !mIsInFlush) {
setFlushMode();
}
while (!outQueue.empty()) {
BufferInfo *inInfo;
OMX_BUFFERHEADERTYPE *inHeader;
BufferInfo *outInfo;
OMX_BUFFERHEADERTYPE *outHeader;
size_t timeStampIx;
inInfo = NULL;
inHeader = NULL;
if (!mIsInFlush) {
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
} else {
break;
}
}
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
outHeader->nTimeStamp = 0;
outHeader->nOffset = 0;
if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) {
mReceivedEOS = true;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
setFlushMode();
}
}
/* Get a free slot in timestamp array to hold input timestamp */
{
size_t i;
timeStampIx = 0;
for (i = 0; i < MAX_TIME_STAMPS; i++) {
if (!mTimeStampsValid[i]) {
timeStampIx = i;
break;
}
}
if (inHeader != NULL) {
mTimeStampsValid[timeStampIx] = true;
mTimeStamps[timeStampIx] = inHeader->nTimeStamp;
}
}
{
ivd_video_decode_ip_t s_dec_ip;
ivd_video_decode_op_t s_dec_op;
WORD32 timeDelay, timeTaken;
size_t sizeY, sizeUV;
setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx);
GETTIME(&mTimeStart, NULL);
/* Compute time elapsed between end of previous decode()
* to start of current decode() */
TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
IV_API_CALL_STATUS_T status;
status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF));
GETTIME(&mTimeEnd, NULL);
/* Compute time taken for decode() */
TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
s_dec_op.u4_num_bytes_consumed);
if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) {
mFlushNeeded = true;
}
if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) {
/* If the input did not contain picture data, then ignore
* the associated timestamp */
mTimeStampsValid[timeStampIx] = false;
}
if (mChangingResolution && !s_dec_op.u4_output_present) {
mChangingResolution = false;
resetDecoder();
resetPlugin();
continue;
}
if (resChanged) {
mChangingResolution = true;
if (mFlushNeeded) {
setFlushMode();
}
continue;
}
if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) {
uint32_t width = s_dec_op.u4_pic_wd;
uint32_t height = s_dec_op.u4_pic_ht;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
resetDecoder();
return;
}
}
if (s_dec_op.u4_output_present) {
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts];
mTimeStampsValid[s_dec_op.u4_ts] = false;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
} else {
/* If in flush mode and no output is returned by the codec,
* then come out of flush mode */
mIsInFlush = false;
/* If EOS was recieved on input port and there is no output
* from the codec, then signal EOS on output port */
if (mReceivedEOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags |= OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
resetPlugin();
}
}
}
if (inHeader != NULL) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20 | void SoftHEVC::onQueueFilled(OMX_U32 portIndex) {
UNUSED(portIndex);
if (mSignalledError) {
return;
}
if (mOutputPortSettingsChange != NONE) {
return;
}
if (NULL == mCodecCtx) {
if (OK != initDecoder()) {
return;
}
}
if (outputBufferWidth() != mStride) {
/* Set the run-time (dynamic) parameters */
mStride = outputBufferWidth();
setParams(mStride);
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
/* If input EOS is seen and decoder is not in flush mode,
* set the decoder in flush mode.
* There can be a case where EOS is sent along with last picture data
* In that case, only after decoding that input data, decoder has to be
* put in flush. This case is handled here */
if (mReceivedEOS && !mIsInFlush) {
setFlushMode();
}
while (!outQueue.empty()) {
BufferInfo *inInfo;
OMX_BUFFERHEADERTYPE *inHeader;
BufferInfo *outInfo;
OMX_BUFFERHEADERTYPE *outHeader;
size_t timeStampIx;
inInfo = NULL;
inHeader = NULL;
if (!mIsInFlush) {
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
} else {
break;
}
}
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
outHeader->nTimeStamp = 0;
outHeader->nOffset = 0;
if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) {
mReceivedEOS = true;
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
setFlushMode();
}
}
/* Get a free slot in timestamp array to hold input timestamp */
{
size_t i;
timeStampIx = 0;
for (i = 0; i < MAX_TIME_STAMPS; i++) {
if (!mTimeStampsValid[i]) {
timeStampIx = i;
break;
}
}
if (inHeader != NULL) {
mTimeStampsValid[timeStampIx] = true;
mTimeStamps[timeStampIx] = inHeader->nTimeStamp;
}
}
{
ivd_video_decode_ip_t s_dec_ip;
ivd_video_decode_op_t s_dec_op;
WORD32 timeDelay, timeTaken;
size_t sizeY, sizeUV;
if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) {
ALOGE("Decoder arg setup failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
GETTIME(&mTimeStart, NULL);
/* Compute time elapsed between end of previous decode()
* to start of current decode() */
TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
IV_API_CALL_STATUS_T status;
status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF));
GETTIME(&mTimeEnd, NULL);
/* Compute time taken for decode() */
TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
ALOGV("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
s_dec_op.u4_num_bytes_consumed);
if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) {
mFlushNeeded = true;
}
if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) {
/* If the input did not contain picture data, then ignore
* the associated timestamp */
mTimeStampsValid[timeStampIx] = false;
}
if (mChangingResolution && !s_dec_op.u4_output_present) {
mChangingResolution = false;
resetDecoder();
resetPlugin();
continue;
}
if (resChanged) {
mChangingResolution = true;
if (mFlushNeeded) {
setFlushMode();
}
continue;
}
if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) {
uint32_t width = s_dec_op.u4_pic_wd;
uint32_t height = s_dec_op.u4_pic_ht;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
resetDecoder();
return;
}
}
if (s_dec_op.u4_output_present) {
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts];
mTimeStampsValid[s_dec_op.u4_ts] = false;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
} else {
/* If in flush mode and no output is returned by the codec,
* then come out of flush mode */
mIsInFlush = false;
/* If EOS was recieved on input port and there is no output
* from the codec, then signal EOS on output port */
if (mReceivedEOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags |= OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
resetPlugin();
}
}
}
if (inHeader != NULL) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
}
| 174,181 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext)
{
SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
info->num_memslots = NUM_MEMSLOTS;
info->num_memslots_groups = NUM_MEMSLOTS_GROUPS;
info->internal_groupslot_id = 0;
info->qxl_ram_size = ssd->bufsize;
info->n_surfaces = ssd->num_surfaces;
}
Commit Message:
CWE ID: CWE-200 | static int interface_get_command(QXLInstance *sin, struct QXLCommandExt *ext)
{
SimpleSpiceDisplay *ssd = container_of(sin, SimpleSpiceDisplay, qxl);
info->num_memslots = NUM_MEMSLOTS;
info->num_memslots_groups = NUM_MEMSLOTS_GROUPS;
info->internal_groupslot_id = 0;
info->qxl_ram_size = 16 * 1024 * 1024;
info->n_surfaces = ssd->num_surfaces;
}
| 165,150 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: XSLStyleSheet::XSLStyleSheet(XSLImportRule* parentRule, const String& originalURL, const KURL& finalURL)
: m_ownerNode(0)
, m_originalURL(originalURL)
, m_finalURL(finalURL)
, m_isDisabled(false)
, m_embedded(false)
, m_processed(false) // Child sheets get marked as processed when the libxslt engine has finally seen them.
, m_stylesheetDoc(0)
, m_stylesheetDocTaken(false)
, m_parentStyleSheet(parentRule ? parentRule->parentStyleSheet() : 0)
{
}
Commit Message: Avoid reparsing an XSLT stylesheet after the first failure.
Certain libxslt versions appear to leave the doc in an invalid state when parsing fails. We should cache this result and avoid re-parsing.
(The test cannot be converted to text-only due to its invalid stylesheet).
[email protected],[email protected],[email protected]
BUG=271939
Review URL: https://chromiumcodereview.appspot.com/23103007
git-svn-id: svn://svn.chromium.org/blink/trunk@156248 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | XSLStyleSheet::XSLStyleSheet(XSLImportRule* parentRule, const String& originalURL, const KURL& finalURL)
: m_ownerNode(0)
, m_originalURL(originalURL)
, m_finalURL(finalURL)
, m_isDisabled(false)
, m_embedded(false)
, m_processed(false) // Child sheets get marked as processed when the libxslt engine has finally seen them.
, m_stylesheetDoc(0)
, m_stylesheetDocTaken(false)
, m_compilationFailed(false)
, m_parentStyleSheet(parentRule ? parentRule->parentStyleSheet() : 0)
{
}
| 171,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: explicit MountState(DriveFsHost* host)
: host_(host),
mojo_connection_delegate_(
host_->delegate_->CreateMojoConnectionDelegate()),
pending_token_(base::UnguessableToken::Create()),
binding_(this) {
source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()});
std::string datadir_option = base::StrCat(
{"datadir=",
host_->profile_path_.Append(kDataPath)
.Append(host_->delegate_->GetAccountId().GetAccountIdKey())
.value()});
chromeos::disks::DiskMountManager::GetInstance()->MountPath(
source_path_, "",
base::StrCat(
{"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}),
{datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE,
chromeos::MOUNT_ACCESS_MODE_READ_WRITE);
auto bootstrap =
mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection());
mojom::DriveFsDelegatePtr delegate;
binding_.Bind(mojo::MakeRequest(&delegate));
bootstrap->Init(
{base::in_place, host_->delegate_->GetAccountId().GetUserEmail()},
mojo::MakeRequest(&drivefs_), std::move(delegate));
PendingConnectionManager::Get().ExpectOpenIpcChannel(
pending_token_,
base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection,
base::Unretained(this)));
}
Commit Message: Add a fake DriveFS launcher client.
Using DriveFS requires building and deploying ChromeOS. Add a client for
the fake DriveFS launcher to allow the use of a real DriveFS from a
ChromeOS chroot to be used with a target_os="chromeos" build of chrome.
This connects to the fake DriveFS launcher using mojo over a unix domain
socket named by a command-line flag, using the launcher to create
DriveFS instances.
Bug: 848126
Change-Id: I22dcca154d41bda196dd7c1782bb503f6bcba5b1
Reviewed-on: https://chromium-review.googlesource.com/1098434
Reviewed-by: Xiyuan Xia <[email protected]>
Commit-Queue: Sam McNally <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567513}
CWE ID: | explicit MountState(DriveFsHost* host)
: host_(host),
mojo_connection_delegate_(
host_->delegate_->CreateMojoConnectionDelegate()),
pending_token_(base::UnguessableToken::Create()),
binding_(this) {
source_path_ = base::StrCat({kMountScheme, pending_token_.ToString()});
std::string datadir_option = base::StrCat(
{"datadir=",
host_->profile_path_.Append(kDataPath)
.Append(host_->delegate_->GetAccountId().GetAccountIdKey())
.value()});
auto bootstrap =
mojo::MakeProxy(mojo_connection_delegate_->InitializeMojoConnection());
mojom::DriveFsDelegatePtr delegate;
binding_.Bind(mojo::MakeRequest(&delegate));
bootstrap->Init(
{base::in_place, host_->delegate_->GetAccountId().GetUserEmail()},
mojo::MakeRequest(&drivefs_), std::move(delegate));
PendingConnectionManager::Get().ExpectOpenIpcChannel(
pending_token_,
base::BindOnce(&DriveFsHost::MountState::AcceptMojoConnection,
base::Unretained(this)));
chromeos::disks::DiskMountManager::GetInstance()->MountPath(
source_path_, "",
base::StrCat(
{"drivefs-", host_->delegate_->GetAccountId().GetAccountIdKey()}),
{datadir_option}, chromeos::MOUNT_TYPE_NETWORK_STORAGE,
chromeos::MOUNT_ACCESS_MODE_READ_WRITE);
}
| 171,729 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MountLibrary* CrosLibrary::GetMountLibrary() {
return mount_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | MountLibrary* CrosLibrary::GetMountLibrary() {
| 170,626 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: apr_status_t h2_stream_add_header(h2_stream *stream,
const char *name, size_t nlen,
const char *value, size_t vlen)
{
ap_assert(stream);
if (!stream->has_response) {
if (name[0] == ':') {
if ((vlen) > stream->session->s->limit_req_line) {
/* pseudo header: approximation of request line size check */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): pseudo header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_URI_TOO_LARGE);
}
}
else if ((nlen + 2 + vlen) > stream->session->s->limit_req_fieldsize) {
/* header too long */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): header %s too long",
stream->session->id, stream->id, name);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
if (name[0] != ':') {
++stream->request_headers_added;
if (stream->request_headers_added
> stream->session->s->limit_req_fields) {
/* too many header lines */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): too many header lines",
stream->session->id, stream->id);
return h2_stream_set_error(stream,
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
}
}
if (h2_stream_is_scheduled(stream)) {
return add_trailer(stream, name, nlen, value, vlen);
}
else {
if (!stream->rtmp) {
stream->rtmp = h2_req_create(stream->id, stream->pool,
NULL, NULL, NULL, NULL, NULL, 0);
}
if (stream->state != H2_STREAM_ST_OPEN) {
return APR_ECONNRESET;
}
return h2_request_add_header(stream->rtmp, stream->pool,
name, nlen, value, vlen);
}
}
Commit Message: SECURITY: CVE-2016-8740
mod_http2: properly crafted, endless HTTP/2 CONTINUATION frames could be used to exhaust all server's memory.
Reported by: Naveen Tiwari <[email protected]> and CDF/SEFCOM at Arizona State University
git-svn-id: https://svn.apache.org/repos/asf/httpd/httpd/trunk@1772576 13f79535-47bb-0310-9956-ffa450edef68
CWE ID: CWE-20 | apr_status_t h2_stream_add_header(h2_stream *stream,
const char *name, size_t nlen,
const char *value, size_t vlen)
{
int error = 0;
ap_assert(stream);
if (stream->has_response) {
return APR_EINVAL;
}
++stream->request_headers_added;
if (name[0] == ':') {
if ((vlen) > stream->session->s->limit_req_line) {
/* pseudo header: approximation of request line size check */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): pseudo header %s too long",
stream->session->id, stream->id, name);
error = HTTP_REQUEST_URI_TOO_LARGE;
}
}
else if ((nlen + 2 + vlen) > stream->session->s->limit_req_fieldsize) {
/* header too long */
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): header %s too long",
stream->session->id, stream->id, name);
error = HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
}
if (stream->request_headers_added
> stream->session->s->limit_req_fields + 4) {
/* too many header lines, include 4 pseudo headers */
if (stream->request_headers_added
> stream->session->s->limit_req_fields + 4 + 100) {
/* yeah, right */
return APR_ECONNRESET;
}
ap_log_cerror(APLOG_MARK, APLOG_TRACE1, 0, stream->session->c,
"h2_stream(%ld-%d): too many header lines",
stream->session->id, stream->id);
error = HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE;
}
if (h2_stream_is_scheduled(stream)) {
return add_trailer(stream, name, nlen, value, vlen);
}
else if (error) {
return h2_stream_set_error(stream, error);
}
else {
if (!stream->rtmp) {
stream->rtmp = h2_req_create(stream->id, stream->pool,
NULL, NULL, NULL, NULL, NULL, 0);
}
if (stream->state != H2_STREAM_ST_OPEN) {
return APR_ECONNRESET;
}
return h2_request_add_header(stream->rtmp, stream->pool,
name, nlen, value, vlen);
}
}
| 166,904 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Cluster* Segment::GetFirst() const
{
if ((m_clusters == NULL) || (m_clusterCount <= 0))
return &m_eos;
Cluster* const pCluster = m_clusters[0];
assert(pCluster);
return pCluster;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Cluster* Segment::GetFirst() const
Cluster* const pCluster = m_clusters[0];
assert(pCluster);
return pCluster;
}
| 174,322 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {
RFlagsAtOffset *flags = NULL;
RFlagsAtOffset key;
key.off = off;
if (dir >= 0) {
flags = r_skiplist_get_geq (f->by_off, &key);
} else {
flags = r_skiplist_get_leq (f->by_off, &key);
}
if (dir == 0 && flags && flags->off != off) {
return NULL;
}
return flags;
}
Commit Message: Fix crash in wasm disassembler
CWE ID: CWE-125 | static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {
static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) {
RFlagsAtOffset *flags = NULL;
RFlagsAtOffset key;
key.off = off;
if (dir >= 0) {
flags = r_skiplist_get_geq (f->by_off, &key);
} else {
flags = r_skiplist_get_leq (f->by_off, &key);
}
if (dir == 0 && flags && flags->off != off) {
return NULL;
}
return flags;
}
| 167,723 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: uint32_t _WM_SetupMidiEvent(struct _mdi *mdi, uint8_t * event_data, uint8_t running_event) {
/*
Only add standard MIDI and Sysex events in here.
Non-standard events need to be handled by calling function
to avoid compatibility issues.
TODO:
Add value limit checks
*/
uint32_t ret_cnt = 0;
uint8_t command = 0;
uint8_t channel = 0;
uint8_t data_1 = 0;
uint8_t data_2 = 0;
char *text = NULL;
if (event_data[0] >= 0x80) {
command = *event_data & 0xf0;
channel = *event_data++ & 0x0f;
ret_cnt++;
} else {
command = running_event & 0xf0;
channel = running_event & 0x0f;
}
switch(command) {
case 0x80:
_SETUP_NOTEOFF:
data_1 = *event_data++;
data_2 = *event_data++;
_WM_midi_setup_noteoff(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0x90:
if (event_data[1] == 0) goto _SETUP_NOTEOFF; /* A velocity of 0 in a note on is actually a note off */
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_noteon(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xa0:
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_aftertouch(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xb0:
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_control(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xc0:
data_1 = *event_data++;
midi_setup_patch(mdi, channel, data_1);
ret_cnt++;
break;
case 0xd0:
data_1 = *event_data++;
midi_setup_channel_pressure(mdi, channel, data_1);
ret_cnt++;
break;
case 0xe0:
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_pitch(mdi, channel, ((data_2 << 7) | (data_1 & 0x7f)));
ret_cnt += 2;
break;
case 0xf0:
if (channel == 0x0f) {
/*
MIDI Meta Events
*/
uint32_t tmp_length = 0;
if ((event_data[0] == 0x00) && (event_data[1] == 0x02)) {
/*
Sequence Number
We only setting this up here for WM_Event2Midi function
*/
midi_setup_sequenceno(mdi, ((event_data[2] << 8) + event_data[3]));
ret_cnt += 4;
} else if (event_data[0] == 0x01) {
/* Text Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_text(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x02) {
/* Copyright Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
/* Copy copyright info in the getinfo struct */
if (mdi->extra_info.copyright) {
mdi->extra_info.copyright = realloc(mdi->extra_info.copyright,(strlen(mdi->extra_info.copyright) + 1 + tmp_length + 1));
memcpy(&mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1], event_data, tmp_length);
mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1 + tmp_length] = '\0';
mdi->extra_info.copyright[strlen(mdi->extra_info.copyright)] = '\n';
} else {
mdi->extra_info.copyright = malloc(tmp_length + 1);
memcpy(mdi->extra_info.copyright, event_data, tmp_length);
mdi->extra_info.copyright[tmp_length] = '\0';
}
/* NOTE: free'd when events are cleared during closure of mdi */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_copyright(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x03) {
/* Track Name Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_trackname(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x04) {
/* Instrument Name Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_instrumentname(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x05) {
/* Lyric Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_lyric(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x06) {
/* Marker Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_marker(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x07) {
/* Cue Point Event */
/* Get Length */
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_cuepoint(mdi, text);
ret_cnt += tmp_length;
} else if ((event_data[0] == 0x20) && (event_data[1] == 0x01)) {
/*
Channel Prefix
We only setting this up here for WM_Event2Midi function
*/
midi_setup_channelprefix(mdi, event_data[2]);
ret_cnt += 3;
} else if ((event_data[0] == 0x21) && (event_data[1] == 0x01)) {
/*
Port Prefix
We only setting this up here for WM_Event2Midi function
*/
midi_setup_portprefix(mdi, event_data[2]);
ret_cnt += 3;
} else if ((event_data[0] == 0x2F) && (event_data[1] == 0x00)) {
/*
End of Track
Deal with this inside calling function
We only setting this up here for _WM_Event2Midi function
*/
_WM_midi_setup_endoftrack(mdi);
ret_cnt += 2;
} else if ((event_data[0] == 0x51) && (event_data[1] == 0x03)) {
/*
Tempo
Deal with this inside calling function.
We only setting this up here for _WM_Event2Midi function
*/
_WM_midi_setup_tempo(mdi, ((event_data[2] << 16) + (event_data[3] << 8) + event_data[4]));
ret_cnt += 5;
} else if ((event_data[0] == 0x54) && (event_data[1] == 0x05)) {
/*
SMPTE Offset
We only setting this up here for WM_Event2Midi function
*/
midi_setup_smpteoffset(mdi, ((event_data[3] << 24) + (event_data[4] << 16) + (event_data[5] << 8) + event_data[6]));
/*
Because this has 5 bytes of data we gonna "hack" it a little
*/
mdi->events[mdi->events_size - 1].event_data.channel = event_data[2];
ret_cnt += 7;
} else if ((event_data[0] == 0x58) && (event_data[1] == 0x04)) {
/*
Time Signature
We only setting this up here for WM_Event2Midi function
*/
midi_setup_timesignature(mdi, ((event_data[2] << 24) + (event_data[3] << 16) + (event_data[4] << 8) + event_data[5]));
ret_cnt += 6;
} else if ((event_data[0] == 0x59) && (event_data[1] == 0x02)) {
/*
Key Signature
We only setting this up here for WM_Event2Midi function
*/
midi_setup_keysignature(mdi, ((event_data[2] << 8) + event_data[3]));
ret_cnt += 4;
} else {
/*
Unsupported Meta Event
*/
event_data++;
ret_cnt++;
if (*event_data > 0x7f) {
do {
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
ret_cnt++;
ret_cnt += tmp_length;
}
} else if ((channel == 0) || (channel == 7)) {
/*
Sysex Events
*/
uint32_t sysex_len = 0;
uint8_t *sysex_store = NULL;
if (*event_data > 0x7f) {
do {
sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
event_data++;
ret_cnt++;
} while (*event_data > 0x7f);
}
sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
event_data++;
if (!sysex_len) break;
ret_cnt++;
sysex_store = malloc(sizeof(uint8_t) * sysex_len);
memcpy(sysex_store, event_data, sysex_len);
if (sysex_store[sysex_len - 1] == 0xF7) {
uint8_t rolandsysexid[] = { 0x41, 0x10, 0x42, 0x12 };
if (memcmp(rolandsysexid, sysex_store, 4) == 0) {
/* For Roland Sysex Messages */
/* checksum */
uint8_t sysex_cs = 0;
uint32_t sysex_ofs = 4;
do {
sysex_cs += sysex_store[sysex_ofs];
if (sysex_cs > 0x7F) {
sysex_cs -= 0x80;
}
sysex_ofs++;
} while (sysex_store[sysex_ofs + 1] != 0xf7);
sysex_cs = 128 - sysex_cs;
/* is roland sysex message valid */
if (sysex_cs == sysex_store[sysex_ofs]) {
/* process roland sysex event */
if (sysex_store[4] == 0x40) {
if (((sysex_store[5] & 0xf0) == 0x10) && (sysex_store[6] == 0x15)) {
/* Roland Drum Track Setting */
uint8_t sysex_ch = 0x0f & sysex_store[5];
if (sysex_ch == 0x00) {
sysex_ch = 0x09;
} else if (sysex_ch <= 0x09) {
sysex_ch -= 1;
}
midi_setup_sysex_roland_drum_track(mdi, sysex_ch, sysex_store[7]);
} else if ((sysex_store[5] == 0x00) && (sysex_store[6] == 0x7F) && (sysex_store[7] == 0x00)) {
/* Roland GS Reset */
midi_setup_sysex_roland_reset(mdi);
}
}
}
} else {
/* For non-Roland Sysex Messages */
uint8_t gm_reset[] = {0x7e, 0x7f, 0x09, 0x01, 0xf7};
uint8_t yamaha_reset[] = {0x43, 0x10, 0x4c, 0x00, 0x00, 0x7e, 0x00, 0xf7};
if (memcmp(gm_reset, sysex_store, 5) == 0) {
/* GM Reset */
midi_setup_sysex_gm_reset(mdi);
} else if (memcmp(yamaha_reset,sysex_store,8) == 0) {
/* Yamaha Reset */
midi_setup_sysex_yamaha_reset(mdi);
}
}
}
free(sysex_store);
sysex_store = NULL;
/*
event_data += sysex_len;
*/
ret_cnt += sysex_len;
} else {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(unrecognized meta type event)", 0);
return 0;
}
break;
default: /* Should NEVER get here */
ret_cnt = 0;
break;
}
if (ret_cnt == 0)
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing event)", 0);
return ret_cnt;
}
Commit Message: Add a new size parameter to _WM_SetupMidiEvent() so that it knows
where to stop reading, and adjust its users properly. Fixes bug #175
(CVE-2017-11661, CVE-2017-11662, CVE-2017-11663, CVE-2017-11664.)
CWE ID: CWE-125 | uint32_t _WM_SetupMidiEvent(struct _mdi *mdi, uint8_t * event_data, uint8_t running_event) {
uint32_t _WM_SetupMidiEvent(struct _mdi *mdi, uint8_t * event_data, uint32_t siz, uint8_t running_event) {
/*
Only add standard MIDI and Sysex events in here.
Non-standard events need to be handled by calling function
to avoid compatibility issues.
TODO:
Add value limit checks
*/
uint32_t ret_cnt = 0;
uint8_t command = 0;
uint8_t channel = 0;
uint8_t data_1 = 0;
uint8_t data_2 = 0;
char *text = NULL;
if (!siz) goto shortbuf;
if (event_data[0] >= 0x80) {
command = *event_data & 0xf0;
channel = *event_data++ & 0x0f;
ret_cnt++;
if (--siz == 0) goto shortbuf;
} else {
command = running_event & 0xf0;
channel = running_event & 0x0f;
}
switch(command) {
case 0x80:
_SETUP_NOTEOFF:
if (siz < 2) goto shortbuf;
data_1 = *event_data++;
data_2 = *event_data++;
_WM_midi_setup_noteoff(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0x90:
if (event_data[1] == 0) goto _SETUP_NOTEOFF; /* A velocity of 0 in a note on is actually a note off */
if (siz < 2) goto shortbuf;
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_noteon(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xa0:
if (siz < 2) goto shortbuf;
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_aftertouch(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xb0:
if (siz < 2) goto shortbuf;
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_control(mdi, channel, data_1, data_2);
ret_cnt += 2;
break;
case 0xc0:
data_1 = *event_data++;
midi_setup_patch(mdi, channel, data_1);
ret_cnt++;
break;
case 0xd0:
data_1 = *event_data++;
midi_setup_channel_pressure(mdi, channel, data_1);
ret_cnt++;
break;
case 0xe0:
if (siz < 2) goto shortbuf;
data_1 = *event_data++;
data_2 = *event_data++;
midi_setup_pitch(mdi, channel, ((data_2 << 7) | (data_1 & 0x7f)));
ret_cnt += 2;
break;
case 0xf0:
if (channel == 0x0f) {
/*
MIDI Meta Events
*/
uint32_t tmp_length = 0;
if ((event_data[0] == 0x00) && (event_data[1] == 0x02)) {
/*
Sequence Number
We only setting this up here for WM_Event2Midi function
*/
if (siz < 4) goto shortbuf;
midi_setup_sequenceno(mdi, ((event_data[2] << 8) + event_data[3]));
ret_cnt += 4;
} else if (event_data[0] == 0x01) {
/* Text Event */
/* Get Length */
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
if (--siz < tmp_length) goto shortbuf;
if (!tmp_length) break; /* bad file? */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_text(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x02) {
/* Copyright Event */
/* Get Length */
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
if (--siz < tmp_length) goto shortbuf;
if (!tmp_length) break; /* bad file? */
/* Copy copyright info in the getinfo struct */
if (mdi->extra_info.copyright) {
mdi->extra_info.copyright = realloc(mdi->extra_info.copyright,(strlen(mdi->extra_info.copyright) + 1 + tmp_length + 1));
memcpy(&mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1], event_data, tmp_length);
mdi->extra_info.copyright[strlen(mdi->extra_info.copyright) + 1 + tmp_length] = '\0';
mdi->extra_info.copyright[strlen(mdi->extra_info.copyright)] = '\n';
} else {
mdi->extra_info.copyright = malloc(tmp_length + 1);
memcpy(mdi->extra_info.copyright, event_data, tmp_length);
mdi->extra_info.copyright[tmp_length] = '\0';
}
/* NOTE: free'd when events are cleared during closure of mdi */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_copyright(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x03) {
/* Track Name Event */
/* Get Length */
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
if (--siz < tmp_length) goto shortbuf;
if (!tmp_length) break; /* bad file? */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_trackname(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x04) {
/* Instrument Name Event */
/* Get Length */
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
if (--siz < tmp_length) goto shortbuf;
if (!tmp_length) break; /* bad file? */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_instrumentname(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x05) {
/* Lyric Event */
/* Get Length */
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
if (--siz < tmp_length) goto shortbuf;
if (!tmp_length) break; /* bad file? */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_lyric(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x06) {
/* Marker Event */
/* Get Length */
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
if (--siz < tmp_length) goto shortbuf;
if (!tmp_length) break; /* bad file? */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_marker(mdi, text);
ret_cnt += tmp_length;
} else if (event_data[0] == 0x07) {
/* Cue Point Event */
/* Get Length */
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
ret_cnt++;
if (--siz < tmp_length) goto shortbuf;
if (!tmp_length) break; /* bad file? */
text = malloc(tmp_length + 1);
memcpy(text, event_data, tmp_length);
text[tmp_length] = '\0';
midi_setup_cuepoint(mdi, text);
ret_cnt += tmp_length;
} else if ((event_data[0] == 0x20) && (event_data[1] == 0x01)) {
/*
Channel Prefix
We only setting this up here for WM_Event2Midi function
*/
if (siz < 3) goto shortbuf;
midi_setup_channelprefix(mdi, event_data[2]);
ret_cnt += 3;
} else if ((event_data[0] == 0x21) && (event_data[1] == 0x01)) {
/*
Port Prefix
We only setting this up here for WM_Event2Midi function
*/
if (siz < 3) goto shortbuf;
midi_setup_portprefix(mdi, event_data[2]);
ret_cnt += 3;
} else if ((event_data[0] == 0x2F) && (event_data[1] == 0x00)) {
/*
End of Track
Deal with this inside calling function
We only setting this up here for _WM_Event2Midi function
*/
if (siz < 2) goto shortbuf;
_WM_midi_setup_endoftrack(mdi);
ret_cnt += 2;
} else if ((event_data[0] == 0x51) && (event_data[1] == 0x03)) {
/*
Tempo
Deal with this inside calling function.
We only setting this up here for _WM_Event2Midi function
*/
if (siz < 5) goto shortbuf;
_WM_midi_setup_tempo(mdi, ((event_data[2] << 16) + (event_data[3] << 8) + event_data[4]));
ret_cnt += 5;
} else if ((event_data[0] == 0x54) && (event_data[1] == 0x05)) {
if (siz < 7) goto shortbuf;
/*
SMPTE Offset
We only setting this up here for WM_Event2Midi function
*/
midi_setup_smpteoffset(mdi, ((event_data[3] << 24) + (event_data[4] << 16) + (event_data[5] << 8) + event_data[6]));
/*
Because this has 5 bytes of data we gonna "hack" it a little
*/
mdi->events[mdi->events_size - 1].event_data.channel = event_data[2];
ret_cnt += 7;
} else if ((event_data[0] == 0x58) && (event_data[1] == 0x04)) {
/*
Time Signature
We only setting this up here for WM_Event2Midi function
*/
if (siz < 6) goto shortbuf;
midi_setup_timesignature(mdi, ((event_data[2] << 24) + (event_data[3] << 16) + (event_data[4] << 8) + event_data[5]));
ret_cnt += 6;
} else if ((event_data[0] == 0x59) && (event_data[1] == 0x02)) {
/*
Key Signature
We only setting this up here for WM_Event2Midi function
*/
if (siz < 4) goto shortbuf;
midi_setup_keysignature(mdi, ((event_data[2] << 8) + event_data[3]));
ret_cnt += 4;
} else {
/*
Unsupported Meta Event
*/
event_data++;
ret_cnt++;
if (--siz && *event_data > 0x7f) {
do {
if (!siz) break;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
tmp_length = (tmp_length << 7) + (*event_data & 0x7f);
ret_cnt++;
ret_cnt += tmp_length;
if (--siz < tmp_length) goto shortbuf;
}
} else if ((channel == 0) || (channel == 7)) {
/*
Sysex Events
*/
uint32_t sysex_len = 0;
uint8_t *sysex_store = NULL;
if (*event_data > 0x7f) {
do {
if (!siz) break;
sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
event_data++;
siz--;
ret_cnt++;
} while (*event_data > 0x7f);
}
if (!siz) goto shortbuf;
sysex_len = (sysex_len << 7) + (*event_data & 0x7F);
event_data++;
ret_cnt++;
if (--siz < sysex_len) goto shortbuf;
if (!sysex_len) break; /* bad file? */
sysex_store = malloc(sizeof(uint8_t) * sysex_len);
memcpy(sysex_store, event_data, sysex_len);
if (sysex_store[sysex_len - 1] == 0xF7) {
uint8_t rolandsysexid[] = { 0x41, 0x10, 0x42, 0x12 };
if (memcmp(rolandsysexid, sysex_store, 4) == 0) {
/* For Roland Sysex Messages */
/* checksum */
uint8_t sysex_cs = 0;
uint32_t sysex_ofs = 4;
do {
sysex_cs += sysex_store[sysex_ofs];
if (sysex_cs > 0x7F) {
sysex_cs -= 0x80;
}
sysex_ofs++;
} while (sysex_store[sysex_ofs + 1] != 0xf7);
sysex_cs = 128 - sysex_cs;
/* is roland sysex message valid */
if (sysex_cs == sysex_store[sysex_ofs]) {
/* process roland sysex event */
if (sysex_store[4] == 0x40) {
if (((sysex_store[5] & 0xf0) == 0x10) && (sysex_store[6] == 0x15)) {
/* Roland Drum Track Setting */
uint8_t sysex_ch = 0x0f & sysex_store[5];
if (sysex_ch == 0x00) {
sysex_ch = 0x09;
} else if (sysex_ch <= 0x09) {
sysex_ch -= 1;
}
midi_setup_sysex_roland_drum_track(mdi, sysex_ch, sysex_store[7]);
} else if ((sysex_store[5] == 0x00) && (sysex_store[6] == 0x7F) && (sysex_store[7] == 0x00)) {
/* Roland GS Reset */
midi_setup_sysex_roland_reset(mdi);
}
}
}
} else {
/* For non-Roland Sysex Messages */
uint8_t gm_reset[] = {0x7e, 0x7f, 0x09, 0x01, 0xf7};
uint8_t yamaha_reset[] = {0x43, 0x10, 0x4c, 0x00, 0x00, 0x7e, 0x00, 0xf7};
if (memcmp(gm_reset, sysex_store, 5) == 0) {
/* GM Reset */
midi_setup_sysex_gm_reset(mdi);
} else if (memcmp(yamaha_reset,sysex_store,8) == 0) {
/* Yamaha Reset */
midi_setup_sysex_yamaha_reset(mdi);
}
}
}
free(sysex_store);
sysex_store = NULL;
/*
event_data += sysex_len;
*/
ret_cnt += sysex_len;
} else {
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(unrecognized meta type event)", 0);
return 0;
}
break;
default: /* Should NEVER get here */
ret_cnt = 0;
break;
}
if (ret_cnt == 0)
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(missing event)", 0);
return ret_cnt;
shortbuf:
_WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_CORUPT, "(too short)", 0);
return 0;
}
| 168,007 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: _XcursorReadImage (XcursorFile *file,
XcursorFileHeader *fileHeader,
int toc)
{
XcursorChunkHeader chunkHeader;
XcursorImage head;
XcursorImage *image;
int n;
XcursorPixel *p;
if (!file || !fileHeader)
return NULL;
if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader))
return NULL;
if (!_XcursorReadUInt (file, &head.width))
return NULL;
if (!_XcursorReadUInt (file, &head.height))
return NULL;
if (!_XcursorReadUInt (file, &head.xhot))
return NULL;
if (!_XcursorReadUInt (file, &head.yhot))
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width >= 0x10000 || head.height > 0x10000)
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width >= 0x10000 || head.height > 0x10000)
return NULL;
if (head.width == 0 || head.height == 0)
return NULL;
return NULL;
if (chunkHeader.version < image->version)
image->version = chunkHeader.version;
image->size = chunkHeader.subtype;
image->xhot = head.xhot;
image->yhot = head.yhot;
image->delay = head.delay;
n = image->width * image->height;
p = image->pixels;
while (n--)
{
if (!_XcursorReadUInt (file, p))
{
XcursorImageDestroy (image);
return NULL;
}
p++;
}
return image;
}
Commit Message:
CWE ID: CWE-190 | _XcursorReadImage (XcursorFile *file,
XcursorFileHeader *fileHeader,
int toc)
{
XcursorChunkHeader chunkHeader;
XcursorImage head;
XcursorImage *image;
int n;
XcursorPixel *p;
if (!file || !fileHeader)
return NULL;
if (!_XcursorFileReadChunkHeader (file, fileHeader, toc, &chunkHeader))
return NULL;
if (!_XcursorReadUInt (file, &head.width))
return NULL;
if (!_XcursorReadUInt (file, &head.height))
return NULL;
if (!_XcursorReadUInt (file, &head.xhot))
return NULL;
if (!_XcursorReadUInt (file, &head.yhot))
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width >= 0x10000 || head.height > 0x10000)
return NULL;
if (!_XcursorReadUInt (file, &head.delay))
return NULL;
/* sanity check data */
if (head.width > XCURSOR_IMAGE_MAX_SIZE ||
head.height > XCURSOR_IMAGE_MAX_SIZE)
return NULL;
if (head.width == 0 || head.height == 0)
return NULL;
return NULL;
if (chunkHeader.version < image->version)
image->version = chunkHeader.version;
image->size = chunkHeader.subtype;
image->xhot = head.xhot;
image->yhot = head.yhot;
image->delay = head.delay;
n = image->width * image->height;
p = image->pixels;
while (n--)
{
if (!_XcursorReadUInt (file, p))
{
XcursorImageDestroy (image);
return NULL;
}
p++;
}
return image;
}
| 164,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void UtilityServiceFactory::RegisterServices(ServiceMap* services) {
GetContentClient()->utility()->RegisterServices(services);
service_manager::EmbeddedServiceInfo video_capture_info;
video_capture_info.factory = base::Bind(&CreateVideoCaptureService);
services->insert(
std::make_pair(video_capture::mojom::kServiceName, video_capture_info));
#if BUILDFLAG(ENABLE_PEPPER_CDMS)
service_manager::EmbeddedServiceInfo info;
info.factory = base::Bind(&CreateMediaService);
services->insert(std::make_pair(media::mojom::kMediaServiceName, info));
#endif
service_manager::EmbeddedServiceInfo shape_detection_info;
shape_detection_info.factory =
base::Bind(&shape_detection::ShapeDetectionService::Create);
services->insert(std::make_pair(shape_detection::mojom::kServiceName,
shape_detection_info));
service_manager::EmbeddedServiceInfo data_decoder_info;
data_decoder_info.factory = base::Bind(&CreateDataDecoderService);
services->insert(
std::make_pair(data_decoder::mojom::kServiceName, data_decoder_info));
if (base::FeatureList::IsEnabled(features::kNetworkService)) {
GetContentClient()->utility()->RegisterNetworkBinders(
network_registry_.get());
service_manager::EmbeddedServiceInfo network_info;
network_info.factory = base::Bind(
&UtilityServiceFactory::CreateNetworkService, base::Unretained(this));
network_info.task_runner = ChildProcess::current()->io_task_runner();
services->insert(
std::make_pair(content::mojom::kNetworkServiceName, network_info));
}
}
Commit Message: media: Support hosting mojo CDM in a standalone service
Currently when mojo CDM is enabled it is hosted in the MediaService
running in the process specified by "mojo_media_host". However, on
some platforms we need to run mojo CDM and other mojo media services in
different processes. For example, on desktop platforms, we want to run
mojo video decoder in the GPU process, but run the mojo CDM in the
utility process.
This CL adds a new build flag "enable_standalone_cdm_service". When
enabled, the mojo CDM service will be hosted in a standalone "cdm"
service running in the utility process. All other mojo media services
will sill be hosted in the "media" servie running in the process
specified by "mojo_media_host".
BUG=664364
TEST=Encrypted media browser tests using mojo CDM is still working.
Change-Id: I95be6e05adc9ebcff966b26958ef1d7becdfb487
Reviewed-on: https://chromium-review.googlesource.com/567172
Commit-Queue: Xiaohan Wang <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Dan Sanders <[email protected]>
Cr-Commit-Position: refs/heads/master@{#486947}
CWE ID: CWE-119 | void UtilityServiceFactory::RegisterServices(ServiceMap* services) {
GetContentClient()->utility()->RegisterServices(services);
service_manager::EmbeddedServiceInfo video_capture_info;
video_capture_info.factory = base::Bind(&CreateVideoCaptureService);
services->insert(
std::make_pair(video_capture::mojom::kServiceName, video_capture_info));
#if BUILDFLAG(ENABLE_PEPPER_CDMS)
service_manager::EmbeddedServiceInfo info;
info.factory = base::Bind(&CreateCdmService);
services->insert(std::make_pair(media::mojom::kCdmServiceName, info));
#endif
service_manager::EmbeddedServiceInfo shape_detection_info;
shape_detection_info.factory =
base::Bind(&shape_detection::ShapeDetectionService::Create);
services->insert(std::make_pair(shape_detection::mojom::kServiceName,
shape_detection_info));
service_manager::EmbeddedServiceInfo data_decoder_info;
data_decoder_info.factory = base::Bind(&CreateDataDecoderService);
services->insert(
std::make_pair(data_decoder::mojom::kServiceName, data_decoder_info));
if (base::FeatureList::IsEnabled(features::kNetworkService)) {
GetContentClient()->utility()->RegisterNetworkBinders(
network_registry_.get());
service_manager::EmbeddedServiceInfo network_info;
network_info.factory = base::Bind(
&UtilityServiceFactory::CreateNetworkService, base::Unretained(this));
network_info.task_runner = ChildProcess::current()->io_task_runner();
services->insert(
std::make_pair(content::mojom::kNetworkServiceName, network_info));
}
}
| 171,942 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: generate_row(png_bytep row, size_t rowbytes, unsigned int y, int color_type,
int bit_depth, png_const_bytep gamma_table, double conv,
unsigned int *colors)
{
png_uint_32 size_max = image_size_of_type(color_type, bit_depth, colors)-1;
png_uint_32 depth_max = (1U << bit_depth)-1; /* up to 65536 */
if (colors[0] == 0) switch (channels_of_type(color_type))
{
/* 1 channel: a square image with a diamond, the least luminous colors are on
* the edge of the image, the most luminous in the center.
*/
case 1:
{
png_uint_32 x;
png_uint_32 base = 2*size_max - abs(2*y-size_max);
for (x=0; x<=size_max; ++x)
{
png_uint_32 luma = base - abs(2*x-size_max);
/* 'luma' is now in the range 0..2*size_max, we need
* 0..depth_max
*/
luma = (luma*depth_max + size_max) / (2*size_max);
set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv);
}
}
break;
/* 2 channels: the color channel increases in luminosity from top to bottom,
* the alpha channel increases in opacity from left to right.
*/
case 2:
{
png_uint_32 alpha = (depth_max * y * 2 + size_max) / (2 * size_max);
png_uint_32 x;
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 2*x, bit_depth,
(depth_max * x * 2 + size_max) / (2 * size_max), gamma_table,
conv);
set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
conv);
}
}
break;
/* 3 channels: linear combinations of, from the top-left corner clockwise,
* black, green, white, red.
*/
case 3:
{
/* x0: the black->red scale (the value of the red component) at the
* start of the row (blue and green are 0).
* x1: the green->white scale (the value of the red and blue
* components at the end of the row; green is depth_max).
*/
png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
png_uint_32 x;
/* Interpolate x/depth_max from start to end:
*
* start end difference
* red: Y Y 0
* green: 0 depth_max depth_max
* blue: 0 Y Y
*/
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 3*x+0, bit_depth, /* red */ Y,
gamma_table, conv);
set_value(row, rowbytes, 3*x+1, bit_depth, /* green */
(depth_max * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 3*x+2, bit_depth, /* blue */
(Y * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
}
}
break;
/* 4 channels: linear combinations of, from the top-left corner clockwise,
* transparent, red, green, blue.
*/
case 4:
{
/* x0: the transparent->blue scale (the value of the blue and alpha
* components) at the start of the row (red and green are 0).
* x1: the red->green scale (the value of the red and green
* components at the end of the row; blue is 0 and alpha is
* depth_max).
*/
png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
png_uint_32 x;
/* Interpolate x/depth_max from start to end:
*
* start end difference
* red: 0 depth_max-Y depth_max-Y
* green: 0 Y Y
* blue: Y 0 -Y
* alpha: Y depth_max depth_max-Y
*/
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 4*x+0, bit_depth, /* red */
((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 4*x+1, bit_depth, /* green */
(Y * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 4*x+2, bit_depth, /* blue */
Y - (Y * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 4*x+3, bit_depth, /* alpha */
Y + ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
}
}
break;
default:
fprintf(stderr, "makepng: internal bad channel count\n");
exit(2);
}
else if (color_type & PNG_COLOR_MASK_PALETTE)
{
/* Palette with fixed color: the image rows are all 0 and the image width
* is 16.
*/
memset(row, 0, rowbytes);
}
else if (colors[0] == channels_of_type(color_type))
switch (channels_of_type(color_type))
{
case 1:
{
const png_uint_32 luma = colors[1];
png_uint_32 x;
for (x=0; x<=size_max; ++x)
set_value(row, rowbytes, x, bit_depth, luma, gamma_table,
conv);
}
break;
case 2:
{
const png_uint_32 luma = colors[1];
const png_uint_32 alpha = colors[2];
png_uint_32 x;
for (x=0; x<size_max; ++x)
{
set_value(row, rowbytes, 2*x, bit_depth, luma, gamma_table,
conv);
set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
conv);
}
}
break;
case 3:
{
const png_uint_32 red = colors[1];
const png_uint_32 green = colors[2];
const png_uint_32 blue = colors[3];
png_uint_32 x;
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 3*x+0, bit_depth, red, gamma_table,
conv);
set_value(row, rowbytes, 3*x+1, bit_depth, green, gamma_table,
conv);
set_value(row, rowbytes, 3*x+2, bit_depth, blue, gamma_table,
conv);
}
}
break;
case 4:
{
const png_uint_32 red = colors[1];
const png_uint_32 green = colors[2];
const png_uint_32 blue = colors[3];
const png_uint_32 alpha = colors[4];
png_uint_32 x;
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 4*x+0, bit_depth, red, gamma_table,
conv);
set_value(row, rowbytes, 4*x+1, bit_depth, green, gamma_table,
conv);
set_value(row, rowbytes, 4*x+2, bit_depth, blue, gamma_table,
conv);
set_value(row, rowbytes, 4*x+3, bit_depth, alpha, gamma_table,
conv);
}
}
break;
default:
fprintf(stderr, "makepng: internal bad channel count\n");
exit(2);
}
else
{
fprintf(stderr,
"makepng: --color: count(%u) does not match channels(%u)\n",
colors[0], channels_of_type(color_type));
exit(1);
}
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | generate_row(png_bytep row, size_t rowbytes, unsigned int y, int color_type,
int bit_depth, png_const_bytep gamma_table, double conv,
unsigned int *colors, int small)
{
int filters = 0; /* file *MASK*, 0 means the default, not NONE */
png_uint_32 size_max =
image_size_of_type(color_type, bit_depth, colors, small)-1;
png_uint_32 depth_max = (1U << bit_depth)-1; /* up to 65536 */
if (colors[0] == 0) if (small)
{
unsigned int pixel_depth = pixel_depth_of_type(color_type, bit_depth);
/* For pixel depths less than 16 generate a single row containing all the
* possible pixel values. For 16 generate all 65536 byte pair
* combinations in a 256x256 pixel array.
*/
switch (pixel_depth)
{
case 1:
assert(y == 0 && rowbytes == 1 && size_max == 1);
row[0] = 0x6CU; /* binary: 01101100, only top 2 bits used */
filters = PNG_FILTER_NONE;
break;
case 2:
assert(y == 0 && rowbytes == 1 && size_max == 3);
row[0] = 0x1BU; /* binary 00011011, all bits used */
filters = PNG_FILTER_NONE;
break;
case 4:
assert(y == 0 && rowbytes == 8 && size_max == 15);
row[0] = 0x01U;
row[1] = 0x23U; /* SUB gives 0x22U for all following bytes */
row[2] = 0x45U;
row[3] = 0x67U;
row[4] = 0x89U;
row[5] = 0xABU;
row[6] = 0xCDU;
row[7] = 0xEFU;
filters = PNG_FILTER_SUB;
break;
case 8:
/* The row will have all the pixel values in order starting with
* '1', the SUB filter will change every byte into '1' (including
* the last, which generates pixel value '0'). Since the SUB filter
* has value 1 this should result in maximum compression.
*/
assert(y == 0 && rowbytes == 256 && size_max == 255);
for (;;)
{
row[size_max] = 0xFFU & (size_max+1);
if (size_max == 0)
break;
--size_max;
}
filters = PNG_FILTER_SUB;
break;
case 16:
/* Rows are generated such that each row has a constant difference
* between the first and second byte of each pixel and so that the
* difference increases by 1 at each row. The rows start with the
* first byte value of 0 and the value increases to 255 across the
* row.
*
* The difference starts at 1, so the first row is:
*
* 0 1 1 2 2 3 3 4 ... 254 255 255 0
*
* This means that running the SUB filter on the first row produces:
*
* [SUB==1] 0 1 0 1 0 1...
*
* Then the difference is 2 on the next row, giving:
*
* 0 2 1 3 2 4 3 5 ... 254 0 255 1
*
* When the UP filter is run on this libpng produces:
*
* [UP ==2] 0 1 0 1 0 1...
*
* And so on for all the remain rows to the final two * rows:
*
* row 254: 0 255 1 0 2 1 3 2 4 3 ... 254 253 255 254
* row 255: 0 0 1 1 2 2 3 3 4 4 ... 254 254 255 255
*/
assert(rowbytes == 512 && size_max == 255);
for (;;)
{
row[2*size_max ] = 0xFFU & size_max;
row[2*size_max+1] = 0xFFU & (size_max+y+1);
if (size_max == 0)
break;
--size_max;
}
/* The first row must include PNG_FILTER_UP so that libpng knows we
* need to keep it for the following row:
*/
filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
break;
case 24:
case 32:
case 48:
case 64:
/* The rows are filled by an alogorithm similar to the above, in the
* first row pixel bytes are all equal, increasing from 0 by 1 for
* each pixel. In the second row the bytes within a pixel are
* incremented 1,3,5,7,... from the previous row byte. Using an odd
* number ensures all the possible byte values are used.
*/
assert(size_max == 255 && rowbytes == 256*(pixel_depth>>3));
pixel_depth >>= 3; /* now in bytes */
while (rowbytes > 0)
{
const size_t pixel_index = --rowbytes/pixel_depth;
if (y == 0)
row[rowbytes] = 0xFFU & pixel_index;
else
{
const size_t byte_offset =
rowbytes - pixel_index * pixel_depth;
row[rowbytes] =
0xFFU & (pixel_index + (byte_offset * 2*y) + 1);
}
}
filters = (y == 0 ? PNG_FILTER_SUB+PNG_FILTER_UP : PNG_FILTER_UP);
break;
default:
assert(0/*NOT REACHED*/);
}
}
else switch (channels_of_type(color_type))
{
/* 1 channel: a square image with a diamond, the least luminous colors are on
* the edge of the image, the most luminous in the center.
*/
case 1:
{
png_uint_32 x;
png_uint_32 base = 2*size_max - abs(2*y-size_max);
for (x=0; x<=size_max; ++x)
{
png_uint_32 luma = base - abs(2*x-size_max);
/* 'luma' is now in the range 0..2*size_max, we need
* 0..depth_max
*/
luma = (luma*depth_max + size_max) / (2*size_max);
set_value(row, rowbytes, x, bit_depth, luma, gamma_table, conv);
}
}
break;
/* 2 channels: the color channel increases in luminosity from top to bottom,
* the alpha channel increases in opacity from left to right.
*/
case 2:
{
png_uint_32 alpha = (depth_max * y * 2 + size_max) / (2 * size_max);
png_uint_32 x;
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 2*x, bit_depth,
(depth_max * x * 2 + size_max) / (2 * size_max), gamma_table,
conv);
set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
conv);
}
}
break;
/* 3 channels: linear combinations of, from the top-left corner clockwise,
* black, green, white, red.
*/
case 3:
{
/* x0: the black->red scale (the value of the red component) at the
* start of the row (blue and green are 0).
* x1: the green->white scale (the value of the red and blue
* components at the end of the row; green is depth_max).
*/
png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
png_uint_32 x;
/* Interpolate x/depth_max from start to end:
*
* start end difference
* red: Y Y 0
* green: 0 depth_max depth_max
* blue: 0 Y Y
*/
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 3*x+0, bit_depth, /* red */ Y,
gamma_table, conv);
set_value(row, rowbytes, 3*x+1, bit_depth, /* green */
(depth_max * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 3*x+2, bit_depth, /* blue */
(Y * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
}
}
break;
/* 4 channels: linear combinations of, from the top-left corner clockwise,
* transparent, red, green, blue.
*/
case 4:
{
/* x0: the transparent->blue scale (the value of the blue and alpha
* components) at the start of the row (red and green are 0).
* x1: the red->green scale (the value of the red and green
* components at the end of the row; blue is 0 and alpha is
* depth_max).
*/
png_uint_32 Y = (depth_max * y * 2 + size_max) / (2 * size_max);
png_uint_32 x;
/* Interpolate x/depth_max from start to end:
*
* start end difference
* red: 0 depth_max-Y depth_max-Y
* green: 0 Y Y
* blue: Y 0 -Y
* alpha: Y depth_max depth_max-Y
*/
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 4*x+0, bit_depth, /* red */
((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 4*x+1, bit_depth, /* green */
(Y * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 4*x+2, bit_depth, /* blue */
Y - (Y * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
set_value(row, rowbytes, 4*x+3, bit_depth, /* alpha */
Y + ((depth_max-Y) * x * 2 + size_max) / (2 * size_max),
gamma_table, conv);
}
}
break;
default:
fprintf(stderr, "makepng: internal bad channel count\n");
exit(2);
}
else if (color_type & PNG_COLOR_MASK_PALETTE)
{
/* Palette with fixed color: the image rows are all 0 and the image width
* is 16.
*/
memset(row, 0, rowbytes);
}
else if (colors[0] == channels_of_type(color_type))
switch (channels_of_type(color_type))
{
case 1:
{
const png_uint_32 luma = colors[1];
png_uint_32 x;
for (x=0; x<=size_max; ++x)
set_value(row, rowbytes, x, bit_depth, luma, gamma_table,
conv);
}
break;
case 2:
{
const png_uint_32 luma = colors[1];
const png_uint_32 alpha = colors[2];
png_uint_32 x;
for (x=0; x<size_max; ++x)
{
set_value(row, rowbytes, 2*x, bit_depth, luma, gamma_table,
conv);
set_value(row, rowbytes, 2*x+1, bit_depth, alpha, gamma_table,
conv);
}
}
break;
case 3:
{
const png_uint_32 red = colors[1];
const png_uint_32 green = colors[2];
const png_uint_32 blue = colors[3];
png_uint_32 x;
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 3*x+0, bit_depth, red, gamma_table,
conv);
set_value(row, rowbytes, 3*x+1, bit_depth, green, gamma_table,
conv);
set_value(row, rowbytes, 3*x+2, bit_depth, blue, gamma_table,
conv);
}
}
break;
case 4:
{
const png_uint_32 red = colors[1];
const png_uint_32 green = colors[2];
const png_uint_32 blue = colors[3];
const png_uint_32 alpha = colors[4];
png_uint_32 x;
for (x=0; x<=size_max; ++x)
{
set_value(row, rowbytes, 4*x+0, bit_depth, red, gamma_table,
conv);
set_value(row, rowbytes, 4*x+1, bit_depth, green, gamma_table,
conv);
set_value(row, rowbytes, 4*x+2, bit_depth, blue, gamma_table,
conv);
set_value(row, rowbytes, 4*x+3, bit_depth, alpha, gamma_table,
conv);
}
}
break;
default:
fprintf(stderr, "makepng: internal bad channel count\n");
exit(2);
}
else
{
fprintf(stderr,
"makepng: --color: count(%u) does not match channels(%u)\n",
colors[0], channels_of_type(color_type));
exit(1);
}
return filters;
}
| 173,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Dispatcher::AddStatus(const std::string& pattern) {
mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendStatus, NULL);
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void Dispatcher::AddStatus(const std::string& pattern) {
void Dispatcher::AddHealthz(const std::string& pattern) {
mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendHealthz, NULL);
}
void Dispatcher::AddLog(const std::string& pattern) {
mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendLog, NULL);
}
| 170,455 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fput(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
struct task_struct *task = current;
file_sb_list_del(file);
if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {
init_task_work(&file->f_u.fu_rcuhead, ____fput);
if (!task_work_add(task, &file->f_u.fu_rcuhead, true))
return;
/*
* After this task has run exit_task_work(),
* task_work_add() will fail. Fall through to delayed
* fput to avoid leaking *file.
*/
}
if (llist_add(&file->f_u.fu_llist, &delayed_fput_list))
schedule_work(&delayed_fput_work);
}
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void fput(struct file *file)
{
if (atomic_long_dec_and_test(&file->f_count)) {
struct task_struct *task = current;
if (likely(!in_interrupt() && !(task->flags & PF_KTHREAD))) {
init_task_work(&file->f_u.fu_rcuhead, ____fput);
if (!task_work_add(task, &file->f_u.fu_rcuhead, true))
return;
/*
* After this task has run exit_task_work(),
* task_work_add() will fail. Fall through to delayed
* fput to avoid leaking *file.
*/
}
if (llist_add(&file->f_u.fu_llist, &delayed_fput_list))
schedule_work(&delayed_fput_work);
}
}
| 166,801 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static Image *ReadCALSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
header[MagickPathExtent],
message[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register ssize_t
i;
unsigned long
density,
direction,
height,
orientation,
pel_path,
type,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CALS header.
*/
(void) memset(header,0,sizeof(header));
density=0;
direction=0;
orientation=1;
pel_path=0;
type=1;
width=0;
height=0;
for (i=0; i < 16; i++)
{
if (ReadBlob(image,128,(unsigned char *) header) != 128)
break;
switch (*header)
{
case 'R':
case 'r':
{
if (LocaleNCompare(header,"rdensty:",8) == 0)
{
(void) sscanf(header+8,"%lu",&density);
break;
}
if (LocaleNCompare(header,"rpelcnt:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&width,&height);
break;
}
if (LocaleNCompare(header,"rorient:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&pel_path,&direction);
if (pel_path == 90)
orientation=5;
else
if (pel_path == 180)
orientation=3;
else
if (pel_path == 270)
orientation=7;
if (direction == 90)
orientation++;
break;
}
if (LocaleNCompare(header,"rtype:",6) == 0)
{
(void) sscanf(header+6,"%lu",&type);
break;
}
break;
}
}
}
/*
Read CALS pixels.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
while ((c=ReadBlobByte(image)) != EOF)
(void) fputc(c,file);
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"group4:%s",
filename);
(void) FormatLocaleString(message,MagickPathExtent,"%lux%lu",width,height);
(void) CloneString(&read_info->size,message);
(void) FormatLocaleString(message,MagickPathExtent,"%lu",density);
(void) CloneString(&read_info->density,message);
read_info->orientation=(OrientationType) orientation;
image=ReadImage(read_info,exception);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"CALS",MagickPathExtent);
}
read_info=DestroyImageInfo(read_info);
(void) RelinquishUniqueFileResource(filename);
return(image);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1199
CWE ID: CWE-20 | static Image *ReadCALSImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
filename[MagickPathExtent],
header[MagickPathExtent],
message[MagickPathExtent];
FILE
*file;
Image
*image;
ImageInfo
*read_info;
int
c,
unique_file;
MagickBooleanType
status;
register ssize_t
i;
unsigned long
density,
direction,
height,
orientation,
pel_path,
type,
width;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read CALS header.
*/
(void) memset(header,0,sizeof(header));
density=0;
direction=0;
orientation=1;
pel_path=0;
type=1;
width=0;
height=0;
for (i=0; i < 16; i++)
{
if (ReadBlob(image,128,(unsigned char *) header) != 128)
break;
switch (*header)
{
case 'R':
case 'r':
{
if (LocaleNCompare(header,"rdensty:",8) == 0)
{
(void) sscanf(header+8,"%lu",&density);
break;
}
if (LocaleNCompare(header,"rpelcnt:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&width,&height);
break;
}
if (LocaleNCompare(header,"rorient:",8) == 0)
{
(void) sscanf(header+8,"%lu,%lu",&pel_path,&direction);
if (pel_path == 90)
orientation=5;
else
if (pel_path == 180)
orientation=3;
else
if (pel_path == 270)
orientation=7;
if (direction == 90)
orientation++;
break;
}
if (LocaleNCompare(header,"rtype:",6) == 0)
{
(void) sscanf(header+6,"%lu",&type);
break;
}
break;
}
}
}
/*
Read CALS pixels.
*/
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if ((unique_file == -1) || (file == (FILE *) NULL))
ThrowImageException(FileOpenError,"UnableToCreateTemporaryFile");
while ((c=ReadBlobByte(image)) != EOF)
if (fputc(c,file) != c)
break;
(void) fclose(file);
(void) CloseBlob(image);
image=DestroyImage(image);
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,"group4:%s",
filename);
(void) FormatLocaleString(message,MagickPathExtent,"%lux%lu",width,height);
(void) CloneString(&read_info->size,message);
(void) FormatLocaleString(message,MagickPathExtent,"%lu",density);
(void) CloneString(&read_info->density,message);
read_info->orientation=(OrientationType) orientation;
image=ReadImage(read_info,exception);
if (image != (Image *) NULL)
{
(void) CopyMagickString(image->filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick_filename,image_info->filename,
MagickPathExtent);
(void) CopyMagickString(image->magick,"CALS",MagickPathExtent);
}
read_info=DestroyImageInfo(read_info);
(void) RelinquishUniqueFileResource(filename);
return(image);
}
| 169,038 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplTempFileObject, __construct)
{
long max_memory = PHP_STREAM_MAX_MEM;
char tmp_fname[48];
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
if (max_memory < 0) {
intern->file_name = "php://memory";
intern->file_name_len = 12;
} else if (ZEND_NUM_ARGS()) {
intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory);
intern->file_name = tmp_fname;
} else {
intern->file_name = "php://temp";
intern->file_name_len = 10;
}
intern->u.file.open_mode = "wb";
intern->u.file.open_mode_len = 1;
intern->u.file.zcontext = NULL;
if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) {
intern->_path_len = 0;
intern->_path = estrndup("", 0);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::rewind()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplTempFileObject, __construct)
{
long max_memory = PHP_STREAM_MAX_MEM;
char tmp_fname[48];
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
zend_error_handling error_handling;
zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) {
zend_restore_error_handling(&error_handling TSRMLS_CC);
return;
}
if (max_memory < 0) {
intern->file_name = "php://memory";
intern->file_name_len = 12;
} else if (ZEND_NUM_ARGS()) {
intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory);
intern->file_name = tmp_fname;
} else {
intern->file_name = "php://temp";
intern->file_name_len = 10;
}
intern->u.file.open_mode = "wb";
intern->u.file.open_mode_len = 1;
intern->u.file.zcontext = NULL;
if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) {
intern->_path_len = 0;
intern->_path = estrndup("", 0);
}
zend_restore_error_handling(&error_handling TSRMLS_CC);
} /* }}} */
/* {{{ proto void SplFileObject::rewind()
| 167,050 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j;
if (!v) return -1;
for(i=0;i<n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim;j++)
a[i++]=v[j];
}
}else{
int i,j;
for(i=0;i<n;){
for (j=0;j<book->dim;j++)
a[i++]=0;
}
}
return 0;
}
Commit Message: Fix out of bounds access in codebook processing
Bug: 62800140
Test: ran poc, CTS
Change-Id: I9960d507be62ee0a3b0aa991240951d5a0784f37
(cherry picked from commit 2c4c4bd895f01fdecb90ebdd0412b60608a9ccf0)
CWE ID: CWE-200 | long vorbis_book_decodev_set(codebook *book,ogg_int32_t *a,
oggpack_buffer *b,int n,int point){
if(book->used_entries>0){
ogg_int32_t *v = book->dec_buf;//(ogg_int32_t *)alloca(sizeof(*v)*book->dim);
int i,j;
if (!v) return -1;
for(i=0;i<n;){
if(decode_map(book,b,v,point))return -1;
for (j=0;j<book->dim && i < n;j++)
a[i++]=v[j];
}
}else{
int i,j;
for(i=0;i<n;){
for (j=0;j<book->dim && i < n;j++)
a[i++]=0;
}
}
return 0;
}
| 173,987 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream)
{
unsigned int header_len;
if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) {
return 0;
}
if (!extend_raw_data(header, stream,
LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) {
return 0;
}
header_len = lha_decode_uint32(&RAW_DATA(header, 24));
if (header_len > LEVEL_3_MAX_HEADER_LEN) {
return 0;
}
if (!extend_raw_data(header, stream,
header_len - RAW_DATA_LEN(header))) {
return 0;
}
memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5);
(*header)->compress_method[5] = '\0';
(*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7));
(*header)->length = lha_decode_uint32(&RAW_DATA(header, 11));
(*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15));
(*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21));
(*header)->os_type = RAW_DATA(header, 23);
if (!decode_extended_headers(header, 28)) {
return 0;
}
return 1;
}
Commit Message: Fix integer underflow vulnerability in L3 decode.
Marcin 'Icewall' Noga of Cisco TALOS discovered that the level 3 header
decoding routines were vulnerable to an integer underflow, if the 32-bit
header length was less than the base level 3 header length. This could
lead to an exploitable heap corruption condition.
Thanks go to Marcin Noga and Regina Wilson of Cisco TALOS for reporting
this vulnerability.
CWE ID: CWE-190 | static int decode_level3_header(LHAFileHeader **header, LHAInputStream *stream)
{
unsigned int header_len;
if (lha_decode_uint16(&RAW_DATA(header, 0)) != 4) {
return 0;
}
if (!extend_raw_data(header, stream,
LEVEL_3_HEADER_LEN - RAW_DATA_LEN(header))) {
return 0;
}
header_len = lha_decode_uint32(&RAW_DATA(header, 24));
if (header_len > LEVEL_3_MAX_HEADER_LEN
|| header_len < RAW_DATA_LEN(header)) {
return 0;
}
if (!extend_raw_data(header, stream,
header_len - RAW_DATA_LEN(header))) {
return 0;
}
memcpy((*header)->compress_method, &RAW_DATA(header, 2), 5);
(*header)->compress_method[5] = '\0';
(*header)->compressed_length = lha_decode_uint32(&RAW_DATA(header, 7));
(*header)->length = lha_decode_uint32(&RAW_DATA(header, 11));
(*header)->timestamp = lha_decode_uint32(&RAW_DATA(header, 15));
(*header)->crc = lha_decode_uint16(&RAW_DATA(header, 21));
(*header)->os_type = RAW_DATA(header, 23);
if (!decode_extended_headers(header, 28)) {
return 0;
}
return 1;
}
| 168,846 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static entity_table_opt determine_entity_table(int all, int doctype)
{
entity_table_opt retval = {NULL};
assert(!(doctype == ENT_HTML_DOC_XML1 && all));
if (all) {
retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
entity_ms_table_html5 : entity_ms_table_html4;
} else {
retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
}
return retval;
}
Commit Message: Fix bug #72135 - don't create strings with lengths outside int range
CWE ID: CWE-190 | static entity_table_opt determine_entity_table(int all, int doctype)
{
entity_table_opt retval = {NULL};
assert(!(doctype == ENT_HTML_DOC_XML1 && all));
if (all) {
retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
entity_ms_table_html5 : entity_ms_table_html4;
} else {
retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
}
return retval;
}
| 167,170 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SampleTable::isValid() const {
return mChunkOffsetOffset >= 0
&& mSampleToChunkOffset >= 0
&& mSampleSizeOffset >= 0
&& !mTimeToSample.empty();
}
Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug
28076789.
Detail: Before the original fix
(Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the
code allowed a time-to-sample table size to be 0. The change
made in that fix disallowed such situation, which in fact should
be allowed. This current patch allows it again while maintaining
the security of the previous fix.
Bug: 28288202
Bug: 28076789
Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295
CWE ID: CWE-20 | bool SampleTable::isValid() const {
return mChunkOffsetOffset >= 0
&& mSampleToChunkOffset >= 0
&& mSampleSizeOffset >= 0
&& mHasTimeToSample;
}
| 173,772 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AudioRendererHost::OnCreateStream(
int stream_id, const media::AudioParameters& params, int input_channels) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK(LookupById(stream_id) == NULL);
media::AudioParameters audio_params(params);
uint32 buffer_size = media::AudioBus::CalculateMemorySize(audio_params);
DCHECK_GT(buffer_size, 0U);
DCHECK_LE(buffer_size,
static_cast<uint32>(media::limits::kMaxPacketSizeInBytes));
DCHECK_GE(input_channels, 0);
DCHECK_LT(input_channels, media::limits::kMaxChannels);
int output_memory_size = AudioBus::CalculateMemorySize(audio_params);
DCHECK_GT(output_memory_size, 0);
int frames = audio_params.frames_per_buffer();
int input_memory_size =
AudioBus::CalculateMemorySize(input_channels, frames);
DCHECK_GE(input_memory_size, 0);
scoped_ptr<AudioEntry> entry(new AudioEntry());
uint32 io_buffer_size = output_memory_size + input_memory_size;
uint32 shared_memory_size =
media::TotalSharedMemorySizeInBytes(io_buffer_size);
if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) {
SendErrorMessage(stream_id);
return;
}
scoped_ptr<AudioSyncReader> reader(
new AudioSyncReader(&entry->shared_memory, params, input_channels));
if (!reader->Init()) {
SendErrorMessage(stream_id);
return;
}
entry->reader.reset(reader.release());
entry->controller = media::AudioOutputController::Create(
audio_manager_, this, audio_params, entry->reader.get());
if (!entry->controller) {
SendErrorMessage(stream_id);
return;
}
entry->stream_id = stream_id;
audio_entries_.insert(std::make_pair(stream_id, entry.release()));
if (media_observer_)
media_observer_->OnSetAudioStreamStatus(this, stream_id, "created");
}
Commit Message: Improve validation when creating audio streams.
BUG=166795
Review URL: https://codereview.chromium.org/11647012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@173981 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | void AudioRendererHost::OnCreateStream(
int stream_id, const media::AudioParameters& params, int input_channels) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// media::AudioParameters is validated in the deserializer.
if (input_channels < 0 ||
input_channels > media::limits::kMaxChannels ||
LookupById(stream_id) != NULL) {
SendErrorMessage(stream_id);
return;
}
media::AudioParameters audio_params(params);
int output_memory_size = AudioBus::CalculateMemorySize(audio_params);
int frames = audio_params.frames_per_buffer();
int input_memory_size =
AudioBus::CalculateMemorySize(input_channels, frames);
scoped_ptr<AudioEntry> entry(new AudioEntry());
uint32 io_buffer_size = output_memory_size + input_memory_size;
uint32 shared_memory_size =
media::TotalSharedMemorySizeInBytes(io_buffer_size);
if (!entry->shared_memory.CreateAndMapAnonymous(shared_memory_size)) {
SendErrorMessage(stream_id);
return;
}
scoped_ptr<AudioSyncReader> reader(
new AudioSyncReader(&entry->shared_memory, params, input_channels));
if (!reader->Init()) {
SendErrorMessage(stream_id);
return;
}
entry->reader.reset(reader.release());
entry->controller = media::AudioOutputController::Create(
audio_manager_, this, audio_params, entry->reader.get());
if (!entry->controller) {
SendErrorMessage(stream_id);
return;
}
entry->stream_id = stream_id;
audio_entries_.insert(std::make_pair(stream_id, entry.release()));
if (media_observer_)
media_observer_->OnSetAudioStreamStatus(this, stream_id, "created");
}
| 171,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
{
ASSERT(m_world->isMainWorld());
if (m_context.isEmpty())
return;
if (document->hasNamedItem(name.impl()) || document->hasExtraNamedItem(name.impl()))
return;
v8::HandleScope handleScope(m_isolate);
v8::Context::Scope contextScope(m_context.newLocal(m_isolate));
ASSERT(!m_document.isEmpty());
v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
checkDocumentWrapper(documentHandle, document);
documentHandle->Delete(v8String(name, m_isolate));
}
Commit Message: Fix tracking of the id attribute string if it is shared across elements.
The patch to remove AtomicStringImpl:
http://src.chromium.org/viewvc/blink?view=rev&rev=154790
Exposed a lifetime issue with strings for id attributes. We simply need to use
AtomicString.
BUG=290566
Review URL: https://codereview.chromium.org/33793004
git-svn-id: svn://svn.chromium.org/blink/trunk@160250 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void V8WindowShell::namedItemRemoved(HTMLDocument* document, const AtomicString& name)
{
ASSERT(m_world->isMainWorld());
if (m_context.isEmpty())
return;
if (document->hasNamedItem(name) || document->hasExtraNamedItem(name))
return;
v8::HandleScope handleScope(m_isolate);
v8::Context::Scope contextScope(m_context.newLocal(m_isolate));
ASSERT(!m_document.isEmpty());
v8::Handle<v8::Object> documentHandle = m_document.newLocal(m_isolate);
checkDocumentWrapper(documentHandle, document);
documentHandle->Delete(v8String(name, m_isolate));
}
| 171,154 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: asmlinkage void __kprobes do_page_fault(struct pt_regs *regs, unsigned long write,
unsigned long address)
{
struct vm_area_struct * vma = NULL;
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
const int field = sizeof(unsigned long) * 2;
siginfo_t info;
int fault;
#if 0
printk("Cpu%d[%s:%d:%0*lx:%ld:%0*lx]\n", raw_smp_processor_id(),
current->comm, current->pid, field, address, write,
field, regs->cp0_epc);
#endif
#ifdef CONFIG_KPROBES
/*
* This is to notify the fault handler of the kprobes. The
* exception code is redundant as it is also carried in REGS,
* but we pass it anyhow.
*/
if (notify_die(DIE_PAGE_FAULT, "page fault", regs, -1,
(regs->cp0_cause >> 2) & 0x1f, SIGSEGV) == NOTIFY_STOP)
return;
#endif
info.si_code = SEGV_MAPERR;
/*
* We fault-in kernel-space virtual memory on-demand. The
* 'reference' page table is init_mm.pgd.
*
* NOTE! We MUST NOT take any locks for this case. We may
* be in an interrupt or a critical region, and should
* only copy the information from the master page table,
* nothing more.
*/
#ifdef CONFIG_64BIT
# define VMALLOC_FAULT_TARGET no_context
#else
# define VMALLOC_FAULT_TARGET vmalloc_fault
#endif
if (unlikely(address >= VMALLOC_START && address <= VMALLOC_END))
goto VMALLOC_FAULT_TARGET;
#ifdef MODULE_START
if (unlikely(address >= MODULE_START && address < MODULE_END))
goto VMALLOC_FAULT_TARGET;
#endif
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto bad_area_nosemaphore;
down_read(&mm->mmap_sem);
vma = find_vma(mm, address);
if (!vma)
goto bad_area;
if (vma->vm_start <= address)
goto good_area;
if (!(vma->vm_flags & VM_GROWSDOWN))
goto bad_area;
if (expand_stack(vma, address))
goto bad_area;
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
info.si_code = SEGV_ACCERR;
if (write) {
if (!(vma->vm_flags & VM_WRITE))
goto bad_area;
} else {
if (kernel_uses_smartmips_rixi) {
if (address == regs->cp0_epc && !(vma->vm_flags & VM_EXEC)) {
#if 0
pr_notice("Cpu%d[%s:%d:%0*lx:%ld:%0*lx] XI violation\n",
raw_smp_processor_id(),
current->comm, current->pid,
field, address, write,
field, regs->cp0_epc);
#endif
goto bad_area;
}
if (!(vma->vm_flags & VM_READ)) {
#if 0
pr_notice("Cpu%d[%s:%d:%0*lx:%ld:%0*lx] RI violation\n",
raw_smp_processor_id(),
current->comm, current->pid,
field, address, write,
field, regs->cp0_epc);
#endif
goto bad_area;
}
} else {
if (!(vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC)))
goto bad_area;
}
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
fault = handle_mm_fault(mm, vma, address, write ? FAULT_FLAG_WRITE : 0);
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, 0, regs, address);
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM)
goto out_of_memory;
else if (fault & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (fault & VM_FAULT_MAJOR) {
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ,
1, 0, regs, address);
tsk->maj_flt++;
} else {
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN,
1, 0, regs, address);
tsk->min_flt++;
}
up_read(&mm->mmap_sem);
return;
/*
* Something tried to access memory that isn't in our memory map..
* Fix it, but check if it's kernel or user first..
*/
bad_area:
up_read(&mm->mmap_sem);
bad_area_nosemaphore:
/* User mode accesses just cause a SIGSEGV */
if (user_mode(regs)) {
tsk->thread.cp0_badvaddr = address;
tsk->thread.error_code = write;
#if 0
printk("do_page_fault() #2: sending SIGSEGV to %s for "
"invalid %s\n%0*lx (epc == %0*lx, ra == %0*lx)\n",
tsk->comm,
write ? "write access to" : "read access from",
field, address,
field, (unsigned long) regs->cp0_epc,
field, (unsigned long) regs->regs[31]);
#endif
info.si_signo = SIGSEGV;
info.si_errno = 0;
/* info.si_code has been set above */
info.si_addr = (void __user *) address;
force_sig_info(SIGSEGV, &info, tsk);
return;
}
no_context:
/* Are we prepared to handle this kernel fault? */
if (fixup_exception(regs)) {
current->thread.cp0_baduaddr = address;
return;
}
/*
* Oops. The kernel tried to access some bad page. We'll have to
* terminate things with extreme prejudice.
*/
bust_spinlocks(1);
printk(KERN_ALERT "CPU %d Unable to handle kernel paging request at "
"virtual address %0*lx, epc == %0*lx, ra == %0*lx\n",
raw_smp_processor_id(), field, address, field, regs->cp0_epc,
field, regs->regs[31]);
die("Oops", regs);
out_of_memory:
/*
* We ran out of memory, call the OOM killer, and return the userspace
* (which will retry the fault, or kill us if we got oom-killed).
*/
up_read(&mm->mmap_sem);
pagefault_out_of_memory();
return;
do_sigbus:
up_read(&mm->mmap_sem);
/* Kernel mode? Handle exceptions or die */
if (!user_mode(regs))
goto no_context;
else
/*
* Send a sigbus, regardless of whether we were in kernel
* or user mode.
*/
#if 0
printk("do_page_fault() #3: sending SIGBUS to %s for "
"invalid %s\n%0*lx (epc == %0*lx, ra == %0*lx)\n",
tsk->comm,
write ? "write access to" : "read access from",
field, address,
field, (unsigned long) regs->cp0_epc,
field, (unsigned long) regs->regs[31]);
#endif
tsk->thread.cp0_badvaddr = address;
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRERR;
info.si_addr = (void __user *) address;
force_sig_info(SIGBUS, &info, tsk);
return;
#ifndef CONFIG_64BIT
vmalloc_fault:
{
/*
* Synchronize this task's top level page-table
* with the 'reference' page table.
*
* Do _not_ use "tsk" here. We might be inside
* an interrupt in the middle of a task switch..
*/
int offset = __pgd_offset(address);
pgd_t *pgd, *pgd_k;
pud_t *pud, *pud_k;
pmd_t *pmd, *pmd_k;
pte_t *pte_k;
pgd = (pgd_t *) pgd_current[raw_smp_processor_id()] + offset;
pgd_k = init_mm.pgd + offset;
if (!pgd_present(*pgd_k))
goto no_context;
set_pgd(pgd, *pgd_k);
pud = pud_offset(pgd, address);
pud_k = pud_offset(pgd_k, address);
if (!pud_present(*pud_k))
goto no_context;
pmd = pmd_offset(pud, address);
pmd_k = pmd_offset(pud_k, address);
if (!pmd_present(*pmd_k))
goto no_context;
set_pmd(pmd, *pmd_k);
pte_k = pte_offset_kernel(pmd_k, address);
if (!pte_present(*pte_k))
goto no_context;
return;
}
#endif
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | asmlinkage void __kprobes do_page_fault(struct pt_regs *regs, unsigned long write,
unsigned long address)
{
struct vm_area_struct * vma = NULL;
struct task_struct *tsk = current;
struct mm_struct *mm = tsk->mm;
const int field = sizeof(unsigned long) * 2;
siginfo_t info;
int fault;
#if 0
printk("Cpu%d[%s:%d:%0*lx:%ld:%0*lx]\n", raw_smp_processor_id(),
current->comm, current->pid, field, address, write,
field, regs->cp0_epc);
#endif
#ifdef CONFIG_KPROBES
/*
* This is to notify the fault handler of the kprobes. The
* exception code is redundant as it is also carried in REGS,
* but we pass it anyhow.
*/
if (notify_die(DIE_PAGE_FAULT, "page fault", regs, -1,
(regs->cp0_cause >> 2) & 0x1f, SIGSEGV) == NOTIFY_STOP)
return;
#endif
info.si_code = SEGV_MAPERR;
/*
* We fault-in kernel-space virtual memory on-demand. The
* 'reference' page table is init_mm.pgd.
*
* NOTE! We MUST NOT take any locks for this case. We may
* be in an interrupt or a critical region, and should
* only copy the information from the master page table,
* nothing more.
*/
#ifdef CONFIG_64BIT
# define VMALLOC_FAULT_TARGET no_context
#else
# define VMALLOC_FAULT_TARGET vmalloc_fault
#endif
if (unlikely(address >= VMALLOC_START && address <= VMALLOC_END))
goto VMALLOC_FAULT_TARGET;
#ifdef MODULE_START
if (unlikely(address >= MODULE_START && address < MODULE_END))
goto VMALLOC_FAULT_TARGET;
#endif
/*
* If we're in an interrupt or have no user
* context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto bad_area_nosemaphore;
down_read(&mm->mmap_sem);
vma = find_vma(mm, address);
if (!vma)
goto bad_area;
if (vma->vm_start <= address)
goto good_area;
if (!(vma->vm_flags & VM_GROWSDOWN))
goto bad_area;
if (expand_stack(vma, address))
goto bad_area;
/*
* Ok, we have a good vm_area for this memory access, so
* we can handle it..
*/
good_area:
info.si_code = SEGV_ACCERR;
if (write) {
if (!(vma->vm_flags & VM_WRITE))
goto bad_area;
} else {
if (kernel_uses_smartmips_rixi) {
if (address == regs->cp0_epc && !(vma->vm_flags & VM_EXEC)) {
#if 0
pr_notice("Cpu%d[%s:%d:%0*lx:%ld:%0*lx] XI violation\n",
raw_smp_processor_id(),
current->comm, current->pid,
field, address, write,
field, regs->cp0_epc);
#endif
goto bad_area;
}
if (!(vma->vm_flags & VM_READ)) {
#if 0
pr_notice("Cpu%d[%s:%d:%0*lx:%ld:%0*lx] RI violation\n",
raw_smp_processor_id(),
current->comm, current->pid,
field, address, write,
field, regs->cp0_epc);
#endif
goto bad_area;
}
} else {
if (!(vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC)))
goto bad_area;
}
}
/*
* If for any reason at all we couldn't handle the fault,
* make sure we exit gracefully rather than endlessly redo
* the fault.
*/
fault = handle_mm_fault(mm, vma, address, write ? FAULT_FLAG_WRITE : 0);
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
if (unlikely(fault & VM_FAULT_ERROR)) {
if (fault & VM_FAULT_OOM)
goto out_of_memory;
else if (fault & VM_FAULT_SIGBUS)
goto do_sigbus;
BUG();
}
if (fault & VM_FAULT_MAJOR) {
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
tsk->maj_flt++;
} else {
perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
tsk->min_flt++;
}
up_read(&mm->mmap_sem);
return;
/*
* Something tried to access memory that isn't in our memory map..
* Fix it, but check if it's kernel or user first..
*/
bad_area:
up_read(&mm->mmap_sem);
bad_area_nosemaphore:
/* User mode accesses just cause a SIGSEGV */
if (user_mode(regs)) {
tsk->thread.cp0_badvaddr = address;
tsk->thread.error_code = write;
#if 0
printk("do_page_fault() #2: sending SIGSEGV to %s for "
"invalid %s\n%0*lx (epc == %0*lx, ra == %0*lx)\n",
tsk->comm,
write ? "write access to" : "read access from",
field, address,
field, (unsigned long) regs->cp0_epc,
field, (unsigned long) regs->regs[31]);
#endif
info.si_signo = SIGSEGV;
info.si_errno = 0;
/* info.si_code has been set above */
info.si_addr = (void __user *) address;
force_sig_info(SIGSEGV, &info, tsk);
return;
}
no_context:
/* Are we prepared to handle this kernel fault? */
if (fixup_exception(regs)) {
current->thread.cp0_baduaddr = address;
return;
}
/*
* Oops. The kernel tried to access some bad page. We'll have to
* terminate things with extreme prejudice.
*/
bust_spinlocks(1);
printk(KERN_ALERT "CPU %d Unable to handle kernel paging request at "
"virtual address %0*lx, epc == %0*lx, ra == %0*lx\n",
raw_smp_processor_id(), field, address, field, regs->cp0_epc,
field, regs->regs[31]);
die("Oops", regs);
out_of_memory:
/*
* We ran out of memory, call the OOM killer, and return the userspace
* (which will retry the fault, or kill us if we got oom-killed).
*/
up_read(&mm->mmap_sem);
pagefault_out_of_memory();
return;
do_sigbus:
up_read(&mm->mmap_sem);
/* Kernel mode? Handle exceptions or die */
if (!user_mode(regs))
goto no_context;
else
/*
* Send a sigbus, regardless of whether we were in kernel
* or user mode.
*/
#if 0
printk("do_page_fault() #3: sending SIGBUS to %s for "
"invalid %s\n%0*lx (epc == %0*lx, ra == %0*lx)\n",
tsk->comm,
write ? "write access to" : "read access from",
field, address,
field, (unsigned long) regs->cp0_epc,
field, (unsigned long) regs->regs[31]);
#endif
tsk->thread.cp0_badvaddr = address;
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRERR;
info.si_addr = (void __user *) address;
force_sig_info(SIGBUS, &info, tsk);
return;
#ifndef CONFIG_64BIT
vmalloc_fault:
{
/*
* Synchronize this task's top level page-table
* with the 'reference' page table.
*
* Do _not_ use "tsk" here. We might be inside
* an interrupt in the middle of a task switch..
*/
int offset = __pgd_offset(address);
pgd_t *pgd, *pgd_k;
pud_t *pud, *pud_k;
pmd_t *pmd, *pmd_k;
pte_t *pte_k;
pgd = (pgd_t *) pgd_current[raw_smp_processor_id()] + offset;
pgd_k = init_mm.pgd + offset;
if (!pgd_present(*pgd_k))
goto no_context;
set_pgd(pgd, *pgd_k);
pud = pud_offset(pgd, address);
pud_k = pud_offset(pgd_k, address);
if (!pud_present(*pud_k))
goto no_context;
pmd = pmd_offset(pud, address);
pmd_k = pmd_offset(pud_k, address);
if (!pmd_present(*pmd_k))
goto no_context;
set_pmd(pmd, *pmd_k);
pte_k = pte_offset_kernel(pmd_k, address);
if (!pte_present(*pte_k))
goto no_context;
return;
}
#endif
}
| 165,787 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec)
{
stream_t *ps_stream;
UWORD32 u4_start_code;
IMPEG2D_ERROR_CODES_T e_error;
e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE;
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_ERROR_CODES_T)IVD_ERROR_NONE == e_error)
{
if(u4_start_code == USER_DATA_START_CODE)
{
impeg2d_dec_user_data(ps_dec);
}
else
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN);
switch(u4_start_code)
{
case SEQ_DISPLAY_EXT_ID:
impeg2d_dec_seq_disp_ext(ps_dec);
break;
case SEQ_SCALABLE_EXT_ID:
e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED;
break;
default:
/* In case its a reserved extension code */
impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN);
impeg2d_peek_next_start_code(ps_dec);
break;
}
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
return e_error;
}
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 | IMPEG2D_ERROR_CODES_T impeg2d_dec_seq_ext_data(dec_state_t *ps_dec)
{
stream_t *ps_stream;
UWORD32 u4_start_code;
IMPEG2D_ERROR_CODES_T e_error;
e_error = (IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE;
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_ERROR_CODES_T)IVD_ERROR_NONE == e_error &&
(ps_stream->u4_offset < ps_stream->u4_max_offset))
{
if(u4_start_code == USER_DATA_START_CODE)
{
impeg2d_dec_user_data(ps_dec);
}
else
{
impeg2d_bit_stream_flush(ps_stream,START_CODE_LEN);
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,EXT_ID_LEN);
switch(u4_start_code)
{
case SEQ_DISPLAY_EXT_ID:
impeg2d_dec_seq_disp_ext(ps_dec);
break;
case SEQ_SCALABLE_EXT_ID:
e_error = IMPEG2D_SCALABILITIY_NOT_SUPPORTED;
break;
default:
/* In case its a reserved extension code */
impeg2d_bit_stream_flush(ps_stream,EXT_ID_LEN);
impeg2d_peek_next_start_code(ps_dec);
break;
}
}
u4_start_code = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN);
}
return e_error;
}
| 173,946 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
Commit Message:
CWE ID: | static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
X509_ALGOR **pmaskHash)
{
const unsigned char *p;
int plen;
RSA_PSS_PARAMS *pss;
*pmaskHash = NULL;
if (!alg->parameter || alg->parameter->type != V_ASN1_SEQUENCE)
return NULL;
p = alg->parameter->value.sequence->data;
plen = alg->parameter->value.sequence->length;
pss = d2i_RSA_PSS_PARAMS(NULL, &p, plen);
if (!pss)
return NULL;
if (pss->maskGenAlgorithm) {
ASN1_TYPE *param = pss->maskGenAlgorithm->parameter;
if (OBJ_obj2nid(pss->maskGenAlgorithm->algorithm) == NID_mgf1
&& param && param->type == V_ASN1_SEQUENCE) {
p = param->value.sequence->data;
plen = param->value.sequence->length;
*pmaskHash = d2i_X509_ALGOR(NULL, &p, plen);
}
}
return pss;
}
| 164,719 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b = NULL;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey = NULL;
size_t keylen, ivlen, maclen;
int r;
if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
(r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
(r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
(r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
(r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
goto out;
if ((r = mac_setup(mac, mac->name)) != 0)
goto out;
if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
(r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
goto out;
if (maclen > mac->key_len) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
mac->key_len = maclen;
}
if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&comp->enabled)) != 0 ||
(r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
goto out;
if (enc->name == NULL ||
cipher_by_name(enc->name) != enc->cipher) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (sshbuf_len(b) != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
enc->key_len = keylen;
enc->iv_len = ivlen;
ssh->kex->newkeys[mode] = newkey;
newkey = NULL;
r = 0;
out:
free(newkey);
sshbuf_free(b);
return r;
}
Commit Message: Remove support for pre-authentication compression. Doing compression
early in the protocol probably seemed reasonable in the 1990s, but
today it's clearly a bad idea in terms of both cryptography (cf.
multiple compression oracle attacks in TLS) and attack surface.
Moreover, to support it across privilege-separation zlib needed
the assistance of a complex shared-memory manager that made the
required attack surface considerably larger.
Prompted by Guido Vranken pointing out a compiler-elided security
check in the shared memory manager found by Stack
(http://css.csail.mit.edu/stack/); ok deraadt@ markus@
NB. pre-auth authentication has been disabled by default in sshd
for >10 years.
CWE ID: CWE-119 | newkeys_from_blob(struct sshbuf *m, struct ssh *ssh, int mode)
{
struct sshbuf *b = NULL;
struct sshcomp *comp;
struct sshenc *enc;
struct sshmac *mac;
struct newkeys *newkey = NULL;
size_t keylen, ivlen, maclen;
int r;
if ((newkey = calloc(1, sizeof(*newkey))) == NULL) {
r = SSH_ERR_ALLOC_FAIL;
goto out;
}
if ((r = sshbuf_froms(m, &b)) != 0)
goto out;
#ifdef DEBUG_PK
sshbuf_dump(b, stderr);
#endif
enc = &newkey->enc;
mac = &newkey->mac;
comp = &newkey->comp;
if ((r = sshbuf_get_cstring(b, &enc->name, NULL)) != 0 ||
(r = sshbuf_get(b, &enc->cipher, sizeof(enc->cipher))) != 0 ||
(r = sshbuf_get_u32(b, (u_int *)&enc->enabled)) != 0 ||
(r = sshbuf_get_u32(b, &enc->block_size)) != 0 ||
(r = sshbuf_get_string(b, &enc->key, &keylen)) != 0 ||
(r = sshbuf_get_string(b, &enc->iv, &ivlen)) != 0)
goto out;
if (cipher_authlen(enc->cipher) == 0) {
if ((r = sshbuf_get_cstring(b, &mac->name, NULL)) != 0)
goto out;
if ((r = mac_setup(mac, mac->name)) != 0)
goto out;
if ((r = sshbuf_get_u32(b, (u_int *)&mac->enabled)) != 0 ||
(r = sshbuf_get_string(b, &mac->key, &maclen)) != 0)
goto out;
if (maclen > mac->key_len) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
mac->key_len = maclen;
}
if ((r = sshbuf_get_u32(b, &comp->type)) != 0 ||
(r = sshbuf_get_cstring(b, &comp->name, NULL)) != 0)
goto out;
if (enc->name == NULL ||
cipher_by_name(enc->name) != enc->cipher) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
if (sshbuf_len(b) != 0) {
r = SSH_ERR_INVALID_FORMAT;
goto out;
}
enc->key_len = keylen;
enc->iv_len = ivlen;
ssh->kex->newkeys[mode] = newkey;
newkey = NULL;
r = 0;
out:
free(newkey);
sshbuf_free(b);
return r;
}
| 168,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: atmarp_print(netdissect_options *ndo,
const u_char *bp, u_int length, u_int caplen)
{
const struct atmarp_pkthdr *ap;
u_short pro, hrd, op;
ap = (const struct atmarp_pkthdr *)bp;
ND_TCHECK(*ap);
hrd = ATMHRD(ap);
pro = ATMPRO(ap);
op = ATMOP(ap);
if (!ND_TTEST2(*aar_tpa(ap), ATMTPROTO_LEN(ap))) {
ND_PRINT((ndo, "%s", tstr));
ND_DEFAULTPRINT((const u_char *)ap, length);
return;
}
if (!ndo->ndo_eflag) {
ND_PRINT((ndo, "ARP, "));
}
if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) ||
ATMSPROTO_LEN(ap) != 4 ||
ATMTPROTO_LEN(ap) != 4 ||
ndo->ndo_vflag) {
ND_PRINT((ndo, "%s, %s (len %u/%u)",
tok2str(arphrd_values, "Unknown Hardware (%u)", hrd),
tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro),
ATMSPROTO_LEN(ap),
ATMTPROTO_LEN(ap)));
/* don't know know about the address formats */
if (!ndo->ndo_vflag) {
goto out;
}
}
/* print operation */
ND_PRINT((ndo, "%s%s ",
ndo->ndo_vflag ? ", " : "",
tok2str(arpop_values, "Unknown (%u)", op)));
switch (op) {
case ARPOP_REQUEST:
ND_PRINT((ndo, "who-has %s", ipaddr_string(ndo, ATMTPA(ap))));
if (ATMTHRD_LEN(ap) != 0) {
ND_PRINT((ndo, " ("));
atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap),
ATMTSA(ap), ATMTSLN(ap));
ND_PRINT((ndo, ")"));
}
ND_PRINT((ndo, "tell %s", ipaddr_string(ndo, ATMSPA(ap))));
break;
case ARPOP_REPLY:
ND_PRINT((ndo, "%s is-at ", ipaddr_string(ndo, ATMSPA(ap))));
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
break;
case ARPOP_INVREQUEST:
ND_PRINT((ndo, "who-is "));
atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap), ATMTSA(ap),
ATMTSLN(ap));
ND_PRINT((ndo, " tell "));
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
break;
case ARPOP_INVREPLY:
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
ND_PRINT((ndo, "at %s", ipaddr_string(ndo, ATMSPA(ap))));
break;
case ARPOP_NAK:
ND_PRINT((ndo, "for %s", ipaddr_string(ndo, ATMSPA(ap))));
break;
default:
ND_DEFAULTPRINT((const u_char *)ap, caplen);
return;
}
out:
ND_PRINT((ndo, ", length %u", length));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-13013/ARP: Fix printing of ARP protocol addresses.
If the protocol type isn't ETHERTYPE_IP or ETHERTYPE_TRAIL, or if the
protocol address length isn't 4, don't print the address as an IPv4 address.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s), modified
so the capture file won't be rejected as an invalid capture.
Update another test file's tcpdump output to reflect this change.
CWE ID: CWE-125 | atmarp_print(netdissect_options *ndo,
const u_char *bp, u_int length, u_int caplen)
{
const struct atmarp_pkthdr *ap;
u_short pro, hrd, op;
ap = (const struct atmarp_pkthdr *)bp;
ND_TCHECK(*ap);
hrd = ATMHRD(ap);
pro = ATMPRO(ap);
op = ATMOP(ap);
if (!ND_TTEST2(*aar_tpa(ap), ATMTPROTO_LEN(ap))) {
ND_PRINT((ndo, "%s", tstr));
ND_DEFAULTPRINT((const u_char *)ap, length);
return;
}
if (!ndo->ndo_eflag) {
ND_PRINT((ndo, "ARP, "));
}
if ((pro != ETHERTYPE_IP && pro != ETHERTYPE_TRAIL) ||
ATMSPROTO_LEN(ap) != 4 ||
ATMTPROTO_LEN(ap) != 4 ||
ndo->ndo_vflag) {
ND_PRINT((ndo, "%s, %s (len %u/%u)",
tok2str(arphrd_values, "Unknown Hardware (%u)", hrd),
tok2str(ethertype_values, "Unknown Protocol (0x%04x)", pro),
ATMSPROTO_LEN(ap),
ATMTPROTO_LEN(ap)));
/* don't know know about the address formats */
if (!ndo->ndo_vflag) {
goto out;
}
}
/* print operation */
ND_PRINT((ndo, "%s%s ",
ndo->ndo_vflag ? ", " : "",
tok2str(arpop_values, "Unknown (%u)", op)));
switch (op) {
case ARPOP_REQUEST:
ND_PRINT((ndo, "who-has "));
atmarp_tpaddr_print(ndo, ap, pro);
if (ATMTHRD_LEN(ap) != 0) {
ND_PRINT((ndo, " ("));
atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap),
ATMTSA(ap), ATMTSLN(ap));
ND_PRINT((ndo, ")"));
}
ND_PRINT((ndo, " tell "));
atmarp_spaddr_print(ndo, ap, pro);
break;
case ARPOP_REPLY:
atmarp_spaddr_print(ndo, ap, pro);
ND_PRINT((ndo, " is-at "));
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
break;
case ARPOP_INVREQUEST:
ND_PRINT((ndo, "who-is "));
atmarp_addr_print(ndo, ATMTHA(ap), ATMTHRD_LEN(ap), ATMTSA(ap),
ATMTSLN(ap));
ND_PRINT((ndo, " tell "));
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
break;
case ARPOP_INVREPLY:
atmarp_addr_print(ndo, ATMSHA(ap), ATMSHRD_LEN(ap), ATMSSA(ap),
ATMSSLN(ap));
ND_PRINT((ndo, "at "));
atmarp_spaddr_print(ndo, ap, pro);
break;
case ARPOP_NAK:
ND_PRINT((ndo, "for "));
atmarp_spaddr_print(ndo, ap, pro);
break;
default:
ND_DEFAULTPRINT((const u_char *)ap, caplen);
return;
}
out:
ND_PRINT((ndo, ", length %u", length));
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 167,881 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FragmentPaintPropertyTreeBuilder::UpdateSvgLocalToBorderBoxTransform() {
DCHECK(properties_);
if (!object_.IsSVGRoot())
return;
if (NeedsPaintPropertyUpdate()) {
AffineTransform transform_to_border_box =
SVGRootPainter(ToLayoutSVGRoot(object_))
.TransformToPixelSnappedBorderBox(context_.current.paint_offset);
if (!transform_to_border_box.IsIdentity() &&
NeedsSVGLocalToBorderBoxTransform(object_)) {
OnUpdate(properties_->UpdateSvgLocalToBorderBoxTransform(
context_.current.transform,
TransformPaintPropertyNode::State{transform_to_border_box}));
} else {
OnClear(properties_->ClearSvgLocalToBorderBoxTransform());
}
}
if (properties_->SvgLocalToBorderBoxTransform()) {
context_.current.transform = properties_->SvgLocalToBorderBoxTransform();
context_.current.should_flatten_inherited_transform = false;
context_.current.rendering_context_id = 0;
}
context_.current.paint_offset = LayoutPoint();
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | void FragmentPaintPropertyTreeBuilder::UpdateSvgLocalToBorderBoxTransform() {
DCHECK(properties_);
if (!object_.IsSVGRoot())
return;
if (NeedsPaintPropertyUpdate()) {
AffineTransform transform_to_border_box =
SVGRootPainter(ToLayoutSVGRoot(object_))
.TransformToPixelSnappedBorderBox(context_.current.paint_offset);
if (!transform_to_border_box.IsIdentity() &&
NeedsSVGLocalToBorderBoxTransform(object_)) {
OnUpdate(properties_->UpdateSvgLocalToBorderBoxTransform(
*context_.current.transform,
TransformPaintPropertyNode::State{transform_to_border_box}));
} else {
OnClear(properties_->ClearSvgLocalToBorderBoxTransform());
}
}
if (properties_->SvgLocalToBorderBoxTransform()) {
context_.current.transform = properties_->SvgLocalToBorderBoxTransform();
context_.current.should_flatten_inherited_transform = false;
context_.current.rendering_context_id = 0;
}
context_.current.paint_offset = LayoutPoint();
}
| 171,805 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int snd_timer_close(struct snd_timer_instance *timeri)
{
struct snd_timer *timer = NULL;
struct snd_timer_instance *slave, *tmp;
if (snd_BUG_ON(!timeri))
return -ENXIO;
/* force to stop the timer */
snd_timer_stop(timeri);
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) {
/* wait, until the active callback is finished */
spin_lock_irq(&slave_active_lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&slave_active_lock);
udelay(10);
spin_lock_irq(&slave_active_lock);
}
spin_unlock_irq(&slave_active_lock);
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
mutex_unlock(®ister_mutex);
} else {
timer = timeri->timer;
if (snd_BUG_ON(!timer))
goto out;
/* wait, until the active callback is finished */
spin_lock_irq(&timer->lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&timer->lock);
udelay(10);
spin_lock_irq(&timer->lock);
}
spin_unlock_irq(&timer->lock);
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
if (timer && list_empty(&timer->open_list_head) &&
timer->hw.close)
timer->hw.close(timer);
/* remove slave links */
list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,
open_list) {
spin_lock_irq(&slave_active_lock);
_snd_timer_stop(slave, 1, SNDRV_TIMER_EVENT_RESOLUTION);
list_move_tail(&slave->open_list, &snd_timer_slave_list);
slave->master = NULL;
slave->timer = NULL;
spin_unlock_irq(&slave_active_lock);
}
mutex_unlock(®ister_mutex);
}
out:
if (timeri->private_free)
timeri->private_free(timeri);
kfree(timeri->owner);
kfree(timeri);
if (timer)
module_put(timer->module);
return 0;
}
Commit Message: ALSA: timer: Harden slave timer list handling
A slave timer instance might be still accessible in a racy way while
operating the master instance as it lacks of locking. Since the
master operation is mostly protected with timer->lock, we should cope
with it while changing the slave instance, too. Also, some linked
lists (active_list and ack_list) of slave instances aren't unlinked
immediately at stopping or closing, and this may lead to unexpected
accesses.
This patch tries to address these issues. It adds spin lock of
timer->lock (either from master or slave, which is equivalent) in a
few places. For avoiding a deadlock, we ensure that the global
slave_active_lock is always locked at first before each timer lock.
Also, ack and active_list of slave instances are properly unlinked at
snd_timer_stop() and snd_timer_close().
Last but not least, remove the superfluous call of _snd_timer_stop()
at removing slave links. This is a noop, and calling it may confuse
readers wrt locking. Further cleanup will follow in a later patch.
Actually we've got reports of use-after-free by syzkaller fuzzer, and
this hopefully fixes these issues.
Reported-by: Dmitry Vyukov <[email protected]>
Cc: <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-20 | int snd_timer_close(struct snd_timer_instance *timeri)
{
struct snd_timer *timer = NULL;
struct snd_timer_instance *slave, *tmp;
if (snd_BUG_ON(!timeri))
return -ENXIO;
/* force to stop the timer */
snd_timer_stop(timeri);
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) {
/* wait, until the active callback is finished */
spin_lock_irq(&slave_active_lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&slave_active_lock);
udelay(10);
spin_lock_irq(&slave_active_lock);
}
spin_unlock_irq(&slave_active_lock);
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
mutex_unlock(®ister_mutex);
} else {
timer = timeri->timer;
if (snd_BUG_ON(!timer))
goto out;
/* wait, until the active callback is finished */
spin_lock_irq(&timer->lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&timer->lock);
udelay(10);
spin_lock_irq(&timer->lock);
}
spin_unlock_irq(&timer->lock);
mutex_lock(®ister_mutex);
list_del(&timeri->open_list);
if (timer && list_empty(&timer->open_list_head) &&
timer->hw.close)
timer->hw.close(timer);
/* remove slave links */
spin_lock_irq(&slave_active_lock);
spin_lock(&timer->lock);
list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,
open_list) {
list_move_tail(&slave->open_list, &snd_timer_slave_list);
slave->master = NULL;
slave->timer = NULL;
list_del_init(&slave->ack_list);
list_del_init(&slave->active_list);
}
spin_unlock(&timer->lock);
spin_unlock_irq(&slave_active_lock);
mutex_unlock(®ister_mutex);
}
out:
if (timeri->private_free)
timeri->private_free(timeri);
kfree(timeri->owner);
kfree(timeri);
if (timer)
module_put(timer->module);
return 0;
}
| 167,402 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: PreconnectedRequestStats::PreconnectedRequestStats(const GURL& origin,
bool was_preconnected)
: origin(origin),
was_preconnected(was_preconnected) {}
Commit Message: Origins should be represented as url::Origin (not as GURL).
As pointed out in //docs/security/origin-vs-url.md, origins should be
represented as url::Origin (not as GURL). This CL applies this
guideline to predictor-related code and changes the type of the
following fields from GURL to url::Origin:
- OriginRequestSummary::origin
- PreconnectedRequestStats::origin
- PreconnectRequest::origin
The old code did not depend on any non-origin parts of GURL
(like path and/or query). Therefore, this CL has no intended
behavior change.
Bug: 973885
Change-Id: Idd14590b4834cb9d50c74ed747b595fe1a4ba357
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1895167
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: Alex Ilin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#716311}
CWE ID: CWE-125 | PreconnectedRequestStats::PreconnectedRequestStats(const GURL& origin,
PreconnectedRequestStats::PreconnectedRequestStats(const url::Origin& origin,
bool was_preconnected)
| 172,375 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __get_data_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh, int create, int flag,
pgoff_t *next_pgofs)
{
struct f2fs_map_blocks map;
int err;
map.m_lblk = iblock;
map.m_len = bh->b_size >> inode->i_blkbits;
map.m_next_pgofs = next_pgofs;
err = f2fs_map_blocks(inode, &map, create, flag);
if (!err) {
map_bh(bh, inode->i_sb, map.m_pblk);
bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;
bh->b_size = map.m_len << inode->i_blkbits;
}
return err;
}
Commit Message: f2fs: fix a dead loop in f2fs_fiemap()
A dead loop can be triggered in f2fs_fiemap() using the test case
as below:
...
fd = open();
fallocate(fd, 0, 0, 4294967296);
ioctl(fd, FS_IOC_FIEMAP, fiemap_buf);
...
It's caused by an overflow in __get_data_block():
...
bh->b_size = map.m_len << inode->i_blkbits;
...
map.m_len is an unsigned int, and bh->b_size is a size_t which is 64 bits
on 64 bits archtecture, type conversion from an unsigned int to a size_t
will result in an overflow.
In the above-mentioned case, bh->b_size will be zero, and f2fs_fiemap()
will call get_data_block() at block 0 again an again.
Fix this by adding a force conversion before left shift.
Signed-off-by: Wei Fang <[email protected]>
Acked-by: Chao Yu <[email protected]>
Signed-off-by: Jaegeuk Kim <[email protected]>
CWE ID: CWE-190 | static int __get_data_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh, int create, int flag,
pgoff_t *next_pgofs)
{
struct f2fs_map_blocks map;
int err;
map.m_lblk = iblock;
map.m_len = bh->b_size >> inode->i_blkbits;
map.m_next_pgofs = next_pgofs;
err = f2fs_map_blocks(inode, &map, create, flag);
if (!err) {
map_bh(bh, inode->i_sb, map.m_pblk);
bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags;
bh->b_size = (u64)map.m_len << inode->i_blkbits;
}
return err;
}
| 169,377 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
Commit Message: CVE-2017-13690/IKEv2: Fix some bounds checks.
Use a pointer of the correct type in ND_TCHECK(), or use ND_TCHECK2()
and provide the correct length.
While we're at it, remove the blank line between some checks and the
UNALIGNED_MEMCPY()s they protect.
Also, note the places where we print the entire payload.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev2_p_print(netdissect_options *ndo, u_char tpay _U_, int pcount _U_,
const struct isakmp_gen *ext, u_int oprop_length,
const u_char *ep, int depth)
{
const struct ikev2_p *p;
struct ikev2_p prop;
u_int prop_length;
const u_char *cp;
int i;
int tcount;
u_char np;
struct isakmp_gen e;
u_int item_len;
p = (const struct ikev2_p *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&prop, ext, sizeof(prop));
ikev2_pay_print(ndo, NPSTR(ISAKMP_NPTYPE_P), prop.h.critical);
/*
* ikev2_sa_print() guarantees that this is >= 4.
*/
prop_length = oprop_length - 4;
ND_PRINT((ndo," #%u protoid=%s transform=%d len=%u",
prop.p_no, PROTOIDSTR(prop.prot_id),
prop.num_t, oprop_length));
cp = (const u_char *)(p + 1);
if (prop.spi_size) {
if (prop_length < prop.spi_size)
goto toolong;
ND_PRINT((ndo," spi="));
if (!rawprint(ndo, (const uint8_t *)cp, prop.spi_size))
goto trunc;
cp += prop.spi_size;
prop_length -= prop.spi_size;
}
/*
* Print the transforms.
*/
tcount = 0;
for (np = ISAKMP_NPTYPE_T; np != 0; np = e.np) {
tcount++;
ext = (const struct isakmp_gen *)cp;
if (prop_length < sizeof(*ext))
goto toolong;
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Since we can't have a payload length of less than 4 bytes,
* we need to bail out here if the generic header is nonsensical
* or truncated, otherwise we could loop forever processing
* zero-length items or otherwise misdissect the packet.
*/
item_len = ntohs(e.len);
if (item_len <= 4)
goto trunc;
if (prop_length < item_len)
goto toolong;
ND_TCHECK2(*cp, item_len);
depth++;
ND_PRINT((ndo,"\n"));
for (i = 0; i < depth; i++)
ND_PRINT((ndo," "));
ND_PRINT((ndo,"("));
if (np == ISAKMP_NPTYPE_T) {
cp = ikev2_t_print(ndo, tcount, ext, item_len, ep);
if (cp == NULL) {
/* error, already reported */
return NULL;
}
} else {
ND_PRINT((ndo, "%s", NPSTR(np)));
cp += item_len;
}
ND_PRINT((ndo,")"));
depth--;
prop_length -= item_len;
}
return cp;
toolong:
/*
* Skip the rest of the proposal.
*/
cp += prop_length;
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return cp;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_P)));
return NULL;
}
| 167,800 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int tty_open(struct inode *inode, struct file *filp)
{
struct tty_struct *tty = NULL;
int noctty, retval;
struct tty_driver *driver;
int index;
dev_t device = inode->i_rdev;
unsigned saved_flags = filp->f_flags;
nonseekable_open(inode, filp);
retry_open:
noctty = filp->f_flags & O_NOCTTY;
index = -1;
retval = 0;
mutex_lock(&tty_mutex);
tty_lock();
if (device == MKDEV(TTYAUX_MAJOR, 0)) {
tty = get_current_tty();
if (!tty) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENXIO;
}
driver = tty_driver_kref_get(tty->driver);
index = tty->index;
filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
/* noctty = 1; */
/* FIXME: Should we take a driver reference ? */
tty_kref_put(tty);
goto got_driver;
}
#ifdef CONFIG_VT
if (device == MKDEV(TTY_MAJOR, 0)) {
extern struct tty_driver *console_driver;
driver = tty_driver_kref_get(console_driver);
index = fg_console;
noctty = 1;
goto got_driver;
}
#endif
if (device == MKDEV(TTYAUX_MAJOR, 1)) {
struct tty_driver *console_driver = console_device(&index);
if (console_driver) {
driver = tty_driver_kref_get(console_driver);
if (driver) {
/* Don't let /dev/console block */
filp->f_flags |= O_NONBLOCK;
noctty = 1;
goto got_driver;
}
}
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
driver = get_tty_driver(device, &index);
if (!driver) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
got_driver:
if (!tty) {
/* check whether we're reopening an existing tty */
tty = tty_driver_lookup_tty(driver, inode, index);
if (IS_ERR(tty)) {
tty_unlock();
mutex_unlock(&tty_mutex);
return PTR_ERR(tty);
}
}
if (tty) {
retval = tty_reopen(tty);
if (retval)
tty = ERR_PTR(retval);
} else
tty = tty_init_dev(driver, index, 0);
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
if (IS_ERR(tty)) {
tty_unlock();
return PTR_ERR(tty);
}
retval = tty_add_file(tty, filp);
if (retval) {
tty_unlock();
tty_release(inode, filp);
return retval;
}
check_tty_count(tty, "tty_open");
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
noctty = 1;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "opening %s...", tty->name);
#endif
if (tty->ops->open)
retval = tty->ops->open(tty, filp);
else
retval = -ENODEV;
filp->f_flags = saved_flags;
if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) &&
!capable(CAP_SYS_ADMIN))
retval = -EBUSY;
if (retval) {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error %d in opening %s...", retval,
tty->name);
#endif
tty_unlock(); /* need to call tty_release without BTM */
tty_release(inode, filp);
if (retval != -ERESTARTSYS)
return retval;
if (signal_pending(current))
return retval;
schedule();
/*
* Need to reset f_op in case a hangup happened.
*/
tty_lock();
if (filp->f_op == &hung_up_tty_fops)
filp->f_op = &tty_fops;
tty_unlock();
goto retry_open;
}
tty_unlock();
mutex_lock(&tty_mutex);
tty_lock();
spin_lock_irq(¤t->sighand->siglock);
if (!noctty &&
current->signal->leader &&
!current->signal->tty &&
tty->session == NULL)
__proc_set_tty(current, tty);
spin_unlock_irq(¤t->sighand->siglock);
tty_unlock();
mutex_unlock(&tty_mutex);
return 0;
}
Commit Message: TTY: drop driver reference in tty_open fail path
When tty_driver_lookup_tty fails in tty_open, we forget to drop a
reference to the tty driver. This was added by commit 4a2b5fddd5 (Move
tty lookup/reopen to caller).
Fix that by adding tty_driver_kref_put to the fail path.
I will refactor the code later. This is for the ease of backporting to
stable.
Introduced-in: v2.6.28-rc2
Signed-off-by: Jiri Slaby <[email protected]>
Cc: stable <[email protected]>
Cc: Alan Cox <[email protected]>
Acked-by: Sukadev Bhattiprolu <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static int tty_open(struct inode *inode, struct file *filp)
{
struct tty_struct *tty = NULL;
int noctty, retval;
struct tty_driver *driver;
int index;
dev_t device = inode->i_rdev;
unsigned saved_flags = filp->f_flags;
nonseekable_open(inode, filp);
retry_open:
noctty = filp->f_flags & O_NOCTTY;
index = -1;
retval = 0;
mutex_lock(&tty_mutex);
tty_lock();
if (device == MKDEV(TTYAUX_MAJOR, 0)) {
tty = get_current_tty();
if (!tty) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENXIO;
}
driver = tty_driver_kref_get(tty->driver);
index = tty->index;
filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */
/* noctty = 1; */
/* FIXME: Should we take a driver reference ? */
tty_kref_put(tty);
goto got_driver;
}
#ifdef CONFIG_VT
if (device == MKDEV(TTY_MAJOR, 0)) {
extern struct tty_driver *console_driver;
driver = tty_driver_kref_get(console_driver);
index = fg_console;
noctty = 1;
goto got_driver;
}
#endif
if (device == MKDEV(TTYAUX_MAJOR, 1)) {
struct tty_driver *console_driver = console_device(&index);
if (console_driver) {
driver = tty_driver_kref_get(console_driver);
if (driver) {
/* Don't let /dev/console block */
filp->f_flags |= O_NONBLOCK;
noctty = 1;
goto got_driver;
}
}
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
driver = get_tty_driver(device, &index);
if (!driver) {
tty_unlock();
mutex_unlock(&tty_mutex);
return -ENODEV;
}
got_driver:
if (!tty) {
/* check whether we're reopening an existing tty */
tty = tty_driver_lookup_tty(driver, inode, index);
if (IS_ERR(tty)) {
tty_unlock();
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
return PTR_ERR(tty);
}
}
if (tty) {
retval = tty_reopen(tty);
if (retval)
tty = ERR_PTR(retval);
} else
tty = tty_init_dev(driver, index, 0);
mutex_unlock(&tty_mutex);
tty_driver_kref_put(driver);
if (IS_ERR(tty)) {
tty_unlock();
return PTR_ERR(tty);
}
retval = tty_add_file(tty, filp);
if (retval) {
tty_unlock();
tty_release(inode, filp);
return retval;
}
check_tty_count(tty, "tty_open");
if (tty->driver->type == TTY_DRIVER_TYPE_PTY &&
tty->driver->subtype == PTY_TYPE_MASTER)
noctty = 1;
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "opening %s...", tty->name);
#endif
if (tty->ops->open)
retval = tty->ops->open(tty, filp);
else
retval = -ENODEV;
filp->f_flags = saved_flags;
if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) &&
!capable(CAP_SYS_ADMIN))
retval = -EBUSY;
if (retval) {
#ifdef TTY_DEBUG_HANGUP
printk(KERN_DEBUG "error %d in opening %s...", retval,
tty->name);
#endif
tty_unlock(); /* need to call tty_release without BTM */
tty_release(inode, filp);
if (retval != -ERESTARTSYS)
return retval;
if (signal_pending(current))
return retval;
schedule();
/*
* Need to reset f_op in case a hangup happened.
*/
tty_lock();
if (filp->f_op == &hung_up_tty_fops)
filp->f_op = &tty_fops;
tty_unlock();
goto retry_open;
}
tty_unlock();
mutex_lock(&tty_mutex);
tty_lock();
spin_lock_irq(¤t->sighand->siglock);
if (!noctty &&
current->signal->leader &&
!current->signal->tty &&
tty->session == NULL)
__proc_set_tty(current, tty);
spin_unlock_irq(¤t->sighand->siglock);
tty_unlock();
mutex_unlock(&tty_mutex);
return 0;
}
| 167,616 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed 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: 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 Tracks::Parse()
| 174,408 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.