instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int irda_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct irda_sock *self;
if (net != &init_net)
return -EAFNOSUPPORT;
/* Check for valid socket type */
switch (sock->type) {
case SOCK_STREAM: /* For TTP connections with SAR disabled */
case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */
case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */
break;
default:
return -ESOCKTNOSUPPORT;
}
/* Allocate networking socket */
sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto, kern);
if (sk == NULL)
return -ENOMEM;
self = irda_sk(sk);
pr_debug("%s() : self is %p\n", __func__, self);
init_waitqueue_head(&self->query_wait);
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &irda_stream_ops;
self->max_sdu_size_rx = TTP_SAR_DISABLE;
break;
case SOCK_SEQPACKET:
sock->ops = &irda_seqpacket_ops;
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
case SOCK_DGRAM:
switch (protocol) {
#ifdef CONFIG_IRDA_ULTRA
case IRDAPROTO_ULTRA:
sock->ops = &irda_ultra_ops;
/* Initialise now, because we may send on unbound
* sockets. Jean II */
self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER;
self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER;
break;
#endif /* CONFIG_IRDA_ULTRA */
case IRDAPROTO_UNITDATA:
sock->ops = &irda_dgram_ops;
/* We let Unitdata conn. be like seqpack conn. */
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
/* Initialise networking socket struct */
sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */
sk->sk_family = PF_IRDA;
sk->sk_protocol = protocol;
/* Register as a client with IrLMP */
self->ckey = irlmp_register_client(0, NULL, NULL, NULL);
self->mask.word = 0xffff;
self->rx_flow = self->tx_flow = FLOW_START;
self->nslots = DISCOVERY_DEFAULT_SLOTS;
self->daddr = DEV_ADDR_ANY; /* Until we get connected */
self->saddr = 0x0; /* so IrLMP assign us any link */
return 0;
}
Commit Message: net: add validation for the socket syscall protocol argument
郭永刚 reported that one could simply crash the kernel as root by
using a simple program:
int socket_fd;
struct sockaddr_in addr;
addr.sin_port = 0;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_family = 10;
socket_fd = socket(10,3,0x40000000);
connect(socket_fd , &addr,16);
AF_INET, AF_INET6 sockets actually only support 8-bit protocol
identifiers. inet_sock's skc_protocol field thus is sized accordingly,
thus larger protocol identifiers simply cut off the higher bits and
store a zero in the protocol fields.
This could lead to e.g. NULL function pointer because as a result of
the cut off inet_num is zero and we call down to inet_autobind, which
is NULL for raw sockets.
kernel: Call Trace:
kernel: [<ffffffff816db90e>] ? inet_autobind+0x2e/0x70
kernel: [<ffffffff816db9a4>] inet_dgram_connect+0x54/0x80
kernel: [<ffffffff81645069>] SYSC_connect+0xd9/0x110
kernel: [<ffffffff810ac51b>] ? ptrace_notify+0x5b/0x80
kernel: [<ffffffff810236d8>] ? syscall_trace_enter_phase2+0x108/0x200
kernel: [<ffffffff81645e0e>] SyS_connect+0xe/0x10
kernel: [<ffffffff81779515>] tracesys_phase2+0x84/0x89
I found no particular commit which introduced this problem.
CVE: CVE-2015-8543
Cc: Cong Wang <[email protected]>
Reported-by: 郭永刚 <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | static int irda_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct irda_sock *self;
if (protocol < 0 || protocol > SK_PROTOCOL_MAX)
return -EINVAL;
if (net != &init_net)
return -EAFNOSUPPORT;
/* Check for valid socket type */
switch (sock->type) {
case SOCK_STREAM: /* For TTP connections with SAR disabled */
case SOCK_SEQPACKET: /* For TTP connections with SAR enabled */
case SOCK_DGRAM: /* For TTP Unitdata or LMP Ultra transfers */
break;
default:
return -ESOCKTNOSUPPORT;
}
/* Allocate networking socket */
sk = sk_alloc(net, PF_IRDA, GFP_KERNEL, &irda_proto, kern);
if (sk == NULL)
return -ENOMEM;
self = irda_sk(sk);
pr_debug("%s() : self is %p\n", __func__, self);
init_waitqueue_head(&self->query_wait);
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &irda_stream_ops;
self->max_sdu_size_rx = TTP_SAR_DISABLE;
break;
case SOCK_SEQPACKET:
sock->ops = &irda_seqpacket_ops;
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
case SOCK_DGRAM:
switch (protocol) {
#ifdef CONFIG_IRDA_ULTRA
case IRDAPROTO_ULTRA:
sock->ops = &irda_ultra_ops;
/* Initialise now, because we may send on unbound
* sockets. Jean II */
self->max_data_size = ULTRA_MAX_DATA - LMP_PID_HEADER;
self->max_header_size = IRDA_MAX_HEADER + LMP_PID_HEADER;
break;
#endif /* CONFIG_IRDA_ULTRA */
case IRDAPROTO_UNITDATA:
sock->ops = &irda_dgram_ops;
/* We let Unitdata conn. be like seqpack conn. */
self->max_sdu_size_rx = TTP_SAR_UNBOUND;
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
break;
default:
sk_free(sk);
return -ESOCKTNOSUPPORT;
}
/* Initialise networking socket struct */
sock_init_data(sock, sk); /* Note : set sk->sk_refcnt to 1 */
sk->sk_family = PF_IRDA;
sk->sk_protocol = protocol;
/* Register as a client with IrLMP */
self->ckey = irlmp_register_client(0, NULL, NULL, NULL);
self->mask.word = 0xffff;
self->rx_flow = self->tx_flow = FLOW_START;
self->nslots = DISCOVERY_DEFAULT_SLOTS;
self->daddr = DEV_ADDR_ANY; /* Until we get connected */
self->saddr = 0x0; /* so IrLMP assign us any link */
return 0;
}
| 166,566 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, "w.ufdio");
umask(old_umask);
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
Commit Message: Don't follow symlinks on file creation (CVE-2017-7501)
Open newly created files with O_EXCL to prevent symlink tricks.
When reopening hardlinks for writing the actual content, use append
mode instead. This is compatible with the write-only permissions but
is not destructive in case we got redirected to somebody elses file,
verify the target before actually writing anything.
As these are files with the temporary suffix, errors mean a local
user with sufficient privileges to break the installation of the package
anyway is trying to goof us on purpose, don't bother trying to mend it
(we couldn't fix the hardlink case anyhow) but just bail out.
Based on a patch by Florian Festi.
CWE ID: CWE-59 | static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int nodigest, int nocontent)
static int expandRegular(rpmfi fi, const char *dest, rpmpsm psm, int exclusive, int nodigest, int nocontent)
{
FD_t wfd = NULL;
int rc = 0;
/* Create the file with 0200 permissions (write by owner). */
{
mode_t old_umask = umask(0577);
wfd = Fopen(dest, exclusive ? "wx.ufdio" : "a.ufdio");
umask(old_umask);
/* If reopening, make sure the file is what we expect */
if (!exclusive && wfd != NULL && !linkSane(wfd, dest)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
}
if (Ferror(wfd)) {
rc = RPMERR_OPEN_FAILED;
goto exit;
}
if (!nocontent)
rc = rpmfiArchiveReadToFilePsm(fi, wfd, nodigest, psm);
exit:
if (wfd) {
int myerrno = errno;
Fclose(wfd);
errno = myerrno;
}
return rc;
}
| 168,267 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void balloon_process(struct work_struct *work)
{
enum bp_state state = BP_DONE;
long credit;
do {
mutex_lock(&balloon_mutex);
credit = current_credit();
if (credit > 0) {
if (balloon_is_inflated())
state = increase_reservation(credit);
else
state = reserve_additional_memory();
}
if (credit < 0)
state = decrease_reservation(-credit, GFP_BALLOON);
state = update_schedule(state);
mutex_unlock(&balloon_mutex);
cond_resched();
} while (credit && state == BP_DONE);
/* Schedule more work if there is some still to be done. */
if (state == BP_EAGAIN)
schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ);
}
Commit Message: xen: let alloc_xenballooned_pages() fail if not enough memory free
commit a1078e821b605813b63bf6bca414a85f804d5c66 upstream.
Instead of trying to allocate pages with GFP_USER in
add_ballooned_pages() check the available free memory via
si_mem_available(). GFP_USER is far less limiting memory exhaustion
than the test via si_mem_available().
This will avoid dom0 running out of memory due to excessive foreign
page mappings especially on ARM and on x86 in PVH mode, as those don't
have a pre-ballooned area which can be used for foreign mappings.
As the normal ballooning suffers from the same problem don't balloon
down more than si_mem_available() pages in one iteration. At the same
time limit the default maximum number of retries.
This is part of XSA-300.
Signed-off-by: Juergen Gross <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-400 | static void balloon_process(struct work_struct *work)
{
enum bp_state state = BP_DONE;
long credit;
do {
mutex_lock(&balloon_mutex);
credit = current_credit();
if (credit > 0) {
if (balloon_is_inflated())
state = increase_reservation(credit);
else
state = reserve_additional_memory();
}
if (credit < 0) {
long n_pages;
n_pages = min(-credit, si_mem_available());
state = decrease_reservation(n_pages, GFP_BALLOON);
if (state == BP_DONE && n_pages != -credit &&
n_pages < totalreserve_pages)
state = BP_EAGAIN;
}
state = update_schedule(state);
mutex_unlock(&balloon_mutex);
cond_resched();
} while (credit && state == BP_DONE);
/* Schedule more work if there is some still to be done. */
if (state == BP_EAGAIN)
schedule_delayed_work(&balloon_worker, balloon_stats.schedule_delay * HZ);
}
| 169,494 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt)
{
unsigned int i;
/* One for each receive buffer on this connection. */
i = xprt->sc_max_requests;
while (i--) {
struct svc_rdma_req_map *map;
map = alloc_req_map(GFP_KERNEL);
if (!map) {
dprintk("svcrdma: No memory for request map\n");
return false;
}
list_add(&map->free, &xprt->sc_maps);
}
return true;
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | static bool svc_rdma_prealloc_maps(struct svcxprt_rdma *xprt)
| 168,182 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int disrsi_(
int stream,
int *negate,
unsigned *value,
unsigned count)
{
int c;
unsigned locval;
unsigned ndigs;
char *cp;
char scratch[DIS_BUFSIZ+1];
assert(negate != NULL);
assert(value != NULL);
assert(count);
assert(stream >= 0);
assert(dis_getc != NULL);
assert(dis_gets != NULL);
memset(scratch, 0, DIS_BUFSIZ+1);
if (dis_umaxd == 0)
disiui_();
switch (c = (*dis_getc)(stream))
{
case '-':
case '+':
*negate = c == '-';
if ((*dis_gets)(stream, scratch, count) != (int)count)
{
return(DIS_EOD);
}
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
goto overflow;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
goto overflow;
}
cp = scratch;
locval = 0;
do
{
if (((c = *cp++) < '0') || (c > '9'))
{
return(DIS_NONDIGIT);
}
locval = 10 * locval + c - '0';
}
while (--count);
*value = locval;
return (DIS_SUCCESS);
break;
case '0':
return (DIS_LEADZRO);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
ndigs = c - '0';
if (count > 1)
{
if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1)
{
return(DIS_EOD);
}
cp = scratch;
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
break;
*cp = c;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
break;
}
while (--count)
{
if (((c = *++cp) < '0') || (c > '9'))
{
return(DIS_NONDIGIT);
}
ndigs = 10 * ndigs + c - '0';
}
} /* END if (count > 1) */
return(disrsi_(stream, negate, value, ndigs));
/*NOTREACHED*/
break;
case - 1:
return(DIS_EOD);
/*NOTREACHED*/
break;
case -2:
return(DIS_EOF);
/*NOTREACHED*/
break;
default:
return(DIS_NONDIGIT);
/*NOTREACHED*/
break;
}
*negate = FALSE;
overflow:
*value = UINT_MAX;
return(DIS_OVERFLOW);
} /* END disrsi_() */
Commit Message: Merge pull request #171 into 2.5-fixes.
CWE ID: CWE-119 | int disrsi_(
int stream,
int *negate,
unsigned *value,
unsigned count)
{
int c;
unsigned locval;
unsigned ndigs;
char *cp;
char scratch[DIS_BUFSIZ+1];
assert(negate != NULL);
assert(value != NULL);
assert(count);
assert(stream >= 0);
assert(dis_getc != NULL);
assert(dis_gets != NULL);
memset(scratch, 0, DIS_BUFSIZ+1);
if (dis_umaxd == 0)
disiui_();
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
goto overflow;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
goto overflow;
}
switch (c = (*dis_getc)(stream))
{
case '-':
case '+':
*negate = c == '-';
if ((*dis_gets)(stream, scratch, count) != (int)count)
{
return(DIS_EOD);
}
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
goto overflow;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
goto overflow;
}
cp = scratch;
locval = 0;
do
{
if (((c = *cp++) < '0') || (c > '9'))
{
return(DIS_NONDIGIT);
}
locval = 10 * locval + c - '0';
}
while (--count);
*value = locval;
return (DIS_SUCCESS);
break;
case '0':
return (DIS_LEADZRO);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
ndigs = c - '0';
if (count > 1)
{
if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1)
{
return(DIS_EOD);
}
cp = scratch;
if (count >= dis_umaxd)
{
if (count > dis_umaxd)
break;
*cp = c;
if (memcmp(scratch, dis_umax, dis_umaxd) > 0)
break;
}
while (--count)
{
if (((c = *++cp) < '0') || (c > '9'))
{
return(DIS_NONDIGIT);
}
ndigs = 10 * ndigs + c - '0';
}
} /* END if (count > 1) */
return(disrsi_(stream, negate, value, ndigs));
/*NOTREACHED*/
break;
case - 1:
return(DIS_EOD);
/*NOTREACHED*/
break;
case -2:
return(DIS_EOF);
/*NOTREACHED*/
break;
default:
return(DIS_NONDIGIT);
/*NOTREACHED*/
break;
}
*negate = FALSE;
overflow:
*value = UINT_MAX;
return(DIS_OVERFLOW);
} /* END disrsi_() */
| 166,441 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE omx_video::use_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes,
OMX_IN OMX_U8* buffer)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
unsigned char *buf_addr = NULL;
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("Inside use_output_buffer()");
if (bytes != m_sOutPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: use_output_buffer: Size Mismatch!! "
"bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sOutPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_out_mem_ptr) {
output_use_buffer = true;
int nBufHdrSize = 0;
DEBUG_PRINT_LOW("Allocating First Output Buffer(%u)",(unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
if (m_out_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_out_mem_ptr");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
if (m_out_mem_ptr) {
bufHdr = m_out_mem_ptr;
DEBUG_PRINT_LOW("Memory Allocation Succeeded for OUT port%p",m_out_mem_ptr);
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: Output buf mem alloc failed[0x%p]",m_out_mem_ptr);
eRet = OMX_ErrorInsufficientResources;
}
}
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)buffer;
(*bufferHdr)->pAppPrivate = appData;
if (!m_use_output_pmem) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = (m_sOutPortDef.nBufferSize + (SZ_4K - 1)) & ~(SZ_4K - 1);
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,0);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(
m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap() Failed");
close(m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
} else {
OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO*>((*bufferHdr)->pAppPrivate);
DEBUG_PRINT_LOW("Inside qcom_ext pParam: %p", pParam);
if (pParam) {
DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (int)pParam->offset);
m_pOutput_pmem[i].fd = pParam->pmem_fd;
m_pOutput_pmem[i].offset = pParam->offset;
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].buffer = (unsigned char *)buffer;
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM o/p UseBuffer case");
return OMX_ErrorBadParameter;
}
buf_addr = (unsigned char *)buffer;
}
DEBUG_PRINT_LOW("use_out:: bufhdr = %p, pBuffer = %p, m_pOutput_pmem[i].buffer = %p",
(*bufferHdr), (*bufferHdr)->pBuffer, m_pOutput_pmem[i].buffer);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf Failed for o/p buf");
return OMX_ErrorInsufficientResources;
}
BITMASK_SET(&m_out_bm_count,i);
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p Buffers have been Used, invalid use_buf call for "
"index = %u", i);
eRet = OMX_ErrorInsufficientResources;
}
}
return eRet;
}
Commit Message: DO NOT MERGE mm-video-v4l2: venc: add checks before accessing heap pointers
Heap pointers do not point to user virtual addresses in case
of secure session.
Set them to NULL and add checks to avoid accesing them
Bug: 28815329
Bug: 28920116
Change-Id: I94fd5808e753b58654d65e175d3857ef46ffba26
CWE ID: CWE-200 | OMX_ERRORTYPE omx_video::use_output_buffer(
OMX_IN OMX_HANDLETYPE hComp,
OMX_INOUT OMX_BUFFERHEADERTYPE** bufferHdr,
OMX_IN OMX_U32 port,
OMX_IN OMX_PTR appData,
OMX_IN OMX_U32 bytes,
OMX_IN OMX_U8* buffer)
{
(void)hComp, (void)port;
OMX_ERRORTYPE eRet = OMX_ErrorNone;
OMX_BUFFERHEADERTYPE *bufHdr= NULL; // buffer header
unsigned i= 0; // Temporary counter
unsigned char *buf_addr = NULL;
#ifdef _MSM8974_
int align_size;
#endif
DEBUG_PRINT_HIGH("Inside use_output_buffer()");
if (bytes != m_sOutPortDef.nBufferSize) {
DEBUG_PRINT_ERROR("ERROR: use_output_buffer: Size Mismatch!! "
"bytes[%u] != Port.nBufferSize[%u]", (unsigned int)bytes, (unsigned int)m_sOutPortDef.nBufferSize);
return OMX_ErrorBadParameter;
}
if (!m_out_mem_ptr) {
output_use_buffer = true;
int nBufHdrSize = 0;
DEBUG_PRINT_LOW("Allocating First Output Buffer(%u)",(unsigned int)m_sOutPortDef.nBufferCountActual);
nBufHdrSize = m_sOutPortDef.nBufferCountActual * sizeof(OMX_BUFFERHEADERTYPE);
/*
* Memory for output side involves the following:
* 1. Array of Buffer Headers
* 2. Bitmask array to hold the buffer allocation details
* In order to minimize the memory management entire allocation
* is done in one step.
*/
m_out_mem_ptr = (OMX_BUFFERHEADERTYPE *)calloc(nBufHdrSize,1);
if (m_out_mem_ptr == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_out_mem_ptr");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem = (struct pmem *) calloc(sizeof (struct pmem), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_pmem == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_pmem");
return OMX_ErrorInsufficientResources;
}
#ifdef USE_ION
m_pOutput_ion = (struct venc_ion *) calloc(sizeof (struct venc_ion), m_sOutPortDef.nBufferCountActual);
if (m_pOutput_ion == NULL) {
DEBUG_PRINT_ERROR("ERROR: calloc() Failed for m_pOutput_ion");
return OMX_ErrorInsufficientResources;
}
#endif
if (m_out_mem_ptr) {
bufHdr = m_out_mem_ptr;
DEBUG_PRINT_LOW("Memory Allocation Succeeded for OUT port%p",m_out_mem_ptr);
for (i=0; i < m_sOutPortDef.nBufferCountActual ; i++) {
bufHdr->nSize = sizeof(OMX_BUFFERHEADERTYPE);
bufHdr->nVersion.nVersion = OMX_SPEC_VERSION;
bufHdr->nAllocLen = bytes;
bufHdr->nFilledLen = 0;
bufHdr->pAppPrivate = appData;
bufHdr->nOutputPortIndex = PORT_INDEX_OUT;
bufHdr->pBuffer = NULL;
bufHdr++;
m_pOutput_pmem[i].fd = -1;
#ifdef USE_ION
m_pOutput_ion[i].ion_device_fd =-1;
m_pOutput_ion[i].fd_ion_data.fd=-1;
m_pOutput_ion[i].ion_alloc_data.handle = 0;
#endif
}
} else {
DEBUG_PRINT_ERROR("ERROR: Output buf mem alloc failed[0x%p]",m_out_mem_ptr);
eRet = OMX_ErrorInsufficientResources;
}
}
for (i=0; i< m_sOutPortDef.nBufferCountActual; i++) {
if (BITMASK_ABSENT(&m_out_bm_count,i)) {
break;
}
}
if (eRet == OMX_ErrorNone) {
if (i < m_sOutPortDef.nBufferCountActual) {
*bufferHdr = (m_out_mem_ptr + i );
(*bufferHdr)->pBuffer = (OMX_U8 *)buffer;
(*bufferHdr)->pAppPrivate = appData;
if (!m_use_output_pmem) {
#ifdef USE_ION
#ifdef _MSM8974_
align_size = (m_sOutPortDef.nBufferSize + (SZ_4K - 1)) & ~(SZ_4K - 1);
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(align_size,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,0);
#else
m_pOutput_ion[i].ion_device_fd = alloc_map_ion_memory(
m_sOutPortDef.nBufferSize,
&m_pOutput_ion[i].ion_alloc_data,
&m_pOutput_ion[i].fd_ion_data,ION_FLAG_CACHED);
#endif
if (m_pOutput_ion[i].ion_device_fd < 0) {
DEBUG_PRINT_ERROR("ERROR:ION device open() Failed");
return OMX_ErrorInsufficientResources;
}
m_pOutput_pmem[i].fd = m_pOutput_ion[i].fd_ion_data.fd;
#else
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
if (m_pOutput_pmem[i].fd == 0) {
m_pOutput_pmem[i].fd = open (MEM_DEVICE,O_RDWR);
}
if (m_pOutput_pmem[i].fd < 0) {
DEBUG_PRINT_ERROR("ERROR: /dev/pmem_adsp open() Failed");
return OMX_ErrorInsufficientResources;
}
#endif
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].offset = 0;
m_pOutput_pmem[i].buffer = NULL;
if(!secure_session) {
#ifdef _MSM8974_
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
align_size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#else
m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL,
m_pOutput_pmem[i].size,PROT_READ|PROT_WRITE,
MAP_SHARED,m_pOutput_pmem[i].fd,0);
#endif
if (m_pOutput_pmem[i].buffer == MAP_FAILED) {
DEBUG_PRINT_ERROR("ERROR: mmap() Failed");
m_pOutput_pmem[i].buffer = NULL;
close(m_pOutput_pmem[i].fd);
#ifdef USE_ION
free_ion_memory(&m_pOutput_ion[i]);
#endif
return OMX_ErrorInsufficientResources;
}
}
} else {
OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO *pParam = reinterpret_cast<OMX_QCOM_PLATFORM_PRIVATE_PMEM_INFO*>((*bufferHdr)->pAppPrivate);
DEBUG_PRINT_LOW("Inside qcom_ext pParam: %p", pParam);
if (pParam) {
DEBUG_PRINT_LOW("Inside qcom_ext with luma:(fd:%lu,offset:0x%x)", pParam->pmem_fd, (int)pParam->offset);
m_pOutput_pmem[i].fd = pParam->pmem_fd;
m_pOutput_pmem[i].offset = pParam->offset;
m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize;
m_pOutput_pmem[i].buffer = (unsigned char *)buffer;
} else {
DEBUG_PRINT_ERROR("ERROR: Invalid AppData given for PMEM o/p UseBuffer case");
return OMX_ErrorBadParameter;
}
buf_addr = (unsigned char *)buffer;
}
DEBUG_PRINT_LOW("use_out:: bufhdr = %p, pBuffer = %p, m_pOutput_pmem[i].buffer = %p",
(*bufferHdr), (*bufferHdr)->pBuffer, m_pOutput_pmem[i].buffer);
if (dev_use_buf(&m_pOutput_pmem[i],PORT_INDEX_OUT,i) != true) {
DEBUG_PRINT_ERROR("ERROR: dev_use_buf Failed for o/p buf");
return OMX_ErrorInsufficientResources;
}
BITMASK_SET(&m_out_bm_count,i);
} else {
DEBUG_PRINT_ERROR("ERROR: All o/p Buffers have been Used, invalid use_buf call for "
"index = %u", i);
eRet = OMX_ErrorInsufficientResources;
}
}
return eRet;
}
| 173,504 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Object> object)
{
if (!enabled()) {
NOTREACHED();
return v8::Null(m_isolate);
}
v8::Local<v8::Value> argv[] = { object };
v8::Local<v8::Value> location = callDebuggerMethod("getGeneratorObjectLocation", 1, argv).ToLocalChecked();
if (!location->IsObject())
return v8::Null(m_isolate);
v8::Local<v8::Context> context = m_debuggerContext.Get(m_isolate);
if (!markAsInternal(context, v8::Local<v8::Object>::Cast(location), V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return location;
}
Commit Message: [DevTools] Copy objects from debugger context to inspected context properly.
BUG=637594
Review-Url: https://codereview.chromium.org/2253643002
Cr-Commit-Position: refs/heads/master@{#412436}
CWE ID: CWE-79 | v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Object> object)
v8::Local<v8::Value> V8Debugger::generatorObjectLocation(v8::Local<v8::Context> context, v8::Local<v8::Object> object)
{
if (!enabled()) {
NOTREACHED();
return v8::Null(m_isolate);
}
v8::Local<v8::Value> argv[] = { object };
v8::Local<v8::Value> location = callDebuggerMethod("getGeneratorObjectLocation", 1, argv).ToLocalChecked();
v8::Local<v8::Value> copied;
if (!copyValueFromDebuggerContext(m_isolate, debuggerContext(), context, location).ToLocal(&copied) || !copied->IsObject())
return v8::Null(m_isolate);
if (!markAsInternal(context, v8::Local<v8::Object>::Cast(copied), V8InternalValueType::kLocation))
return v8::Null(m_isolate);
return copied;
}
| 172,067 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: header_put_byte (SF_PRIVATE *psf, char x)
{ if (psf->headindex < SIGNED_SIZEOF (psf->header) - 1)
psf->header [psf->headindex++] = x ;
} /* header_put_byte */
Commit Message: src/ : Move to a variable length header buffer
Previously, the `psf->header` buffer was a fixed length specified by
`SF_HEADER_LEN` which was set to `12292`. This was problematic for
two reasons; this value was un-necessarily large for the majority
of files and too small for some others.
Now the size of the header buffer starts at 256 bytes and grows as
necessary up to a maximum of 100k.
CWE ID: CWE-119 | header_put_byte (SF_PRIVATE *psf, char x)
{ psf->header.ptr [psf->header.indx++] = x ;
} /* header_put_byte */
| 170,053 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ClipboardMessageFilter::OnWriteObjectsSync(
const ui::Clipboard::ObjectMap& objects,
base::SharedMemoryHandle bitmap_handle) {
DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
<< "Bad bitmap handle";
scoped_ptr<ui::Clipboard::ObjectMap> long_living_objects(
new ui::Clipboard::ObjectMap(objects));
if (!ui::Clipboard::ReplaceSharedMemHandle(
long_living_objects.get(), bitmap_handle, PeerHandle()))
return;
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&WriteObjectsOnUIThread,
base::Owned(long_living_objects.release())));
}
Commit Message: Refactor ui::Clipboard::ObjectMap sanitization in ClipboardMsgFilter.
BUG=352395
[email protected]
[email protected]
Review URL: https://codereview.chromium.org/200523004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@257164 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ClipboardMessageFilter::OnWriteObjectsSync(
const ui::Clipboard::ObjectMap& objects,
base::SharedMemoryHandle bitmap_handle) {
DCHECK(base::SharedMemory::IsHandleValid(bitmap_handle))
<< "Bad bitmap handle";
scoped_ptr<ui::Clipboard::ObjectMap> long_living_objects(
new ui::Clipboard::ObjectMap(objects));
SanitizeObjectMap(long_living_objects.get(), kAllowBitmap);
if (!ui::Clipboard::ReplaceSharedMemHandle(
long_living_objects.get(), bitmap_handle, PeerHandle()))
return;
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&WriteObjectsOnUIThread,
base::Owned(long_living_objects.release())));
}
| 171,692 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int iwl_process_add_sta_resp(struct iwl_priv *priv,
struct iwl_addsta_cmd *addsta,
struct iwl_rx_packet *pkt)
{
u8 sta_id = addsta->sta.sta_id;
unsigned long flags;
int ret = -EIO;
if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
pkt->hdr.flags);
return ret;
}
IWL_DEBUG_INFO(priv, "Processing response for adding station %u\n",
sta_id);
spin_lock_irqsave(&priv->shrd->sta_lock, flags);
switch (pkt->u.add_sta.status) {
case ADD_STA_SUCCESS_MSK:
IWL_DEBUG_INFO(priv, "REPLY_ADD_STA PASSED\n");
iwl_sta_ucode_activate(priv, sta_id);
ret = 0;
break;
case ADD_STA_NO_ROOM_IN_TABLE:
IWL_ERR(priv, "Adding station %d failed, no room in table.\n",
sta_id);
break;
case ADD_STA_NO_BLOCK_ACK_RESOURCE:
IWL_ERR(priv, "Adding station %d failed, no block ack "
"resource.\n", sta_id);
break;
case ADD_STA_MODIFY_NON_EXIST_STA:
IWL_ERR(priv, "Attempting to modify non-existing station %d\n",
sta_id);
break;
default:
IWL_DEBUG_ASSOC(priv, "Received REPLY_ADD_STA:(0x%08X)\n",
pkt->u.add_sta.status);
break;
}
IWL_DEBUG_INFO(priv, "%s station id %u addr %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
sta_id, priv->stations[sta_id].sta.sta.addr);
/*
* XXX: The MAC address in the command buffer is often changed from
* the original sent to the device. That is, the MAC address
* written to the command buffer often is not the same MAC address
* read from the command buffer when the command returns. This
* issue has not yet been resolved and this debugging is left to
* observe the problem.
*/
IWL_DEBUG_INFO(priv, "%s station according to cmd buffer %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
addsta->sta.addr);
spin_unlock_irqrestore(&priv->shrd->sta_lock, flags);
return ret;
}
Commit Message: iwlwifi: Sanity check for sta_id
On my testing, I saw some strange behavior
[ 421.739708] iwlwifi 0000:01:00.0: ACTIVATE a non DRIVER active station id 148 addr 00:00:00:00:00:00
[ 421.739719] iwlwifi 0000:01:00.0: iwl_sta_ucode_activate Added STA id 148 addr 00:00:00:00:00:00 to uCode
not sure how it happen, but adding the sanity check to prevent memory
corruption
Signed-off-by: Wey-Yi Guy <[email protected]>
Signed-off-by: John W. Linville <[email protected]>
CWE ID: CWE-119 | static int iwl_process_add_sta_resp(struct iwl_priv *priv,
struct iwl_addsta_cmd *addsta,
struct iwl_rx_packet *pkt)
{
u8 sta_id = addsta->sta.sta_id;
unsigned long flags;
int ret = -EIO;
if (pkt->hdr.flags & IWL_CMD_FAILED_MSK) {
IWL_ERR(priv, "Bad return from REPLY_ADD_STA (0x%08X)\n",
pkt->hdr.flags);
return ret;
}
IWL_DEBUG_INFO(priv, "Processing response for adding station %u\n",
sta_id);
spin_lock_irqsave(&priv->shrd->sta_lock, flags);
switch (pkt->u.add_sta.status) {
case ADD_STA_SUCCESS_MSK:
IWL_DEBUG_INFO(priv, "REPLY_ADD_STA PASSED\n");
ret = iwl_sta_ucode_activate(priv, sta_id);
break;
case ADD_STA_NO_ROOM_IN_TABLE:
IWL_ERR(priv, "Adding station %d failed, no room in table.\n",
sta_id);
break;
case ADD_STA_NO_BLOCK_ACK_RESOURCE:
IWL_ERR(priv, "Adding station %d failed, no block ack "
"resource.\n", sta_id);
break;
case ADD_STA_MODIFY_NON_EXIST_STA:
IWL_ERR(priv, "Attempting to modify non-existing station %d\n",
sta_id);
break;
default:
IWL_DEBUG_ASSOC(priv, "Received REPLY_ADD_STA:(0x%08X)\n",
pkt->u.add_sta.status);
break;
}
IWL_DEBUG_INFO(priv, "%s station id %u addr %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
sta_id, priv->stations[sta_id].sta.sta.addr);
/*
* XXX: The MAC address in the command buffer is often changed from
* the original sent to the device. That is, the MAC address
* written to the command buffer often is not the same MAC address
* read from the command buffer when the command returns. This
* issue has not yet been resolved and this debugging is left to
* observe the problem.
*/
IWL_DEBUG_INFO(priv, "%s station according to cmd buffer %pM\n",
priv->stations[sta_id].sta.mode ==
STA_CONTROL_MODIFY_MSK ? "Modified" : "Added",
addsta->sta.addr);
spin_unlock_irqrestore(&priv->shrd->sta_lock, flags);
return ret;
}
| 169,868 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PromoResourceService::ScheduleNotification(double promo_start,
double promo_end) {
if (promo_start > 0 && promo_end > 0) {
const int64 ms_until_start =
static_cast<int64>((base::Time::FromDoubleT(
promo_start) - base::Time::Now()).InMilliseconds());
const int64 ms_until_end =
static_cast<int64>((base::Time::FromDoubleT(
promo_end) - base::Time::Now()).InMilliseconds());
if (ms_until_start > 0) {
PostNotification(ms_until_start);
} else if (ms_until_end > 0) {
if (ms_until_start <= 0) {
PostNotification(0);
}
PostNotification(ms_until_end);
}
}
}
Commit Message: Refresh promo notifications as they're fetched
The "guard" existed for notification scheduling was preventing
"turn-off a promo" and "update a promo" scenarios.
Yet I do not believe it was adding any actual safety: if things
on a server backend go wrong, the clients will be affected one
way or the other, and it is better to have an option to shut
the malformed promo down "as quickly as possible" (~in 12-24 hours).
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10696204
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void PromoResourceService::ScheduleNotification(double promo_start,
double promo_end) {
if (promo_start > 0 && promo_end > 0) {
const int64 ms_until_start =
static_cast<int64>((base::Time::FromDoubleT(
promo_start) - base::Time::Now()).InMilliseconds());
const int64 ms_until_end =
static_cast<int64>((base::Time::FromDoubleT(
promo_end) - base::Time::Now()).InMilliseconds());
if (ms_until_start > 0) {
PostNotification(ms_until_start);
} else if (ms_until_end > 0) {
if (ms_until_start <= 0) {
// The promo is active. Notify immediately.
PostNotification(0);
}
PostNotification(ms_until_end);
} else {
// The promo (if any) has finished. Notify immediately.
PostNotification(0);
}
} else {
// The promo (if any) was apparently cancelled. Notify immediately.
PostNotification(0);
}
}
| 170,784 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int zrle_send_framebuffer_update(VncState *vs, int x, int y,
int w, int h)
{
bool be = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG);
size_t bytes;
int zywrle_level;
if (vs->zrle.type == VNC_ENCODING_ZYWRLE) {
if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1
|| vs->tight.quality == 9) {
zywrle_level = 0;
vs->zrle.type = VNC_ENCODING_ZRLE;
} else if (vs->tight.quality < 3) {
zywrle_level = 3;
} else if (vs->tight.quality < 6) {
zywrle_level = 2;
} else {
zywrle_level = 1;
}
} else {
zywrle_level = 0;
}
vnc_zrle_start(vs);
switch(vs->clientds.pf.bytes_per_pixel) {
case 1:
zrle_encode_8ne(vs, x, y, w, h, zywrle_level);
break;
case 2:
if (vs->clientds.pf.gmax > 0x1F) {
if (be) {
zrle_encode_16be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_16le(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_15be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_15le(vs, x, y, w, h, zywrle_level);
}
}
break;
case 4:
{
bool fits_in_ls3bytes;
bool fits_in_ms3bytes;
fits_in_ls3bytes =
((vs->clientds.pf.rmax << vs->clientds.pf.rshift) < (1 << 24) &&
(vs->clientds.pf.gmax << vs->clientds.pf.gshift) < (1 << 24) &&
(vs->clientds.pf.bmax << vs->clientds.pf.bshift) < (1 << 24));
fits_in_ms3bytes = (vs->clientds.pf.rshift > 7 &&
vs->clientds.pf.gshift > 7 &&
vs->clientds.pf.bshift > 7);
if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) {
if (be) {
zrle_encode_24abe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ale(vs, x, y, w, h, zywrle_level);
}
} else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) {
if (be) {
zrle_encode_24bbe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ble(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_32be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_32le(vs, x, y, w, h, zywrle_level);
}
}
}
break;
}
vnc_zrle_stop(vs);
bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION);
vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type);
vnc_write_u32(vs, bytes);
vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset);
return 1;
}
Commit Message:
CWE ID: CWE-125 | static int zrle_send_framebuffer_update(VncState *vs, int x, int y,
int w, int h)
{
bool be = vs->client_be;
size_t bytes;
int zywrle_level;
if (vs->zrle.type == VNC_ENCODING_ZYWRLE) {
if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1
|| vs->tight.quality == 9) {
zywrle_level = 0;
vs->zrle.type = VNC_ENCODING_ZRLE;
} else if (vs->tight.quality < 3) {
zywrle_level = 3;
} else if (vs->tight.quality < 6) {
zywrle_level = 2;
} else {
zywrle_level = 1;
}
} else {
zywrle_level = 0;
}
vnc_zrle_start(vs);
switch (vs->client_pf.bytes_per_pixel) {
case 1:
zrle_encode_8ne(vs, x, y, w, h, zywrle_level);
break;
case 2:
if (vs->client_pf.gmax > 0x1F) {
if (be) {
zrle_encode_16be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_16le(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_15be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_15le(vs, x, y, w, h, zywrle_level);
}
}
break;
case 4:
{
bool fits_in_ls3bytes;
bool fits_in_ms3bytes;
fits_in_ls3bytes =
((vs->client_pf.rmax << vs->client_pf.rshift) < (1 << 24) &&
(vs->client_pf.gmax << vs->client_pf.gshift) < (1 << 24) &&
(vs->client_pf.bmax << vs->client_pf.bshift) < (1 << 24));
fits_in_ms3bytes = (vs->client_pf.rshift > 7 &&
vs->client_pf.gshift > 7 &&
vs->client_pf.bshift > 7);
if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) {
if (be) {
zrle_encode_24abe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ale(vs, x, y, w, h, zywrle_level);
}
} else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) {
if (be) {
zrle_encode_24bbe(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_24ble(vs, x, y, w, h, zywrle_level);
}
} else {
if (be) {
zrle_encode_32be(vs, x, y, w, h, zywrle_level);
} else {
zrle_encode_32le(vs, x, y, w, h, zywrle_level);
}
}
}
break;
}
vnc_zrle_stop(vs);
bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION);
vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type);
vnc_write_u32(vs, bytes);
vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset);
return 1;
}
| 165,468 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int asymmetric_key_match_preparse(struct key_match_data *match_data)
{
match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
return 0;
}
Commit Message: KEYS: Remove key_type::match in favour of overriding default by match_preparse
A previous patch added a ->match_preparse() method to the key type. This is
allowed to override the function called by the iteration algorithm.
Therefore, we can just set a default that simply checks for an exact match of
the key description with the original criterion data and allow match_preparse
to override it as needed.
The key_type::match op is then redundant and can be removed, as can the
user_match() function.
Signed-off-by: David Howells <[email protected]>
Acked-by: Vivek Goyal <[email protected]>
CWE ID: CWE-476 | static int asymmetric_key_match_preparse(struct key_match_data *match_data)
{
match_data->lookup_type = KEYRING_SEARCH_LOOKUP_ITERATE;
match_data->cmp = asymmetric_key_cmp;
return 0;
}
| 168,437 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *raw_data)
{
struct super_block *s;
struct ecryptfs_sb_info *sbi;
struct ecryptfs_dentry_info *root_info;
const char *err = "Getting sb failed";
struct inode *inode;
struct path path;
int rc;
sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL);
if (!sbi) {
rc = -ENOMEM;
goto out;
}
rc = ecryptfs_parse_options(sbi, raw_data);
if (rc) {
err = "Error parsing options";
goto out;
}
s = sget(fs_type, NULL, set_anon_super, NULL);
if (IS_ERR(s)) {
rc = PTR_ERR(s);
goto out;
}
s->s_flags = flags;
rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY);
if (rc)
goto out1;
ecryptfs_set_superblock_private(s, sbi);
s->s_bdi = &sbi->bdi;
/* ->kill_sb() will take care of sbi after that point */
sbi = NULL;
s->s_op = &ecryptfs_sops;
s->s_d_op = &ecryptfs_dops;
err = "Reading sb failed";
rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path);
if (rc) {
ecryptfs_printk(KERN_WARNING, "kern_path() failed\n");
goto out1;
}
if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) {
rc = -EINVAL;
printk(KERN_ERR "Mount on filesystem of type "
"eCryptfs explicitly disallowed due to "
"known incompatibilities\n");
goto out_free;
}
ecryptfs_set_superblock_lower(s, path.dentry->d_sb);
s->s_maxbytes = path.dentry->d_sb->s_maxbytes;
s->s_blocksize = path.dentry->d_sb->s_blocksize;
s->s_magic = ECRYPTFS_SUPER_MAGIC;
inode = ecryptfs_get_inode(path.dentry->d_inode, s);
rc = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_free;
s->s_root = d_alloc_root(inode);
if (!s->s_root) {
iput(inode);
rc = -ENOMEM;
goto out_free;
}
rc = -ENOMEM;
root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL);
if (!root_info)
goto out_free;
/* ->kill_sb() will take care of root_info */
ecryptfs_set_dentry_private(s->s_root, root_info);
ecryptfs_set_dentry_lower(s->s_root, path.dentry);
ecryptfs_set_dentry_lower_mnt(s->s_root, path.mnt);
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
out_free:
path_put(&path);
out1:
deactivate_locked_super(s);
out:
if (sbi) {
ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat);
kmem_cache_free(ecryptfs_sb_info_cache, sbi);
}
printk(KERN_ERR "%s; rc = [%d]\n", err, rc);
return ERR_PTR(rc);
}
Commit Message: Ecryptfs: Add mount option to check uid of device being mounted = expect uid
Close a TOCTOU race for mounts done via ecryptfs-mount-private. The mount
source (device) can be raced when the ownership test is done in userspace.
Provide Ecryptfs a means to force the uid check at mount time.
Signed-off-by: John Johansen <[email protected]>
Cc: <[email protected]>
Signed-off-by: Tyler Hicks <[email protected]>
CWE ID: CWE-264 | static struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags,
const char *dev_name, void *raw_data)
{
struct super_block *s;
struct ecryptfs_sb_info *sbi;
struct ecryptfs_dentry_info *root_info;
const char *err = "Getting sb failed";
struct inode *inode;
struct path path;
uid_t check_ruid;
int rc;
sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL);
if (!sbi) {
rc = -ENOMEM;
goto out;
}
rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid);
if (rc) {
err = "Error parsing options";
goto out;
}
s = sget(fs_type, NULL, set_anon_super, NULL);
if (IS_ERR(s)) {
rc = PTR_ERR(s);
goto out;
}
s->s_flags = flags;
rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY);
if (rc)
goto out1;
ecryptfs_set_superblock_private(s, sbi);
s->s_bdi = &sbi->bdi;
/* ->kill_sb() will take care of sbi after that point */
sbi = NULL;
s->s_op = &ecryptfs_sops;
s->s_d_op = &ecryptfs_dops;
err = "Reading sb failed";
rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path);
if (rc) {
ecryptfs_printk(KERN_WARNING, "kern_path() failed\n");
goto out1;
}
if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) {
rc = -EINVAL;
printk(KERN_ERR "Mount on filesystem of type "
"eCryptfs explicitly disallowed due to "
"known incompatibilities\n");
goto out_free;
}
if (check_ruid && path.dentry->d_inode->i_uid != current_uid()) {
rc = -EPERM;
printk(KERN_ERR "Mount of device (uid: %d) not owned by "
"requested user (uid: %d)\n",
path.dentry->d_inode->i_uid, current_uid());
goto out_free;
}
ecryptfs_set_superblock_lower(s, path.dentry->d_sb);
s->s_maxbytes = path.dentry->d_sb->s_maxbytes;
s->s_blocksize = path.dentry->d_sb->s_blocksize;
s->s_magic = ECRYPTFS_SUPER_MAGIC;
inode = ecryptfs_get_inode(path.dentry->d_inode, s);
rc = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_free;
s->s_root = d_alloc_root(inode);
if (!s->s_root) {
iput(inode);
rc = -ENOMEM;
goto out_free;
}
rc = -ENOMEM;
root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL);
if (!root_info)
goto out_free;
/* ->kill_sb() will take care of root_info */
ecryptfs_set_dentry_private(s->s_root, root_info);
ecryptfs_set_dentry_lower(s->s_root, path.dentry);
ecryptfs_set_dentry_lower_mnt(s->s_root, path.mnt);
s->s_flags |= MS_ACTIVE;
return dget(s->s_root);
out_free:
path_put(&path);
out1:
deactivate_locked_super(s);
out:
if (sbi) {
ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat);
kmem_cache_free(ecryptfs_sb_info_cache, sbi);
}
printk(KERN_ERR "%s; rc = [%d]\n", err, rc);
return ERR_PTR(rc);
}
| 165,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) {
if (isUserInteractionEvent(event))
return true;
LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject));
if (!slider.isNull() && !slider.inDragMode())
return false;
const AtomicString& type = event->type();
return type == EventTypeNames::mouseover ||
type == EventTypeNames::mouseout || type == EventTypeNames::mousemove;
}
Commit Message: Fixed volume slider element event handling
MediaControlVolumeSliderElement::defaultEventHandler has making
redundant calls to setVolume() & setMuted() on mouse activity. E.g. if
a mouse click changed the slider position, the above calls were made 4
times, once for each of these events: mousedown, input, mouseup,
DOMActive, click. This crack got exposed when PointerEvents are enabled
by default on M55, adding pointermove, pointerdown & pointerup to the
list.
This CL fixes the code to trigger the calls to setVolume() & setMuted()
only when the slider position is changed. Also added pointer events to
certain lists of mouse events in the code.
BUG=677900
Review-Url: https://codereview.chromium.org/2622273003
Cr-Commit-Position: refs/heads/master@{#446032}
CWE ID: CWE-119 | bool isUserInteractionEventForSlider(Event* event, LayoutObject* layoutObject) {
if (isUserInteractionEvent(event))
return true;
LayoutSliderItem slider = LayoutSliderItem(toLayoutSlider(layoutObject));
if (!slider.isNull() && !slider.inDragMode())
return false;
const AtomicString& type = event->type();
return type == EventTypeNames::mouseover ||
type == EventTypeNames::mouseout ||
type == EventTypeNames::mousemove ||
type == EventTypeNames::pointerover ||
type == EventTypeNames::pointerout ||
type == EventTypeNames::pointermove;
}
| 171,900 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int chan = sa->rc_channel;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->rc_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = chan;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
Commit Message: Bluetooth: Fix potential NULL dereference in RFCOMM bind callback
addr can be NULL and it should not be dereferenced before NULL checking.
Signed-off-by: Jaganath Kanakkassery <[email protected]>
Signed-off-by: Marcel Holtmann <[email protected]>
CWE ID: CWE-476 | static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc sa;
struct sock *sk = sock->sk;
int len, err = 0;
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
memset(&sa, 0, sizeof(sa));
len = min_t(unsigned int, sizeof(sa), addr_len);
memcpy(&sa, addr, len);
BT_DBG("sk %p %pMR", sk, &sa.rc_bdaddr);
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (sa.rc_channel &&
__rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);
rfcomm_pi(sk)->channel = sa.rc_channel;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
}
| 167,466 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
vp9_fdct16x16_c(in, out, stride);
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | void fdct16x16_ref(const int16_t *in, int16_t *out, int stride, int tx_type) {
void fdct16x16_ref(const int16_t *in, tran_low_t *out, int stride,
int /*tx_type*/) {
vpx_fdct16x16_c(in, out, stride);
}
| 174,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int rt_fill_info(struct net *net, __be32 dst, __be32 src,
struct flowi4 *fl4, struct sk_buff *skb, u32 portid,
u32 seq, int event, int nowait, unsigned int flags)
{
struct rtable *rt = skb_rtable(skb);
struct rtmsg *r;
struct nlmsghdr *nlh;
unsigned long expires = 0;
u32 error;
u32 metrics[RTAX_MAX];
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags);
if (nlh == NULL)
return -EMSGSIZE;
r = nlmsg_data(nlh);
r->rtm_family = AF_INET;
r->rtm_dst_len = 32;
r->rtm_src_len = 0;
r->rtm_tos = fl4->flowi4_tos;
r->rtm_table = RT_TABLE_MAIN;
if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN))
goto nla_put_failure;
r->rtm_type = rt->rt_type;
r->rtm_scope = RT_SCOPE_UNIVERSE;
r->rtm_protocol = RTPROT_UNSPEC;
r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
if (rt->rt_flags & RTCF_NOTIFY)
r->rtm_flags |= RTM_F_NOTIFY;
if (nla_put_be32(skb, RTA_DST, dst))
goto nla_put_failure;
if (src) {
r->rtm_src_len = 32;
if (nla_put_be32(skb, RTA_SRC, src))
goto nla_put_failure;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
goto nla_put_failure;
#ifdef CONFIG_IP_ROUTE_CLASSID
if (rt->dst.tclassid &&
nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid))
goto nla_put_failure;
#endif
if (!rt_is_input_route(rt) &&
fl4->saddr != src) {
if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr))
goto nla_put_failure;
}
if (rt->rt_uses_gateway &&
nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway))
goto nla_put_failure;
expires = rt->dst.expires;
if (expires) {
unsigned long now = jiffies;
if (time_before(now, expires))
expires -= now;
else
expires = 0;
}
memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics));
if (rt->rt_pmtu && expires)
metrics[RTAX_MTU - 1] = rt->rt_pmtu;
if (rtnetlink_put_metrics(skb, metrics) < 0)
goto nla_put_failure;
if (fl4->flowi4_mark &&
nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark))
goto nla_put_failure;
error = rt->dst.error;
if (rt_is_input_route(rt)) {
#ifdef CONFIG_IP_MROUTE
if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) &&
IPV4_DEVCONF_ALL(net, MC_FORWARDING)) {
int err = ipmr_get_route(net, skb,
fl4->saddr, fl4->daddr,
r, nowait);
if (err <= 0) {
if (!nowait) {
if (err == 0)
return 0;
goto nla_put_failure;
} else {
if (err == -EMSGSIZE)
goto nla_put_failure;
error = err;
}
}
} else
#endif
if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex))
goto nla_put_failure;
}
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
Commit Message: ipv4: try to cache dst_entries which would cause a redirect
Not caching dst_entries which cause redirects could be exploited by hosts
on the same subnet, causing a severe DoS attack. This effect aggravated
since commit f88649721268999 ("ipv4: fix dst race in sk_dst_get()").
Lookups causing redirects will be allocated with DST_NOCACHE set which
will force dst_release to free them via RCU. Unfortunately waiting for
RCU grace period just takes too long, we can end up with >1M dst_entries
waiting to be released and the system will run OOM. rcuos threads cannot
catch up under high softirq load.
Attaching the flag to emit a redirect later on to the specific skb allows
us to cache those dst_entries thus reducing the pressure on allocation
and deallocation.
This issue was discovered by Marcelo Leitner.
Cc: Julian Anastasov <[email protected]>
Signed-off-by: Marcelo Leitner <[email protected]>
Signed-off-by: Florian Westphal <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: Julian Anastasov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-17 | static int rt_fill_info(struct net *net, __be32 dst, __be32 src,
struct flowi4 *fl4, struct sk_buff *skb, u32 portid,
u32 seq, int event, int nowait, unsigned int flags)
{
struct rtable *rt = skb_rtable(skb);
struct rtmsg *r;
struct nlmsghdr *nlh;
unsigned long expires = 0;
u32 error;
u32 metrics[RTAX_MAX];
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags);
if (nlh == NULL)
return -EMSGSIZE;
r = nlmsg_data(nlh);
r->rtm_family = AF_INET;
r->rtm_dst_len = 32;
r->rtm_src_len = 0;
r->rtm_tos = fl4->flowi4_tos;
r->rtm_table = RT_TABLE_MAIN;
if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN))
goto nla_put_failure;
r->rtm_type = rt->rt_type;
r->rtm_scope = RT_SCOPE_UNIVERSE;
r->rtm_protocol = RTPROT_UNSPEC;
r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
if (rt->rt_flags & RTCF_NOTIFY)
r->rtm_flags |= RTM_F_NOTIFY;
if (IPCB(skb)->flags & IPSKB_DOREDIRECT)
r->rtm_flags |= RTCF_DOREDIRECT;
if (nla_put_be32(skb, RTA_DST, dst))
goto nla_put_failure;
if (src) {
r->rtm_src_len = 32;
if (nla_put_be32(skb, RTA_SRC, src))
goto nla_put_failure;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex))
goto nla_put_failure;
#ifdef CONFIG_IP_ROUTE_CLASSID
if (rt->dst.tclassid &&
nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid))
goto nla_put_failure;
#endif
if (!rt_is_input_route(rt) &&
fl4->saddr != src) {
if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr))
goto nla_put_failure;
}
if (rt->rt_uses_gateway &&
nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway))
goto nla_put_failure;
expires = rt->dst.expires;
if (expires) {
unsigned long now = jiffies;
if (time_before(now, expires))
expires -= now;
else
expires = 0;
}
memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics));
if (rt->rt_pmtu && expires)
metrics[RTAX_MTU - 1] = rt->rt_pmtu;
if (rtnetlink_put_metrics(skb, metrics) < 0)
goto nla_put_failure;
if (fl4->flowi4_mark &&
nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark))
goto nla_put_failure;
error = rt->dst.error;
if (rt_is_input_route(rt)) {
#ifdef CONFIG_IP_MROUTE
if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) &&
IPV4_DEVCONF_ALL(net, MC_FORWARDING)) {
int err = ipmr_get_route(net, skb,
fl4->saddr, fl4->daddr,
r, nowait);
if (err <= 0) {
if (!nowait) {
if (err == 0)
return 0;
goto nla_put_failure;
} else {
if (err == -EMSGSIZE)
goto nla_put_failure;
error = err;
}
}
} else
#endif
if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex))
goto nla_put_failure;
}
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0)
goto nla_put_failure;
return nlmsg_end(skb, nlh);
nla_put_failure:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
| 166,699 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void posixtimer_rearm(struct siginfo *info)
{
struct k_itimer *timr;
unsigned long flags;
timr = lock_timer(info->si_tid, &flags);
if (!timr)
return;
if (timr->it_requeue_pending == info->si_sys_private) {
timr->kclock->timer_rearm(timr);
timr->it_active = 1;
timr->it_overrun_last = timr->it_overrun;
timr->it_overrun = -1;
++timr->it_requeue_pending;
info->si_overrun += timr->it_overrun_last;
}
unlock_timer(timr, flags);
}
Commit Message: posix-timers: Sanitize overrun handling
The posix timer overrun handling is broken because the forwarding functions
can return a huge number of overruns which does not fit in an int. As a
consequence timer_getoverrun(2) and siginfo::si_overrun can turn into
random number generators.
The k_clock::timer_forward() callbacks return a 64 bit value now. Make
k_itimer::ti_overrun[_last] 64bit as well, so the kernel internal
accounting is correct. 3Remove the temporary (int) casts.
Add a helper function which clamps the overrun value returned to user space
via timer_getoverrun(2) or siginfo::si_overrun limited to a positive value
between 0 and INT_MAX. INT_MAX is an indicator for user space that the
overrun value has been clamped.
Reported-by: Team OWL337 <[email protected]>
Signed-off-by: Thomas Gleixner <[email protected]>
Acked-by: John Stultz <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Michael Kerrisk <[email protected]>
Link: https://lkml.kernel.org/r/[email protected]
CWE ID: CWE-190 | void posixtimer_rearm(struct siginfo *info)
{
struct k_itimer *timr;
unsigned long flags;
timr = lock_timer(info->si_tid, &flags);
if (!timr)
return;
if (timr->it_requeue_pending == info->si_sys_private) {
timr->kclock->timer_rearm(timr);
timr->it_active = 1;
timr->it_overrun_last = timr->it_overrun;
timr->it_overrun = -1LL;
++timr->it_requeue_pending;
info->si_overrun = timer_overrun_to_int(timr, info->si_overrun);
}
unlock_timer(timr, flags);
}
| 169,183 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: TabsCustomBindings::TabsCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("OpenChannelToTab",
base::Bind(&TabsCustomBindings::OpenChannelToTab,
base::Unretained(this)));
}
Commit Message: [Extensions] Expand bindings access checks
BUG=601149
BUG=601073
Review URL: https://codereview.chromium.org/1866103002
Cr-Commit-Position: refs/heads/master@{#387710}
CWE ID: CWE-284 | TabsCustomBindings::TabsCustomBindings(ScriptContext* context)
: ObjectBackedNativeHandler(context) {
RouteFunction("OpenChannelToTab", "tabs",
base::Bind(&TabsCustomBindings::OpenChannelToTab,
base::Unretained(this)));
}
| 172,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copyMono8(
short *dst,
const int *const *src,
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
}
}
Commit Message: FLACExtractor: copy protect mWriteBuffer
Bug: 30895578
Change-Id: I4cba36bbe3502678210e5925181683df9726b431
CWE ID: CWE-119 | static void copyMono8(
short *dst,
const int * src[FLACParser::kMaxChannels],
unsigned nSamples,
unsigned /* nChannels */) {
for (unsigned i = 0; i < nSamples; ++i) {
*dst++ = src[0][i] << 8;
}
}
| 174,017 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int read_filesystem_tables_4()
{
long long directory_table_end, table_start;
if(read_xattrs_from_disk(fd, &sBlk.s, no_xattrs, &table_start) == 0)
return FALSE;
if(read_uids_guids(&table_start) == FALSE)
return FALSE;
if(parse_exports_table(&table_start) == FALSE)
return FALSE;
if(read_fragment_table(&directory_table_end) == FALSE)
return FALSE;
if(read_inode_table(sBlk.s.inode_table_start,
sBlk.s.directory_table_start) == FALSE)
return FALSE;
if(read_directory_table(sBlk.s.directory_table_start,
directory_table_end) == FALSE)
return FALSE;
if(no_xattrs)
sBlk.s.xattr_id_table_start = SQUASHFS_INVALID_BLK;
return TRUE;
}
Commit Message: unsquashfs-4: Add more sanity checks + fix CVE-2015-4645/6
Add more filesystem table sanity checks to Unsquashfs-4 and
also properly fix CVE-2015-4645 and CVE-2015-4646.
The CVEs were raised due to Unsquashfs having variable
oveflow and stack overflow in a number of vulnerable
functions.
The suggested patch only "fixed" one such function and fixed
it badly, and so it was buggy and introduced extra bugs!
The suggested patch was not only buggy, but, it used the
essentially wrong approach too. It was "fixing" the
symptom but not the cause. The symptom is wrong values
causing overflow, the cause is filesystem corruption.
This corruption should be detected and the filesystem
rejected *before* trying to allocate memory.
This patch applies the following fixes:
1. The filesystem super-block tables are checked, and the values
must match across the filesystem.
This will trap corrupted filesystems created by Mksquashfs.
2. The maximum (theorectical) size the filesystem tables could grow
to, were analysed, and some variables were increased from int to
long long.
This analysis has been added as comments.
3. Stack allocation was removed, and a shared buffer (which is
checked and increased as necessary) is used to read the
table indexes.
Signed-off-by: Phillip Lougher <[email protected]>
CWE ID: CWE-190 | int read_filesystem_tables_4()
{
long long table_start;
/* Read xattrs */
if(sBlk.s.xattr_id_table_start != SQUASHFS_INVALID_BLK) {
/* sanity check super block contents */
if(sBlk.s.xattr_id_table_start >= sBlk.s.bytes_used) {
ERROR("read_filesystem_tables: xattr id table start too large in super block\n");
goto corrupted;
}
if(read_xattrs_from_disk(fd, &sBlk.s, no_xattrs, &table_start) == 0)
goto corrupted;
} else
table_start = sBlk.s.bytes_used;
/* Read id lookup table */
/* Sanity check super block contents */
if(sBlk.s.id_table_start >= table_start) {
ERROR("read_filesystem_tables: id table start too large in super block\n");
goto corrupted;
}
/* there should always be at least one id */
if(sBlk.s.no_ids == 0) {
ERROR("read_filesystem_tables: Bad id count in super block\n");
goto corrupted;
}
/*
* the number of ids can never be more than double the number of inodes
* (the maximum is a unique uid and gid for each inode).
*/
if(sBlk.s.no_ids > (sBlk.s.inodes * 2L)) {
ERROR("read_filesystem_tables: Bad id count in super block\n");
goto corrupted;
}
if(read_id_table(&table_start) == FALSE)
goto corrupted;
/* Read exports table */
if(sBlk.s.lookup_table_start != SQUASHFS_INVALID_BLK) {
/* sanity check super block contents */
if(sBlk.s.lookup_table_start >= table_start) {
ERROR("read_filesystem_tables: lookup table start too large in super block\n");
goto corrupted;
}
if(parse_exports_table(&table_start) == FALSE)
goto corrupted;
}
/* Read fragment table */
if(sBlk.s.fragments != 0) {
/* Sanity check super block contents */
if(sBlk.s.fragment_table_start >= table_start) {
ERROR("read_filesystem_tables: fragment table start too large in super block\n");
goto corrupted;
}
/* The number of fragments should not exceed the number of inodes */
if(sBlk.s.fragments > sBlk.s.inodes) {
ERROR("read_filesystem_tables: Bad fragment count in super block\n");
goto corrupted;
}
if(read_fragment_table(&table_start) == FALSE)
goto corrupted;
} else {
/*
* Sanity check super block contents - with 0 fragments,
* the fragment table should be empty
*/
if(sBlk.s.fragment_table_start != table_start) {
ERROR("read_filesystem_tables: fragment table start invalid in super block\n");
goto corrupted;
}
}
/* Read directory table */
/* Sanity check super block contents */
if(sBlk.s.directory_table_start >= table_start) {
ERROR("read_filesystem_tables: directory table start too large in super block\n");
goto corrupted;
}
if(read_directory_table(sBlk.s.directory_table_start,
table_start) == FALSE)
goto corrupted;
/* Read inode table */
/* Sanity check super block contents */
if(sBlk.s.inode_table_start >= sBlk.s.directory_table_start) {
ERROR("read_filesystem_tables: inode table start too large in super block\n");
goto corrupted;
}
if(read_inode_table(sBlk.s.inode_table_start,
sBlk.s.directory_table_start) == FALSE)
goto corrupted;
if(no_xattrs)
sBlk.s.xattr_id_table_start = SQUASHFS_INVALID_BLK;
return TRUE;
corrupted:
ERROR("File system corruption detected\n");
return FALSE;
}
| 168,880 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok)
#if !defined(DISABLE_NACL)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD,
OnGetReadonlyPnaclFd)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile,
OnNaClCreateTemporaryFile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats,
OnResourceTypeStats)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats,
OnUpdatedCacheStats)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension,
OnOpenChannelToExtension)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle,
OnGetExtensionMessageBundle)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener,
OnExtensionRemoveListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener,
OnExtensionAddLazyListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener,
OnExtensionRemoveLazyListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener,
OnExtensionAddFilteredListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener,
OnExtensionRemoveFilteredListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread,
OnExtensionRequestForIOThread)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck,
OnExtensionShouldUnloadAck)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID,
OnExtensionGenerateUniqueID)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests,
OnExtensionResumeRequests);
#if defined(USE_TCMALLOC)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK,
OnWriteTcmallocHeapProfile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead,
OnCanTriggerClipboardRead)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite,
OnCanTriggerClipboardWrite)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
#if defined(ENABLE_AUTOMATION)
if ((message.type() == ChromeViewHostMsg_GetCookies::ID ||
message.type() == ChromeViewHostMsg_SetCookie::ID) &&
AutomationResourceMessageFilter::ShouldFilterCookieMessages(
render_process_id_, message.routing_id())) {
IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message,
*message_was_ok)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies,
OnGetCookies)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie)
IPC_END_MESSAGE_MAP()
handled = true;
}
#endif
return handled;
}
Commit Message: Disable tcmalloc profile files.
BUG=154983
[email protected]
NOTRY=true
Review URL: https://chromiumcodereview.appspot.com/11087041
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@161048 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok)
#if !defined(DISABLE_NACL)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD,
OnGetReadonlyPnaclFd)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile,
OnNaClCreateTemporaryFile)
#endif
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats,
OnResourceTypeStats)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats,
OnUpdatedCacheStats)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension,
OnOpenChannelToExtension)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle,
OnGetExtensionMessageBundle)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener,
OnExtensionRemoveListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener,
OnExtensionAddLazyListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener,
OnExtensionRemoveLazyListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener,
OnExtensionAddFilteredListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener,
OnExtensionRemoveFilteredListener)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread,
OnExtensionRequestForIOThread)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck,
OnExtensionShouldUnloadAck)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID,
OnExtensionGenerateUniqueID)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck)
IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests,
OnExtensionResumeRequests);
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead,
OnCanTriggerClipboardRead)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite,
OnCanTriggerClipboardWrite)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
#if defined(ENABLE_AUTOMATION)
if ((message.type() == ChromeViewHostMsg_GetCookies::ID ||
message.type() == ChromeViewHostMsg_SetCookie::ID) &&
AutomationResourceMessageFilter::ShouldFilterCookieMessages(
render_process_id_, message.routing_id())) {
IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message,
*message_was_ok)
IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies,
OnGetCookies)
IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie)
IPC_END_MESSAGE_MAP()
handled = true;
}
#endif
return handled;
}
| 170,663 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL(
const String& source,
Document* owner_document) {
Document* document = frame_->GetDocument();
if (!document_loader_ ||
document->PageDismissalEventBeingDispatched() != Document::kNoDismissal)
return;
UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL);
const KURL& url = document->Url();
WebGlobalObjectReusePolicy global_object_reuse_policy =
frame_->ShouldReuseDefaultView(url)
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew;
StopAllLoaders();
SubframeLoadingDisabler disabler(document);
frame_->DetachChildren();
if (!frame_->IsAttached() || document != frame_->GetDocument())
return;
frame_->GetDocument()->Shutdown();
Client()->TransitionToCommittedForNewPage();
document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL(
url, owner_document, global_object_reuse_policy, source);
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285 | void FrameLoader::ReplaceDocumentWhileExecutingJavaScriptURL(
const String& source,
Document* owner_document) {
Document* document = frame_->GetDocument();
if (!document_loader_ ||
document->PageDismissalEventBeingDispatched() != Document::kNoDismissal)
return;
UseCounter::Count(*document, WebFeature::kReplaceDocumentViaJavaScriptURL);
const KURL& url = document->Url();
// The document CSP is the correct one as it is used for CSP checks
// done previously before getting here:
// HTMLFormElement::ScheduleFormSubmission
// HTMLFrameElementBase::OpenURL
WebGlobalObjectReusePolicy global_object_reuse_policy =
frame_->ShouldReuseDefaultView(url, document->GetContentSecurityPolicy())
? WebGlobalObjectReusePolicy::kUseExisting
: WebGlobalObjectReusePolicy::kCreateNew;
StopAllLoaders();
SubframeLoadingDisabler disabler(document);
frame_->DetachChildren();
if (!frame_->IsAttached() || document != frame_->GetDocument())
return;
frame_->GetDocument()->Shutdown();
Client()->TransitionToCommittedForNewPage();
document_loader_->ReplaceDocumentWhileExecutingJavaScriptURL(
url, owner_document, global_object_reuse_policy, source);
}
| 173,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm)
{
return &crypto_rng_tfm(tfm)->__crt_alg->cra_rng;
}
Commit Message: crypto: rng - Remove old low-level rng interface
Now that all rng implementations have switched over to the new
interface, we can remove the old low-level interface.
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-476 | static inline struct old_rng_alg *crypto_old_rng_alg(struct crypto_rng *tfm)
| 167,730 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) {
l->append("<SkBitmap>");
}
Commit Message: Update IPC ParamTraits for SkBitmap to follow best practices.
Using memcpy() to serialize a POD struct is highly discouraged. Just use
the standard IPC param traits macros for doing it.
Bug: 779428
Change-Id: I48f52c1f5c245ba274d595829ed92e8b3cb41334
Reviewed-on: https://chromium-review.googlesource.com/899649
Reviewed-by: Tom Sepez <[email protected]>
Commit-Queue: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534562}
CWE ID: CWE-125 | void ParamTraits<SkBitmap>::Log(const SkBitmap& p, std::string* l) {
l->append("<SkBitmap>");
LogParam(p.info(), l);
}
| 172,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_entry_size_and_hooks(struct ip6t_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 ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_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 ip6t_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 ip6t_entry) != 0 ||
(unsigned char *)e + sizeof(struct ip6t_entry) >= limit ||
(unsigned char *)e + e->next_offset > limit) {
duprintf("Bad offset %p\n", e);
return -EINVAL;
}
if (e->next_offset
< sizeof(struct ip6t_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,372 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CSSDefaultStyleSheets::initDefaultStyle(Element* root)
{
if (!defaultStyle) {
if (!root || elementCanUseSimpleDefaultStyle(root))
loadSimpleDefaultStyle();
else
loadFullDefaultStyle();
}
}
Commit Message: Remove the Simple Default Stylesheet, it's just a foot-gun.
We've been bitten by the Simple Default Stylesheet being out
of sync with the real html.css twice this week.
The Simple Default Stylesheet was invented years ago for Mac:
http://trac.webkit.org/changeset/36135
It nicely handles the case where you just want to create
a single WebView and parse some simple HTML either without
styling said HTML, or only to display a small string, etc.
Note that this optimization/complexity *only* helps for the
very first document, since the default stylesheets are
all static (process-global) variables. Since any real page
on the internet uses a tag not covered by the simple default
stylesheet, not real load benefits from this optimization.
Only uses of WebView which were just rendering small bits
of text might have benefited from this. about:blank would
also have used this sheet.
This was a common application for some uses of WebView back
in those days. These days, even with WebView on Android,
there are likely much larger overheads than parsing the
html.css stylesheet, so making it required seems like the
right tradeoff of code-simplicity for this case.
BUG=319556
Review URL: https://codereview.chromium.org/73723005
git-svn-id: svn://svn.chromium.org/blink/trunk@162153 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void CSSDefaultStyleSheets::initDefaultStyle(Element* root)
void CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary()
{
if (!defaultStyle)
loadDefaultStyle();
}
| 171,580 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: XGetDeviceButtonMapping(
register Display *dpy,
XDevice *device,
unsigned char map[],
unsigned int nmap)
{
int status = 0;
unsigned char mapping[256]; /* known fixed size */
XExtDisplayInfo *info = XInput_find_display(dpy);
register xGetDeviceButtonMappingReq *req;
xGetDeviceButtonMappingReply rep;
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1)
return (NoSuchExtension);
GetReq(GetDeviceButtonMapping, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetDeviceButtonMapping;
req->deviceid = device->device_id;
status = _XReply(dpy, (xReply *) & rep, 0, xFalse);
if (status == 1) {
if (rep.length <= (sizeof(mapping) >> 2)) {
unsigned long nbytes = rep.length << 2;
_XRead(dpy, (char *)mapping, nbytes);
if (rep.nElts)
memcpy(map, mapping, MIN((int)rep.nElts, nmap));
status = rep.nElts;
} else {
_XEatDataWords(dpy, rep.length);
status = 0;
}
} else
status = 0;
UnlockDisplay(dpy);
SyncHandle();
return (status);
}
Commit Message:
CWE ID: CWE-284 | XGetDeviceButtonMapping(
register Display *dpy,
XDevice *device,
unsigned char map[],
unsigned int nmap)
{
int status = 0;
unsigned char mapping[256]; /* known fixed size */
XExtDisplayInfo *info = XInput_find_display(dpy);
register xGetDeviceButtonMappingReq *req;
xGetDeviceButtonMappingReply rep;
LockDisplay(dpy);
if (_XiCheckExtInit(dpy, XInput_Initial_Release, info) == -1)
return (NoSuchExtension);
GetReq(GetDeviceButtonMapping, req);
req->reqType = info->codes->major_opcode;
req->ReqType = X_GetDeviceButtonMapping;
req->deviceid = device->device_id;
status = _XReply(dpy, (xReply *) & rep, 0, xFalse);
if (status == 1) {
if (rep.length <= (sizeof(mapping) >> 2) &&
rep.nElts <= (rep.length << 2)) {
unsigned long nbytes = rep.length << 2;
_XRead(dpy, (char *)mapping, nbytes);
if (rep.nElts)
memcpy(map, mapping, MIN((int)rep.nElts, nmap));
status = rep.nElts;
} else {
_XEatDataWords(dpy, rep.length);
status = 0;
}
} else
status = 0;
UnlockDisplay(dpy);
SyncHandle();
return (status);
}
| 164,917 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_control(png_const_structrp png_ptr)
{
/* This just returns the (file*). The chunk and idat control structures
* don't always exist.
*/
struct control *control = png_voidcast(struct control*,
png_get_error_ptr(png_ptr));
return &control->file;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | get_control(png_const_structrp png_ptr)
{
/* This just returns the (file*). The chunk and idat control structures
* don't always exist.
*/
struct control *control = voidcast(struct control*,
png_get_error_ptr(png_ptr));
return &control->file;
}
| 173,732 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OmniboxPopupViewGtk::~OmniboxPopupViewGtk() {
model_.reset();
g_object_unref(layout_);
gtk_widget_destroy(window_);
for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it)
delete it->second;
}
Commit Message: GTK: Stop listening to gtk signals in the omnibox before destroying the model.
BUG=123530
TEST=none
Review URL: http://codereview.chromium.org/10103012
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132498 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | OmniboxPopupViewGtk::~OmniboxPopupViewGtk() {
// Stop listening to our signals before we destroy the model. I suspect that
// we can race window destruction, otherwise.
signal_registrar_.reset();
model_.reset();
g_object_unref(layout_);
gtk_widget_destroy(window_);
for (ImageMap::iterator it = images_.begin(); it != images_.end(); ++it)
delete it->second;
}
| 171,049 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImeConfig: IBus connection is not alive";
return false;
}
bool is_preload_engines = false;
std::vector<std::string> string_list;
if ((value.type == ImeConfigValue::kValueTypeStringList) &&
(section == kGeneralSectionName) &&
(config_name == kPreloadEnginesConfigName)) {
FilterInputMethods(value.string_list_value, &string_list);
is_preload_engines = true;
} else {
string_list = value.string_list_value;
}
GVariant* variant = NULL;
switch (value.type) {
case ImeConfigValue::kValueTypeString:
variant = g_variant_new_string(value.string_value.c_str());
break;
case ImeConfigValue::kValueTypeInt:
variant = g_variant_new_int32(value.int_value);
break;
case ImeConfigValue::kValueTypeBool:
variant = g_variant_new_boolean(value.bool_value);
break;
case ImeConfigValue::kValueTypeStringList:
GVariantBuilder variant_builder;
g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as"));
const size_t size = string_list.size(); // don't use string_list_value.
for (size_t i = 0; i < size; ++i) {
g_variant_builder_add(&variant_builder, "s", string_list[i].c_str());
}
variant = g_variant_builder_end(&variant_builder);
break;
}
if (!variant) {
LOG(ERROR) << "SetImeConfig: variant is NULL";
return false;
}
DCHECK(g_variant_is_floating(variant));
ibus_config_set_value_async(ibus_config_,
section.c_str(),
config_name.c_str(),
variant,
-1, // use the default ibus timeout
NULL, // cancellable
SetImeConfigCallback,
g_object_ref(ibus_config_));
if (is_preload_engines) {
DLOG(INFO) << "SetImeConfig: " << section << "/" << config_name
<< ": " << value.ToString();
}
return true;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool SetImeConfig(const std::string& section,
// IBusController override.
virtual bool SetImeConfig(const std::string& section,
const std::string& config_name,
const ImeConfigValue& value) {
if (!IBusConnectionsAreAlive()) {
LOG(ERROR) << "SetImeConfig: IBus connection is not alive";
return false;
}
bool is_preload_engines = false;
std::vector<std::string> string_list;
if ((value.type == ImeConfigValue::kValueTypeStringList) &&
(section == kGeneralSectionName) &&
(config_name == kPreloadEnginesConfigName)) {
FilterInputMethods(value.string_list_value, &string_list);
is_preload_engines = true;
} else {
string_list = value.string_list_value;
}
GVariant* variant = NULL;
switch (value.type) {
case ImeConfigValue::kValueTypeString:
variant = g_variant_new_string(value.string_value.c_str());
break;
case ImeConfigValue::kValueTypeInt:
variant = g_variant_new_int32(value.int_value);
break;
case ImeConfigValue::kValueTypeBool:
variant = g_variant_new_boolean(value.bool_value);
break;
case ImeConfigValue::kValueTypeStringList:
GVariantBuilder variant_builder;
g_variant_builder_init(&variant_builder, G_VARIANT_TYPE("as"));
const size_t size = string_list.size(); // don't use string_list_value.
for (size_t i = 0; i < size; ++i) {
g_variant_builder_add(&variant_builder, "s", string_list[i].c_str());
}
variant = g_variant_builder_end(&variant_builder);
break;
}
if (!variant) {
LOG(ERROR) << "SetImeConfig: variant is NULL";
return false;
}
DCHECK(g_variant_is_floating(variant));
ibus_config_set_value_async(ibus_config_,
section.c_str(),
config_name.c_str(),
variant,
-1, // use the default ibus timeout
NULL, // cancellable
SetImeConfigCallback,
g_object_ref(ibus_config_));
if (is_preload_engines) {
VLOG(1) << "SetImeConfig: " << section << "/" << config_name
<< ": " << value.ToString();
}
return true;
}
| 170,547 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AddInputMethodNames(const GList* engines, InputMethodDescriptors* out) {
DCHECK(out);
for (; engines; engines = g_list_next(engines)) {
IBusEngineDesc* engine_desc = IBUS_ENGINE_DESC(engines->data);
const gchar* name = ibus_engine_desc_get_name(engine_desc);
const gchar* longname = ibus_engine_desc_get_longname(engine_desc);
const gchar* layout = ibus_engine_desc_get_layout(engine_desc);
const gchar* language = ibus_engine_desc_get_language(engine_desc);
if (InputMethodIdIsWhitelisted(name)) {
out->push_back(CreateInputMethodDescriptor(name,
longname,
layout,
language));
DLOG(INFO) << name << " (preloaded)";
}
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AddInputMethodNames(const GList* engines, InputMethodDescriptors* out) {
DCHECK(out);
for (; engines; engines = g_list_next(engines)) {
IBusEngineDesc* engine_desc = IBUS_ENGINE_DESC(engines->data);
const gchar* name = ibus_engine_desc_get_name(engine_desc);
const gchar* longname = ibus_engine_desc_get_longname(engine_desc);
const gchar* layout = ibus_engine_desc_get_layout(engine_desc);
const gchar* language = ibus_engine_desc_get_language(engine_desc);
if (InputMethodIdIsWhitelisted(name)) {
out->push_back(CreateInputMethodDescriptor(name,
longname,
layout,
language));
VLOG(1) << name << " (preloaded)";
}
}
}
| 170,517 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_mpi r, s;
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
(void) f_rng;
(void) p_rng;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign_det( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg ) );
#else
(void) md_alg;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#endif
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
Commit Message: Merge remote-tracking branch 'upstream-restricted/pr/549' into mbedtls-2.7-restricted
CWE ID: CWE-200 | int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg,
const unsigned char *hash, size_t hlen,
unsigned char *sig, size_t *slen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret;
mbedtls_mpi r, s;
mbedtls_mpi_init( &r );
mbedtls_mpi_init( &s );
#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
MBEDTLS_MPI_CHK( ecdsa_sign_det_internal( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, md_alg,
f_rng, p_rng ) );
#else
(void) md_alg;
MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
hash, hlen, f_rng, p_rng ) );
#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
cleanup:
mbedtls_mpi_free( &r );
mbedtls_mpi_free( &s );
return( ret );
}
| 170,182 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: (for 4.9.3) CVE-2018-16300/BGP: prevent stack exhaustion
Enforce a limit on how many times bgp_attr_print() can recurse.
This fixes a stack exhaustion discovered by Include Security working
under the Mozilla SOS program in 2018 by means of code audit.
CWE ID: CWE-674 | bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen, 0))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 169,817 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport unsigned char *DetachBlob(BlobInfo *blob_info)
{
unsigned char
*data;
assert(blob_info != (BlobInfo *) NULL);
if (blob_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (blob_info->mapped != MagickFalse)
{
(void) UnmapBlob(blob_info->data,blob_info->length);
RelinquishMagickResource(MapResource,blob_info->length);
}
blob_info->mapped=MagickFalse;
blob_info->length=0;
blob_info->offset=0;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->exempt=MagickFalse;
blob_info->type=UndefinedStream;
blob_info->file_info.file=(FILE *) NULL;
data=blob_info->data;
blob_info->data=(unsigned char *) NULL;
blob_info->stream=(StreamHandler) NULL;
return(data);
}
Commit Message: https://github.com/ImageMagick/ImageMagick6/issues/43
CWE ID: CWE-416 | MagickExport unsigned char *DetachBlob(BlobInfo *blob_info)
{
unsigned char
*data;
assert(blob_info != (BlobInfo *) NULL);
if (blob_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (blob_info->mapped != MagickFalse)
{
(void) UnmapBlob(blob_info->data,blob_info->length);
blob_info->data=NULL;
RelinquishMagickResource(MapResource,blob_info->length);
}
blob_info->mapped=MagickFalse;
blob_info->length=0;
blob_info->offset=0;
blob_info->eof=MagickFalse;
blob_info->error=0;
blob_info->exempt=MagickFalse;
blob_info->type=UndefinedStream;
blob_info->file_info.file=(FILE *) NULL;
data=blob_info->data;
blob_info->data=(unsigned char *) NULL;
blob_info->stream=(StreamHandler) NULL;
return(data);
}
| 169,563 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CloseTabsAndExpectNotifications(
TabStripModel* tab_strip_model,
std::vector<LifecycleUnit*> lifecycle_units) {
std::vector<std::unique_ptr<testing::StrictMock<MockLifecycleUnitObserver>>>
observers;
for (LifecycleUnit* lifecycle_unit : lifecycle_units) {
observers.emplace_back(
std::make_unique<testing::StrictMock<MockLifecycleUnitObserver>>());
lifecycle_unit->AddObserver(observers.back().get());
EXPECT_CALL(*observers.back().get(),
OnLifecycleUnitDestroyed(lifecycle_unit));
}
tab_strip_model->CloseAllTabs();
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID: | void CloseTabsAndExpectNotifications(
TabStripModel* tab_strip_model,
std::vector<LifecycleUnit*> lifecycle_units) {
std::vector<
std::unique_ptr<::testing::StrictMock<MockLifecycleUnitObserver>>>
observers;
for (LifecycleUnit* lifecycle_unit : lifecycle_units) {
observers.emplace_back(
std::make_unique<::testing::StrictMock<MockLifecycleUnitObserver>>());
lifecycle_unit->AddObserver(observers.back().get());
EXPECT_CALL(*observers.back().get(),
OnLifecycleUnitDestroyed(lifecycle_unit));
}
tab_strip_model->CloseAllTabs();
}
| 172,221 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: initpyfribidi (void)
{
PyObject *module;
/* XXX What should be done if we fail here? */
module = Py_InitModule3 ("pyfribidi", PyfribidiMethods,
_pyfribidi__doc__);
PyModule_AddIntConstant (module, "RTL", (long) FRIBIDI_TYPE_RTL);
PyModule_AddIntConstant (module, "LTR", (long) FRIBIDI_TYPE_LTR);
PyModule_AddIntConstant (module, "ON", (long) FRIBIDI_TYPE_ON);
PyModule_AddStringConstant (module, "__author__",
"Yaacov Zamir and Nir Soffer");
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119 | initpyfribidi (void)
init_pyfribidi (void)
{
PyObject *module = Py_InitModule ("_pyfribidi", PyfribidiMethods);
PyModule_AddIntConstant (module, "RTL", (long) FRIBIDI_TYPE_RTL);
PyModule_AddIntConstant (module, "LTR", (long) FRIBIDI_TYPE_LTR);
PyModule_AddIntConstant (module, "ON", (long) FRIBIDI_TYPE_ON);
}
| 165,639 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Erase(const std::string& addr) {
base::AutoLock lock(lock_);
map_.erase(addr);
}
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 Erase(const std::string& addr) {
// Erases the entry for |preview_id|.
void Erase(int32 preview_id) {
base::AutoLock lock(lock_);
map_.erase(preview_id);
}
| 170,830 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
assert(0);
return NULL;
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20 | static float *get_window(vorb *f, int len)
{
len <<= 1;
if (len == f->blocksize_0) return f->window[0];
if (len == f->blocksize_1) return f->window[1];
return NULL;
}
| 169,615 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter)
{
u_char buf[OSPF_API_MAX_MSG_SIZE];
struct msg_register_event *emsg;
int len;
emsg = (struct msg_register_event *) buf;
len = sizeof (struct msg_register_event) +
filter->num_areas * sizeof (struct in_addr);
emsg->filter.typemask = htons (filter->typemask);
emsg->filter.origin = filter->origin;
emsg->filter.num_areas = filter->num_areas;
return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len);
}
Commit Message:
CWE ID: CWE-119 | new_msg_register_event (u_int32_t seqnum, struct lsa_filter_type *filter)
{
u_char buf[OSPF_API_MAX_MSG_SIZE];
struct msg_register_event *emsg;
int len;
emsg = (struct msg_register_event *) buf;
len = sizeof (struct msg_register_event) +
filter->num_areas * sizeof (struct in_addr);
emsg->filter.typemask = htons (filter->typemask);
emsg->filter.origin = filter->origin;
emsg->filter.num_areas = filter->num_areas;
if (len > sizeof (buf))
len = sizeof(buf);
/* API broken - missing memcpy to fill data */
return msg_new (MSG_REGISTER_EVENT, emsg, seqnum, len);
}
| 164,716 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: get_matching_model_microcode(int cpu, unsigned long start,
void *data, size_t size,
struct mc_saved_data *mc_saved_data,
unsigned long *mc_saved_in_initrd,
struct ucode_cpu_info *uci)
{
u8 *ucode_ptr = data;
unsigned int leftover = size;
enum ucode_state state = UCODE_OK;
unsigned int mc_size;
struct microcode_header_intel *mc_header;
struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];
unsigned int mc_saved_count = mc_saved_data->mc_saved_count;
int i;
while (leftover) {
mc_header = (struct microcode_header_intel *)ucode_ptr;
mc_size = get_totalsize(mc_header);
if (!mc_size || mc_size > leftover ||
microcode_sanity_check(ucode_ptr, 0) < 0)
break;
leftover -= mc_size;
/*
* Since APs with same family and model as the BSP may boot in
* the platform, we need to find and save microcode patches
* with the same family and model as the BSP.
*/
if (matching_model_microcode(mc_header, uci->cpu_sig.sig) !=
UCODE_OK) {
ucode_ptr += mc_size;
continue;
}
_save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count);
ucode_ptr += mc_size;
}
if (leftover) {
state = UCODE_ERROR;
goto out;
}
if (mc_saved_count == 0) {
state = UCODE_NFOUND;
goto out;
}
for (i = 0; i < mc_saved_count; i++)
mc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start;
mc_saved_data->mc_saved_count = mc_saved_count;
out:
return state;
}
Commit Message: x86/microcode/intel: Guard against stack overflow in the loader
mc_saved_tmp is a static array allocated on the stack, we need to make
sure mc_saved_count stays within its bounds, otherwise we're overflowing
the stack in _save_mc(). A specially crafted microcode header could lead
to a kernel crash or potentially kernel execution.
Signed-off-by: Quentin Casasnovas <[email protected]>
Cc: "H. Peter Anvin" <[email protected]>
Cc: Fenghua Yu <[email protected]>
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Borislav Petkov <[email protected]>
CWE ID: CWE-119 | get_matching_model_microcode(int cpu, unsigned long start,
void *data, size_t size,
struct mc_saved_data *mc_saved_data,
unsigned long *mc_saved_in_initrd,
struct ucode_cpu_info *uci)
{
u8 *ucode_ptr = data;
unsigned int leftover = size;
enum ucode_state state = UCODE_OK;
unsigned int mc_size;
struct microcode_header_intel *mc_header;
struct microcode_intel *mc_saved_tmp[MAX_UCODE_COUNT];
unsigned int mc_saved_count = mc_saved_data->mc_saved_count;
int i;
while (leftover && mc_saved_count < ARRAY_SIZE(mc_saved_tmp)) {
mc_header = (struct microcode_header_intel *)ucode_ptr;
mc_size = get_totalsize(mc_header);
if (!mc_size || mc_size > leftover ||
microcode_sanity_check(ucode_ptr, 0) < 0)
break;
leftover -= mc_size;
/*
* Since APs with same family and model as the BSP may boot in
* the platform, we need to find and save microcode patches
* with the same family and model as the BSP.
*/
if (matching_model_microcode(mc_header, uci->cpu_sig.sig) !=
UCODE_OK) {
ucode_ptr += mc_size;
continue;
}
_save_mc(mc_saved_tmp, ucode_ptr, &mc_saved_count);
ucode_ptr += mc_size;
}
if (leftover) {
state = UCODE_ERROR;
goto out;
}
if (mc_saved_count == 0) {
state = UCODE_NFOUND;
goto out;
}
for (i = 0; i < mc_saved_count; i++)
mc_saved_in_initrd[i] = (unsigned long)mc_saved_tmp[i] - start;
mc_saved_data->mc_saved_count = mc_saved_count;
out:
return state;
}
| 166,679 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void build_l4proto_sctp(const struct nf_conntrack *ct, struct nethdr *n)
{
ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
sizeof(struct nfct_attr_grp_port));
if (!nfct_attr_is_set(ct, ATTR_SCTP_STATE))
return;
ct_build_u8(ct, ATTR_SCTP_STATE, n, NTA_SCTP_STATE);
ct_build_u32(ct, ATTR_SCTP_VTAG_ORIG, n, NTA_SCTP_VTAG_ORIG);
ct_build_u32(ct, ATTR_SCTP_VTAG_REPL, n, NTA_SCTP_VTAG_REPL);
}
Commit Message:
CWE ID: CWE-17 | static void build_l4proto_sctp(const struct nf_conntrack *ct, struct nethdr *n)
{
/* SCTP is optional, make sure nf_conntrack_sctp is loaded */
if (!nfct_attr_is_set(ct, ATTR_SCTP_STATE))
return;
ct_build_group(ct, ATTR_GRP_ORIG_PORT, n, NTA_PORT,
sizeof(struct nfct_attr_grp_port));
ct_build_u8(ct, ATTR_SCTP_STATE, n, NTA_SCTP_STATE);
ct_build_u32(ct, ATTR_SCTP_VTAG_ORIG, n, NTA_SCTP_VTAG_ORIG);
ct_build_u32(ct, ATTR_SCTP_VTAG_REPL, n, NTA_SCTP_VTAG_REPL);
}
| 164,631 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: hb_buffer_ensure (hb_buffer_t *buffer, unsigned int size)
{
unsigned int new_allocated = buffer->allocated;
if (size > new_allocated)
{
while (size > new_allocated)
new_allocated += (new_allocated >> 1) + 8;
if (buffer->pos)
buffer->pos = (hb_internal_glyph_position_t *) realloc (buffer->pos, new_allocated * sizeof (buffer->pos[0]));
if (buffer->out_info != buffer->info)
{
buffer->info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0]));
buffer->out_info = (hb_internal_glyph_info_t *) buffer->pos;
}
else
{
buffer->info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0]));
buffer->out_info = buffer->info;
}
buffer->allocated = new_allocated;
}
}
Commit Message:
CWE ID: | hb_buffer_ensure (hb_buffer_t *buffer, unsigned int size)
{
if (unlikely (size > buffer->allocated))
{
if (unlikely (buffer->in_error))
return FALSE;
unsigned int new_allocated = buffer->allocated;
hb_internal_glyph_position_t *new_pos;
hb_internal_glyph_info_t *new_info;
bool separate_out;
separate_out = buffer->out_info != buffer->info;
while (size > new_allocated)
new_allocated += (new_allocated >> 1) + 8;
new_pos = (hb_internal_glyph_position_t *) realloc (buffer->pos, new_allocated * sizeof (buffer->pos[0]));
new_info = (hb_internal_glyph_info_t *) realloc (buffer->info, new_allocated * sizeof (buffer->info[0]));
if (unlikely (!new_pos || !new_info))
buffer->in_error = TRUE;
if (likely (new_pos))
buffer->pos = new_pos;
if (likely (new_info))
buffer->info = new_info;
buffer->out_info = separate_out ? (hb_internal_glyph_info_t *) buffer->pos : buffer->info;
if (likely (!buffer->in_error))
buffer->allocated = new_allocated;
}
return likely (!buffer->in_error);
}
| 164,774 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: layer_resize(int layer, int x_size, int y_size)
{
int old_height;
int old_width;
struct map_tile* tile;
int tile_width;
int tile_height;
struct map_tile* tilemap;
struct map_trigger* trigger;
struct map_zone* zone;
int x, y, i;
old_width = s_map->layers[layer].width;
old_height = s_map->layers[layer].height;
if (!(tilemap = malloc(x_size * y_size * sizeof(struct map_tile))))
return false;
for (x = 0; x < x_size; ++x) {
for (y = 0; y < y_size; ++y) {
if (x < old_width && y < old_height) {
tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width];
}
else {
tile = &tilemap[x + y * x_size];
tile->frames_left = tileset_get_delay(s_map->tileset, 0);
tile->tile_index = 0;
}
}
}
free(s_map->layers[layer].tilemap);
s_map->layers[layer].tilemap = tilemap;
s_map->layers[layer].width = x_size;
s_map->layers[layer].height = y_size;
tileset_get_size(s_map->tileset, &tile_width, &tile_height);
s_map->width = 0;
s_map->height = 0;
for (i = 0; i < s_map->num_layers; ++i) {
if (!s_map->layers[i].is_parallax) {
s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width);
s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height);
}
}
for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) {
zone = vector_get(s_map->zones, i);
if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height)
vector_remove(s_map->zones, i);
else {
if (zone->bounds.x2 > s_map->width)
zone->bounds.x2 = s_map->width;
if (zone->bounds.y2 > s_map->height)
zone->bounds.y2 = s_map->height;
}
}
for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) {
trigger = vector_get(s_map->triggers, i);
if (trigger->x >= s_map->width || trigger->y >= s_map->height)
vector_remove(s_map->triggers, i);
}
return true;
}
Commit Message: Fix integer overflow in layer_resize in map_engine.c (#268)
* Fix integer overflow in layer_resize in map_engine.c
There's a buffer overflow bug in the function layer_resize. It allocates
a buffer `tilemap` with size `x_size * y_size * sizeof(struct map_tile)`.
But it didn't check for integer overflow, so if x_size and y_size are
very large, it's possible that the buffer size is smaller than needed,
causing a buffer overflow later.
PoC: `SetLayerSize(0, 0x7FFFFFFF, 0x7FFFFFFF);`
* move malloc to a separate line
CWE ID: CWE-190 | layer_resize(int layer, int x_size, int y_size)
{
int old_height;
int old_width;
struct map_tile* tile;
int tile_width;
int tile_height;
struct map_tile* tilemap;
struct map_trigger* trigger;
struct map_zone* zone;
size_t tilemap_size;
int x, y, i;
old_width = s_map->layers[layer].width;
old_height = s_map->layers[layer].height;
tilemap_size = x_size * y_size * sizeof(struct map_tile);
if (x_size == 0 || tilemap_size / x_size / sizeof(struct map_tile) != y_size
|| !(tilemap = malloc(tilemap_size)))
return false;
for (x = 0; x < x_size; ++x) {
for (y = 0; y < y_size; ++y) {
if (x < old_width && y < old_height) {
tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width];
}
else {
tile = &tilemap[x + y * x_size];
tile->frames_left = tileset_get_delay(s_map->tileset, 0);
tile->tile_index = 0;
}
}
}
free(s_map->layers[layer].tilemap);
s_map->layers[layer].tilemap = tilemap;
s_map->layers[layer].width = x_size;
s_map->layers[layer].height = y_size;
tileset_get_size(s_map->tileset, &tile_width, &tile_height);
s_map->width = 0;
s_map->height = 0;
for (i = 0; i < s_map->num_layers; ++i) {
if (!s_map->layers[i].is_parallax) {
s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width);
s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height);
}
}
for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) {
zone = vector_get(s_map->zones, i);
if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height)
vector_remove(s_map->zones, i);
else {
if (zone->bounds.x2 > s_map->width)
zone->bounds.x2 = s_map->width;
if (zone->bounds.y2 > s_map->height)
zone->bounds.y2 = s_map->height;
}
}
for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) {
trigger = vector_get(s_map->triggers, i);
if (trigger->x >= s_map->width || trigger->y >= s_map->height)
vector_remove(s_map->triggers, i);
}
return true;
}
| 168,941 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HistoryController::UpdateForCommit(RenderFrameImpl* frame,
const WebHistoryItem& item,
WebHistoryCommitType commit_type,
bool navigation_within_page) {
switch (commit_type) {
case blink::WebBackForwardCommit:
if (!provisional_entry_)
return;
current_entry_.reset(provisional_entry_.release());
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
node->set_item(item);
}
break;
case blink::WebStandardCommit:
CreateNewBackForwardItem(frame, item, navigation_within_page);
break;
case blink::WebInitialCommitInChildFrame:
UpdateForInitialLoadInChildFrame(frame, item);
break;
case blink::WebHistoryInertCommit:
if (current_entry_) {
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
if (!navigation_within_page)
node->RemoveChildren();
node->set_item(item);
}
}
break;
default:
NOTREACHED() << "Invalid commit type: " << commit_type;
}
}
Commit Message: Fix HistoryEntry corruption when commit isn't for provisional entry.
BUG=597322
TEST=See bug for repro steps.
Review URL: https://codereview.chromium.org/1848103004
Cr-Commit-Position: refs/heads/master@{#384659}
CWE ID: CWE-254 | void HistoryController::UpdateForCommit(RenderFrameImpl* frame,
const WebHistoryItem& item,
WebHistoryCommitType commit_type,
bool navigation_within_page) {
switch (commit_type) {
case blink::WebBackForwardCommit:
if (!provisional_entry_)
return;
// Commit the provisional entry, but only if this back/forward item
// matches it. Otherwise it could be a commit from an earlier attempt to
// go back/forward, and we should leave the provisional entry in place.
if (HistoryEntry::HistoryNode* node =
provisional_entry_->GetHistoryNodeForFrame(frame)) {
if (node->item().itemSequenceNumber() == item.itemSequenceNumber())
current_entry_.reset(provisional_entry_.release());
}
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
node->set_item(item);
}
break;
case blink::WebStandardCommit:
CreateNewBackForwardItem(frame, item, navigation_within_page);
break;
case blink::WebInitialCommitInChildFrame:
UpdateForInitialLoadInChildFrame(frame, item);
break;
case blink::WebHistoryInertCommit:
if (current_entry_) {
if (HistoryEntry::HistoryNode* node =
current_entry_->GetHistoryNodeForFrame(frame)) {
if (!navigation_within_page)
node->RemoveChildren();
node->set_item(item);
}
}
break;
default:
NOTREACHED() << "Invalid commit type: " << commit_type;
}
}
| 172,565 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int http_buf_read(URLContext *h, uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
int len;
/* read bytes from input buffer first */
len = s->buf_end - s->buf_ptr;
if (len > 0) {
if (len > size)
len = size;
memcpy(buf, s->buf_ptr, len);
s->buf_ptr += len;
} else {
int64_t target_end = s->end_off ? s->end_off : s->filesize;
if ((!s->willclose || s->chunksize < 0) &&
target_end >= 0 && s->off >= target_end)
return AVERROR_EOF;
len = ffurl_read(s->hd, buf, size);
if (!len && (!s->willclose || s->chunksize < 0) &&
target_end >= 0 && s->off < target_end) {
av_log(h, AV_LOG_ERROR,
"Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
s->off, target_end
);
return AVERROR(EIO);
}
}
if (len > 0) {
s->off += len;
if (s->chunksize > 0)
s->chunksize -= len;
}
return len;
}
Commit Message: http: make length/offset-related variables unsigned.
Fixes #5992, reported and found by Paul Cher <[email protected]>.
CWE ID: CWE-119 | static int http_buf_read(URLContext *h, uint8_t *buf, int size)
{
HTTPContext *s = h->priv_data;
int len;
/* read bytes from input buffer first */
len = s->buf_end - s->buf_ptr;
if (len > 0) {
if (len > size)
len = size;
memcpy(buf, s->buf_ptr, len);
s->buf_ptr += len;
} else {
uint64_t target_end = s->end_off ? s->end_off : s->filesize;
if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
return AVERROR_EOF;
len = ffurl_read(s->hd, buf, size);
if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
av_log(h, AV_LOG_ERROR,
"Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
s->off, target_end
);
return AVERROR(EIO);
}
}
if (len > 0) {
s->off += len;
if (s->chunksize > 0)
s->chunksize -= len;
}
return len;
}
| 168,496 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Track::Create(
Segment* pSegment,
const Info& info,
long long element_start,
long long element_size,
Track*& pResult)
{
if (pResult)
return -1;
Track* const pTrack = new (std::nothrow) Track(pSegment,
element_start,
element_size);
if (pTrack == NULL)
return -1; //generic error
const int status = info.Copy(pTrack->m_info);
if (status) // error
{
delete pTrack;
return status;
}
pResult = pTrack;
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 Track::Create(
Track::Info::Info()
: uid(0),
defaultDuration(0),
codecDelay(0),
seekPreRoll(0),
nameAsUTF8(NULL),
language(NULL),
codecId(NULL),
codecNameAsUTF8(NULL),
codecPrivate(NULL),
codecPrivateSize(0),
lacing(false) {}
Track::Info::~Info() { Clear(); }
void Track::Info::Clear() {
delete[] nameAsUTF8;
nameAsUTF8 = NULL;
delete[] language;
language = NULL;
delete[] codecId;
codecId = NULL;
delete[] codecPrivate;
codecPrivate = NULL;
codecPrivateSize = 0;
delete[] codecNameAsUTF8;
codecNameAsUTF8 = NULL;
}
| 174,255 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new Cluster* [n];
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
bool Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) {
assert(pCluster);
assert(pCluster->m_index < 0);
assert(idx >= m_clusterCount);
const long count = m_clusterCount + m_clusterPreloadCount;
long& size = m_clusterSize;
assert(size >= count);
if (count >= size) {
const long n = (size <= 0) ? 2048 : 2 * size;
Cluster** const qq = new (std::nothrow) Cluster*[n];
if (qq == NULL)
return false;
Cluster** q = qq;
Cluster** p = m_clusters;
Cluster** const pp = p + count;
while (p != pp)
*q++ = *p++;
delete[] m_clusters;
m_clusters = qq;
size = n;
}
assert(m_clusters);
Cluster** const p = m_clusters + idx;
Cluster** q = m_clusters + count;
assert(q >= p);
assert(q < (m_clusters + size));
while (q > p) {
Cluster** const qq = q - 1;
assert((*qq)->m_index < 0);
*q = *qq;
q = qq;
}
m_clusters[idx] = pCluster;
++m_clusterPreloadCount;
return true;
}
| 173,860 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: krb5_gss_wrap_size_limit(minor_status, context_handle, conf_req_flag,
qop_req, req_output_size, max_input_size)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
OM_uint32 req_output_size;
OM_uint32 *max_input_size;
{
krb5_gss_ctx_id_rec *ctx;
OM_uint32 data_size, conflen;
OM_uint32 ohlen;
int overhead;
/* only default qop is allowed */
if (qop_req != GSS_C_QOP_DEFAULT) {
*minor_status = (OM_uint32) G_UNKNOWN_QOP;
return(GSS_S_FAILURE);
}
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (! ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
if (ctx->proto == 1) {
/* No pseudo-ASN.1 wrapper overhead, so no sequence length and
OID. */
OM_uint32 sz = req_output_size;
/* Token header: 16 octets. */
if (conf_req_flag) {
krb5_key key;
krb5_enctype enctype;
key = ctx->have_acceptor_subkey ? ctx->acceptor_subkey
: ctx->subkey;
enctype = key->keyblock.enctype;
while (sz > 0 && krb5_encrypt_size(sz, enctype) + 16 > req_output_size)
sz--;
/* Allow for encrypted copy of header. */
if (sz > 16)
sz -= 16;
else
sz = 0;
#ifdef CFX_EXERCISE
/* Allow for EC padding. In the MIT implementation, only
added while testing. */
if (sz > 65535)
sz -= 65535;
else
sz = 0;
#endif
} else {
krb5_cksumtype cksumtype;
krb5_error_code err;
size_t cksumsize;
cksumtype = ctx->have_acceptor_subkey ? ctx->acceptor_subkey_cksumtype
: ctx->cksumtype;
err = krb5_c_checksum_length(ctx->k5_context, cksumtype, &cksumsize);
if (err) {
*minor_status = err;
return GSS_S_FAILURE;
}
/* Allow for token header and checksum. */
if (sz < 16 + cksumsize)
sz = 0;
else
sz -= (16 + cksumsize);
}
*max_input_size = sz;
*minor_status = 0;
return GSS_S_COMPLETE;
}
/* Calculate the token size and subtract that from the output size */
overhead = 7 + ctx->mech_used->length;
data_size = req_output_size;
conflen = kg_confounder_size(ctx->k5_context, ctx->enc->keyblock.enctype);
data_size = (conflen + data_size + 8) & (~(OM_uint32)7);
ohlen = g_token_size(ctx->mech_used,
(unsigned int) (data_size + ctx->cksum_size + 14))
- req_output_size;
if (ohlen+overhead < req_output_size)
/*
* Cannot have trailer length that will cause us to pad over our
* length.
*/
*max_input_size = (req_output_size - ohlen - overhead) & (~(OM_uint32)7);
else
*max_input_size = 0;
*minor_status = 0;
return(GSS_S_COMPLETE);
}
Commit Message: Fix gss_process_context_token() [CVE-2014-5352]
[MITKRB5-SA-2015-001] The krb5 gss_process_context_token() should not
actually delete the context; that leaves the caller with a dangling
pointer and no way to know that it is invalid. Instead, mark the
context as terminated, and check for terminated contexts in the GSS
functions which expect established contexts. Also add checks in
export_sec_context and pseudo_random, and adjust t_prf.c for the
pseudo_random check.
ticket: 8055 (new)
target_version: 1.13.1
tags: pullup
CWE ID: | krb5_gss_wrap_size_limit(minor_status, context_handle, conf_req_flag,
qop_req, req_output_size, max_input_size)
OM_uint32 *minor_status;
gss_ctx_id_t context_handle;
int conf_req_flag;
gss_qop_t qop_req;
OM_uint32 req_output_size;
OM_uint32 *max_input_size;
{
krb5_gss_ctx_id_rec *ctx;
OM_uint32 data_size, conflen;
OM_uint32 ohlen;
int overhead;
/* only default qop is allowed */
if (qop_req != GSS_C_QOP_DEFAULT) {
*minor_status = (OM_uint32) G_UNKNOWN_QOP;
return(GSS_S_FAILURE);
}
ctx = (krb5_gss_ctx_id_rec *) context_handle;
if (ctx->terminated || !ctx->established) {
*minor_status = KG_CTX_INCOMPLETE;
return(GSS_S_NO_CONTEXT);
}
if (ctx->proto == 1) {
/* No pseudo-ASN.1 wrapper overhead, so no sequence length and
OID. */
OM_uint32 sz = req_output_size;
/* Token header: 16 octets. */
if (conf_req_flag) {
krb5_key key;
krb5_enctype enctype;
key = ctx->have_acceptor_subkey ? ctx->acceptor_subkey
: ctx->subkey;
enctype = key->keyblock.enctype;
while (sz > 0 && krb5_encrypt_size(sz, enctype) + 16 > req_output_size)
sz--;
/* Allow for encrypted copy of header. */
if (sz > 16)
sz -= 16;
else
sz = 0;
#ifdef CFX_EXERCISE
/* Allow for EC padding. In the MIT implementation, only
added while testing. */
if (sz > 65535)
sz -= 65535;
else
sz = 0;
#endif
} else {
krb5_cksumtype cksumtype;
krb5_error_code err;
size_t cksumsize;
cksumtype = ctx->have_acceptor_subkey ? ctx->acceptor_subkey_cksumtype
: ctx->cksumtype;
err = krb5_c_checksum_length(ctx->k5_context, cksumtype, &cksumsize);
if (err) {
*minor_status = err;
return GSS_S_FAILURE;
}
/* Allow for token header and checksum. */
if (sz < 16 + cksumsize)
sz = 0;
else
sz -= (16 + cksumsize);
}
*max_input_size = sz;
*minor_status = 0;
return GSS_S_COMPLETE;
}
/* Calculate the token size and subtract that from the output size */
overhead = 7 + ctx->mech_used->length;
data_size = req_output_size;
conflen = kg_confounder_size(ctx->k5_context, ctx->enc->keyblock.enctype);
data_size = (conflen + data_size + 8) & (~(OM_uint32)7);
ohlen = g_token_size(ctx->mech_used,
(unsigned int) (data_size + ctx->cksum_size + 14))
- req_output_size;
if (ohlen+overhead < req_output_size)
/*
* Cannot have trailer length that will cause us to pad over our
* length.
*/
*max_input_size = (req_output_size - ohlen - overhead) & (~(OM_uint32)7);
else
*max_input_size = 0;
*minor_status = 0;
return(GSS_S_COMPLETE);
}
| 166,824 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void TestAppendTabsToTabStrip(bool focus_tab_strip) {
LifecycleUnit* first_lifecycle_unit = nullptr;
LifecycleUnit* second_lifecycle_unit = nullptr;
CreateTwoTabs(focus_tab_strip, &first_lifecycle_unit,
&second_lifecycle_unit);
const base::TimeTicks first_tab_last_focused_time =
first_lifecycle_unit->GetLastFocusedTime();
const base::TimeTicks second_tab_last_focused_time =
second_lifecycle_unit->GetLastFocusedTime();
task_runner_->FastForwardBy(kShortDelay);
LifecycleUnit* third_lifecycle_unit = nullptr;
EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(testing::_))
.WillOnce(testing::Invoke([&](LifecycleUnit* lifecycle_unit) {
third_lifecycle_unit = lifecycle_unit;
if (focus_tab_strip) {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_TRUE(IsFocused(second_lifecycle_unit));
} else {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_EQ(second_tab_last_focused_time,
second_lifecycle_unit->GetLastFocusedTime());
}
EXPECT_EQ(NowTicks(), third_lifecycle_unit->GetLastFocusedTime());
}));
std::unique_ptr<content::WebContents> third_web_contents =
CreateAndNavigateWebContents();
content::WebContents* raw_third_web_contents = third_web_contents.get();
tab_strip_model_->AppendWebContents(std::move(third_web_contents), false);
testing::Mock::VerifyAndClear(&source_observer_);
EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_third_web_contents));
CloseTabsAndExpectNotifications(
tab_strip_model_.get(),
{first_lifecycle_unit, second_lifecycle_unit, third_lifecycle_unit});
}
Commit Message: Connect the LocalDB to TabManager.
Bug: 773382
Change-Id: Iec8fe5226ee175105d51f300f30b4865478ac099
Reviewed-on: https://chromium-review.googlesource.com/1118611
Commit-Queue: Sébastien Marchand <[email protected]>
Reviewed-by: François Doray <[email protected]>
Cr-Commit-Position: refs/heads/master@{#572871}
CWE ID: | void TestAppendTabsToTabStrip(bool focus_tab_strip) {
LifecycleUnit* first_lifecycle_unit = nullptr;
LifecycleUnit* second_lifecycle_unit = nullptr;
CreateTwoTabs(focus_tab_strip, &first_lifecycle_unit,
&second_lifecycle_unit);
const base::TimeTicks first_tab_last_focused_time =
first_lifecycle_unit->GetLastFocusedTime();
const base::TimeTicks second_tab_last_focused_time =
second_lifecycle_unit->GetLastFocusedTime();
task_runner_->FastForwardBy(kShortDelay);
LifecycleUnit* third_lifecycle_unit = nullptr;
EXPECT_CALL(source_observer_, OnLifecycleUnitCreated(::testing::_))
.WillOnce(::testing::Invoke([&](LifecycleUnit* lifecycle_unit) {
third_lifecycle_unit = lifecycle_unit;
if (focus_tab_strip) {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_TRUE(IsFocused(second_lifecycle_unit));
} else {
EXPECT_EQ(first_tab_last_focused_time,
first_lifecycle_unit->GetLastFocusedTime());
EXPECT_EQ(second_tab_last_focused_time,
second_lifecycle_unit->GetLastFocusedTime());
}
EXPECT_EQ(NowTicks(), third_lifecycle_unit->GetLastFocusedTime());
}));
std::unique_ptr<content::WebContents> third_web_contents =
CreateAndNavigateWebContents();
content::WebContents* raw_third_web_contents = third_web_contents.get();
tab_strip_model_->AppendWebContents(std::move(third_web_contents), false);
::testing::Mock::VerifyAndClear(&source_observer_);
EXPECT_TRUE(source_->GetTabLifecycleUnitExternal(raw_third_web_contents));
CloseTabsAndExpectNotifications(
tab_strip_model_.get(),
{first_lifecycle_unit, second_lifecycle_unit, third_lifecycle_unit});
}
| 172,227 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: png_get_int_32(png_bytep buf)
{
png_int_32 i = ((png_int_32)(*buf) << 24) +
((png_int_32)(*(buf + 1)) << 16) +
((png_int_32)(*(buf + 2)) << 8) +
(png_int_32)(*(buf + 3));
return (i);
}
Commit Message: third_party/libpng: update to 1.2.54
[email protected]
BUG=560291
Review URL: https://codereview.chromium.org/1467263003
Cr-Commit-Position: refs/heads/master@{#362298}
CWE ID: CWE-119 | png_get_int_32(png_bytep buf)
{
png_int_32 i = ((png_int_32)((*(buf )) & 0xff) << 24) +
((png_int_32)((*(buf + 1)) & 0xff) << 16) +
((png_int_32)((*(buf + 2)) & 0xff) << 8) +
((png_int_32)((*(buf + 3)) & 0xff) );
return (i);
}
| 172,173 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DeviceTokenFetcher::SetState(FetcherState state) {
state_ = state;
if (state_ != STATE_TEMPORARY_ERROR)
effective_token_fetch_error_delay_ms_ = kTokenFetchErrorDelayMilliseconds;
base::Time delayed_work_at;
switch (state_) {
case STATE_INACTIVE:
notifier_->Inform(CloudPolicySubsystem::UNENROLLED,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_TOKEN_AVAILABLE:
notifier_->Inform(CloudPolicySubsystem::SUCCESS,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_UNMANAGED:
delayed_work_at = cache_->last_policy_refresh_time() +
base::TimeDelta::FromMilliseconds(
kUnmanagedDeviceRefreshRateMilliseconds);
notifier_->Inform(CloudPolicySubsystem::UNMANAGED,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_TEMPORARY_ERROR:
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
effective_token_fetch_error_delay_ms_ =
std::min(effective_token_fetch_error_delay_ms_ * 2,
kTokenFetchErrorMaxDelayMilliseconds);
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_ERROR:
effective_token_fetch_error_delay_ms_ =
kTokenFetchErrorMaxDelayMilliseconds;
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_BAD_AUTH:
notifier_->Inform(CloudPolicySubsystem::BAD_GAIA_TOKEN,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
}
scheduler_->CancelDelayedWork();
if (!delayed_work_at.is_null()) {
base::Time now(base::Time::Now());
int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0);
scheduler_->PostDelayedWork(
base::Bind(&DeviceTokenFetcher::DoWork, base::Unretained(this)), delay);
}
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void DeviceTokenFetcher::SetState(FetcherState state) {
state_ = state;
if (state_ != STATE_TEMPORARY_ERROR)
effective_token_fetch_error_delay_ms_ = kTokenFetchErrorDelayMilliseconds;
backend_.reset(); // Stop any pending requests.
base::Time delayed_work_at;
switch (state_) {
case STATE_INACTIVE:
notifier_->Inform(CloudPolicySubsystem::UNENROLLED,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_TOKEN_AVAILABLE:
notifier_->Inform(CloudPolicySubsystem::SUCCESS,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_UNMANAGED:
delayed_work_at = cache_->last_policy_refresh_time() +
base::TimeDelta::FromMilliseconds(
kUnmanagedDeviceRefreshRateMilliseconds);
notifier_->Inform(CloudPolicySubsystem::UNMANAGED,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_TEMPORARY_ERROR:
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
effective_token_fetch_error_delay_ms_ =
std::min(effective_token_fetch_error_delay_ms_ * 2,
kTokenFetchErrorMaxDelayMilliseconds);
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_ERROR:
effective_token_fetch_error_delay_ms_ =
kTokenFetchErrorMaxDelayMilliseconds;
delayed_work_at = base::Time::Now() +
base::TimeDelta::FromMilliseconds(
effective_token_fetch_error_delay_ms_);
notifier_->Inform(CloudPolicySubsystem::NETWORK_ERROR,
CloudPolicySubsystem::DMTOKEN_NETWORK_ERROR,
PolicyNotifier::TOKEN_FETCHER);
break;
case STATE_BAD_AUTH:
notifier_->Inform(CloudPolicySubsystem::BAD_GAIA_TOKEN,
CloudPolicySubsystem::NO_DETAILS,
PolicyNotifier::TOKEN_FETCHER);
break;
}
scheduler_->CancelDelayedWork();
if (!delayed_work_at.is_null()) {
base::Time now(base::Time::Now());
int64 delay = std::max<int64>((delayed_work_at - now).InMilliseconds(), 0);
scheduler_->PostDelayedWork(
base::Bind(&DeviceTokenFetcher::DoWork, base::Unretained(this)), delay);
}
}
| 170,284 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void llc_conn_handler(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_addr saddr, daddr;
struct sock *sk;
llc_pdu_decode_sa(skb, saddr.mac);
llc_pdu_decode_ssap(skb, &saddr.lsap);
llc_pdu_decode_da(skb, daddr.mac);
llc_pdu_decode_dsap(skb, &daddr.lsap);
sk = __llc_lookup(sap, &saddr, &daddr);
if (!sk)
goto drop;
bh_lock_sock(sk);
/*
* This has to be done here and not at the upper layer ->accept
* method because of the way the PROCOM state machine works:
* it needs to set several state variables (see, for instance,
* llc_adm_actions_2 in net/llc/llc_c_st.c) and send a packet to
* the originator of the new connection, and this state has to be
* in the newly created struct sock private area. -acme
*/
if (unlikely(sk->sk_state == TCP_LISTEN)) {
struct sock *newsk = llc_create_incoming_sock(sk, skb->dev,
&saddr, &daddr);
if (!newsk)
goto drop_unlock;
skb_set_owner_r(skb, newsk);
} else {
/*
* Can't be skb_set_owner_r, this will be done at the
* llc_conn_state_process function, later on, when we will use
* skb_queue_rcv_skb to send it to upper layers, this is
* another trick required to cope with how the PROCOM state
* machine works. -acme
*/
skb->sk = sk;
}
if (!sock_owned_by_user(sk))
llc_conn_rcv(sk, skb);
else {
dprintk("%s: adding to backlog...\n", __func__);
llc_set_backlog_type(skb, LLC_PACKET);
if (sk_add_backlog(sk, skb, sk->sk_rcvbuf))
goto drop_unlock;
}
out:
bh_unlock_sock(sk);
sock_put(sk);
return;
drop:
kfree_skb(skb);
return;
drop_unlock:
kfree_skb(skb);
goto out;
}
Commit Message: net/llc: avoid BUG_ON() in skb_orphan()
It seems nobody used LLC since linux-3.12.
Fortunately fuzzers like syzkaller still know how to run this code,
otherwise it would be no fun.
Setting skb->sk without skb->destructor leads to all kinds of
bugs, we now prefer to be very strict about it.
Ideally here we would use skb_set_owner() but this helper does not exist yet,
only CAN seems to have a private helper for that.
Fixes: 376c7311bdb6 ("net: add a temporary sanity check in skb_orphan()")
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-20 | void llc_conn_handler(struct llc_sap *sap, struct sk_buff *skb)
{
struct llc_addr saddr, daddr;
struct sock *sk;
llc_pdu_decode_sa(skb, saddr.mac);
llc_pdu_decode_ssap(skb, &saddr.lsap);
llc_pdu_decode_da(skb, daddr.mac);
llc_pdu_decode_dsap(skb, &daddr.lsap);
sk = __llc_lookup(sap, &saddr, &daddr);
if (!sk)
goto drop;
bh_lock_sock(sk);
/*
* This has to be done here and not at the upper layer ->accept
* method because of the way the PROCOM state machine works:
* it needs to set several state variables (see, for instance,
* llc_adm_actions_2 in net/llc/llc_c_st.c) and send a packet to
* the originator of the new connection, and this state has to be
* in the newly created struct sock private area. -acme
*/
if (unlikely(sk->sk_state == TCP_LISTEN)) {
struct sock *newsk = llc_create_incoming_sock(sk, skb->dev,
&saddr, &daddr);
if (!newsk)
goto drop_unlock;
skb_set_owner_r(skb, newsk);
} else {
/*
* Can't be skb_set_owner_r, this will be done at the
* llc_conn_state_process function, later on, when we will use
* skb_queue_rcv_skb to send it to upper layers, this is
* another trick required to cope with how the PROCOM state
* machine works. -acme
*/
skb_orphan(skb);
sock_hold(sk);
skb->sk = sk;
skb->destructor = sock_efree;
}
if (!sock_owned_by_user(sk))
llc_conn_rcv(sk, skb);
else {
dprintk("%s: adding to backlog...\n", __func__);
llc_set_backlog_type(skb, LLC_PACKET);
if (sk_add_backlog(sk, skb, sk->sk_rcvbuf))
goto drop_unlock;
}
out:
bh_unlock_sock(sk);
sock_put(sk);
return;
drop:
kfree_skb(skb);
return;
drop_unlock:
kfree_skb(skb);
goto out;
}
| 168,348 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool Block::IsInvisible() const
{
return bool(int(m_flags & 0x08) != 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 | bool Block::IsInvisible() const
const Block::Frame& Block::GetFrame(int idx) const {
assert(idx >= 0);
assert(idx < m_frame_count);
const Frame& f = m_frames[idx];
assert(f.pos > 0);
assert(f.len > 0);
return f;
}
| 174,391 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FindBarController::EndFindSession(SelectionAction action) {
find_bar_->Hide(true);
if (tab_contents_) {
FindManager* find_manager = tab_contents_->GetFindManager();
find_manager->StopFinding(action);
if (action != kKeepSelection)
find_bar_->ClearResults(find_manager->find_result());
find_bar_->RestoreSavedFocus();
}
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void FindBarController::EndFindSession(SelectionAction action) {
find_bar_->Hide(true);
if (tab_contents_) {
FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper();
find_tab_helper->StopFinding(action);
if (action != kKeepSelection)
find_bar_->ClearResults(find_tab_helper->find_result());
find_bar_->RestoreSavedFocus();
}
}
| 170,658 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProxyChannelDelegate::~ProxyChannelDelegate() {
}
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 | ProxyChannelDelegate::~ProxyChannelDelegate() {
| 170,740 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppControllerImpl::GetArcAndroidId(
mojom::AppController::GetArcAndroidIdCallback callback) {
arc::GetAndroidId(base::BindOnce(
[](mojom::AppController::GetArcAndroidIdCallback callback, bool success,
int64_t android_id) {
std::move(callback).Run(success, base::NumberToString(android_id));
},
std::move(callback)));
}
Commit Message: Refactor the AppController implementation into a KeyedService.
This is necessary to guarantee that the AppController will not outlive
the AppServiceProxy, which could happen before during Profile destruction.
Bug: 945427
Change-Id: I9e2089799e38d5a70a4a9aa66df5319113e7809e
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1542336
Reviewed-by: Michael Giuffrida <[email protected]>
Commit-Queue: Lucas Tenório <[email protected]>
Cr-Commit-Position: refs/heads/master@{#645122}
CWE ID: CWE-416 | void AppControllerImpl::GetArcAndroidId(
void AppControllerService::GetArcAndroidId(
mojom::AppController::GetArcAndroidIdCallback callback) {
arc::GetAndroidId(base::BindOnce(
[](mojom::AppController::GetArcAndroidIdCallback callback, bool success,
int64_t android_id) {
std::move(callback).Run(success, base::NumberToString(android_id));
},
std::move(callback)));
}
| 172,083 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int sock_send_fd(int sock_fd, const uint8_t* buf, int len, int send_fd)
{
ssize_t ret;
struct msghdr msg;
unsigned char *buffer = (unsigned char *)buf;
memset(&msg, 0, sizeof(msg));
struct cmsghdr *cmsg;
char msgbuf[CMSG_SPACE(1)];
asrt(send_fd != -1);
if(sock_fd == -1 || send_fd == -1)
return -1;
msg.msg_control = msgbuf;
msg.msg_controllen = sizeof msgbuf;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof send_fd);
memcpy(CMSG_DATA(cmsg), &send_fd, sizeof send_fd);
int ret_len = len;
while (len > 0) {
struct iovec iv;
memset(&iv, 0, sizeof(iv));
iv.iov_base = buffer;
iv.iov_len = len;
msg.msg_iov = &iv;
msg.msg_iovlen = 1;
do {
ret = sendmsg(sock_fd, &msg, MSG_NOSIGNAL);
} while (ret < 0 && errno == EINTR);
if (ret < 0) {
BTIF_TRACE_ERROR("fd:%d, send_fd:%d, sendmsg ret:%d, errno:%d, %s",
sock_fd, send_fd, (int)ret, errno, strerror(errno));
ret_len = -1;
break;
}
buffer += ret;
len -= ret;
memset(&msg, 0, sizeof(msg));
}
BTIF_TRACE_DEBUG("close fd:%d after sent", send_fd);
close(send_fd);
return ret_len;
}
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 sock_send_fd(int sock_fd, const uint8_t* buf, int len, int send_fd)
{
ssize_t ret;
struct msghdr msg;
unsigned char *buffer = (unsigned char *)buf;
memset(&msg, 0, sizeof(msg));
struct cmsghdr *cmsg;
char msgbuf[CMSG_SPACE(1)];
asrt(send_fd != -1);
if(sock_fd == -1 || send_fd == -1)
return -1;
msg.msg_control = msgbuf;
msg.msg_controllen = sizeof msgbuf;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof send_fd);
memcpy(CMSG_DATA(cmsg), &send_fd, sizeof send_fd);
int ret_len = len;
while (len > 0) {
struct iovec iv;
memset(&iv, 0, sizeof(iv));
iv.iov_base = buffer;
iv.iov_len = len;
msg.msg_iov = &iv;
msg.msg_iovlen = 1;
do {
ret = TEMP_FAILURE_RETRY(sendmsg(sock_fd, &msg, MSG_NOSIGNAL));
} while (ret < 0 && errno == EINTR);
if (ret < 0) {
BTIF_TRACE_ERROR("fd:%d, send_fd:%d, sendmsg ret:%d, errno:%d, %s",
sock_fd, send_fd, (int)ret, errno, strerror(errno));
ret_len = -1;
break;
}
buffer += ret;
len -= ret;
memset(&msg, 0, sizeof(msg));
}
BTIF_TRACE_DEBUG("close fd:%d after sent", send_fd);
close(send_fd);
return ret_len;
}
| 173,470 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame,
WebKit::WebNode* node,
bool is_preview) {
DCHECK(frame);
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
&settings.params));
bool result = true;
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
if (!is_preview) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
}
result = false;
}
if (result &&
(settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
NOTREACHED();
result = false;
}
settings.pages.clear();
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
return result;
}
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 PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame,
bool PrintWebViewHelper::InitPrintSettings(WebKit::WebFrame* frame) {
DCHECK(frame);
PrintMsg_PrintPages_Params settings;
Send(new PrintHostMsg_GetDefaultPrintSettings(routing_id(),
&settings.params));
bool result = true;
if (PrintMsg_Print_Params_IsEmpty(settings.params)) {
render_view()->runModalAlertDialog(
frame,
l10n_util::GetStringUTF16(
IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS));
result = false;
}
if (result &&
(settings.params.dpi < kMinDpi || settings.params.document_cookie == 0)) {
NOTREACHED();
result = false;
}
settings.pages.clear();
print_pages_params_.reset(new PrintMsg_PrintPages_Params(settings));
return result;
}
| 170,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WasmCompileStreamingImpl(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
ScriptState* script_state = ScriptState::ForRelevantRealm(args);
v8::Local<v8::Function> compile_callback =
v8::Function::New(isolate, CompileFromResponseCallback);
V8SetReturnValue(args, ScriptPromise::Cast(script_state, args[0])
.Then(compile_callback)
.V8Value());
}
Commit Message: [wasm] Use correct bindings APIs
Use ScriptState::ForCurrentRealm in static methods, instead of
ForRelevantRealm().
Bug: chromium:788453
Change-Id: I63bd25e3f5a4e8d7cbaff945da8df0d71aa65527
Reviewed-on: https://chromium-review.googlesource.com/795096
Commit-Queue: Mircea Trofin <[email protected]>
Reviewed-by: Yuki Shiino <[email protected]>
Reviewed-by: Kentaro Hara <[email protected]>
Cr-Commit-Position: refs/heads/master@{#520174}
CWE ID: CWE-79 | void WasmCompileStreamingImpl(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
ScriptState* script_state = ScriptState::ForCurrentRealm(args);
v8::Local<v8::Function> compile_callback =
v8::Function::New(isolate, CompileFromResponseCallback);
V8SetReturnValue(args, ScriptPromise::Cast(script_state, args[0])
.Then(compile_callback)
.V8Value());
}
| 172,939 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct sk_buff **gre_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct sk_buff *p;
const struct gre_base_hdr *greh;
unsigned int hlen, grehlen;
unsigned int off;
int flush = 1;
struct packet_offload *ptype;
__be16 type;
off = skb_gro_offset(skb);
hlen = off + sizeof(*greh);
greh = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out;
}
/* Only support version 0 and K (key), C (csum) flags. Note that
* although the support for the S (seq#) flag can be added easily
* for GRO, this is problematic for GSO hence can not be enabled
* here because a GRO pkt may end up in the forwarding path, thus
* requiring GSO support to break it up correctly.
*/
if ((greh->flags & ~(GRE_KEY|GRE_CSUM)) != 0)
goto out;
type = greh->protocol;
rcu_read_lock();
ptype = gro_find_receive_by_type(type);
if (!ptype)
goto out_unlock;
grehlen = GRE_HEADER_SECTION;
if (greh->flags & GRE_KEY)
grehlen += GRE_HEADER_SECTION;
if (greh->flags & GRE_CSUM)
grehlen += GRE_HEADER_SECTION;
hlen = off + grehlen;
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out_unlock;
}
/* Don't bother verifying checksum if we're going to flush anyway. */
if ((greh->flags & GRE_CSUM) && !NAPI_GRO_CB(skb)->flush) {
if (skb_gro_checksum_simple_validate(skb))
goto out_unlock;
skb_gro_checksum_try_convert(skb, IPPROTO_GRE, 0,
null_compute_pseudo);
}
for (p = *head; p; p = p->next) {
const struct gre_base_hdr *greh2;
if (!NAPI_GRO_CB(p)->same_flow)
continue;
/* The following checks are needed to ensure only pkts
* from the same tunnel are considered for aggregation.
* The criteria for "the same tunnel" includes:
* 1) same version (we only support version 0 here)
* 2) same protocol (we only support ETH_P_IP for now)
* 3) same set of flags
* 4) same key if the key field is present.
*/
greh2 = (struct gre_base_hdr *)(p->data + off);
if (greh2->flags != greh->flags ||
greh2->protocol != greh->protocol) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
if (greh->flags & GRE_KEY) {
/* compare keys */
if (*(__be32 *)(greh2+1) != *(__be32 *)(greh+1)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
}
}
skb_gro_pull(skb, grehlen);
/* Adjusted NAPI_GRO_CB(skb)->csum after skb_gro_pull()*/
skb_gro_postpull_rcsum(skb, greh, grehlen);
pp = ptype->callbacks.gro_receive(head, skb);
flush = 0;
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
Commit Message: tunnels: Don't apply GRO to multiple layers of encapsulation.
When drivers express support for TSO of encapsulated packets, they
only mean that they can do it for one layer of encapsulation.
Supporting additional levels would mean updating, at a minimum,
more IP length fields and they are unaware of this.
No encapsulation device expresses support for handling offloaded
encapsulated packets, so we won't generate these types of frames
in the transmit path. However, GRO doesn't have a check for
multiple levels of encapsulation and will attempt to build them.
UDP tunnel GRO actually does prevent this situation but it only
handles multiple UDP tunnels stacked on top of each other. This
generalizes that solution to prevent any kind of tunnel stacking
that would cause problems.
Fixes: bf5a755f ("net-gre-gro: Add GRE support to the GRO stack")
Signed-off-by: Jesse Gross <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-400 | static struct sk_buff **gre_gro_receive(struct sk_buff **head,
struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct sk_buff *p;
const struct gre_base_hdr *greh;
unsigned int hlen, grehlen;
unsigned int off;
int flush = 1;
struct packet_offload *ptype;
__be16 type;
if (NAPI_GRO_CB(skb)->encap_mark)
goto out;
NAPI_GRO_CB(skb)->encap_mark = 1;
off = skb_gro_offset(skb);
hlen = off + sizeof(*greh);
greh = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out;
}
/* Only support version 0 and K (key), C (csum) flags. Note that
* although the support for the S (seq#) flag can be added easily
* for GRO, this is problematic for GSO hence can not be enabled
* here because a GRO pkt may end up in the forwarding path, thus
* requiring GSO support to break it up correctly.
*/
if ((greh->flags & ~(GRE_KEY|GRE_CSUM)) != 0)
goto out;
type = greh->protocol;
rcu_read_lock();
ptype = gro_find_receive_by_type(type);
if (!ptype)
goto out_unlock;
grehlen = GRE_HEADER_SECTION;
if (greh->flags & GRE_KEY)
grehlen += GRE_HEADER_SECTION;
if (greh->flags & GRE_CSUM)
grehlen += GRE_HEADER_SECTION;
hlen = off + grehlen;
if (skb_gro_header_hard(skb, hlen)) {
greh = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!greh))
goto out_unlock;
}
/* Don't bother verifying checksum if we're going to flush anyway. */
if ((greh->flags & GRE_CSUM) && !NAPI_GRO_CB(skb)->flush) {
if (skb_gro_checksum_simple_validate(skb))
goto out_unlock;
skb_gro_checksum_try_convert(skb, IPPROTO_GRE, 0,
null_compute_pseudo);
}
for (p = *head; p; p = p->next) {
const struct gre_base_hdr *greh2;
if (!NAPI_GRO_CB(p)->same_flow)
continue;
/* The following checks are needed to ensure only pkts
* from the same tunnel are considered for aggregation.
* The criteria for "the same tunnel" includes:
* 1) same version (we only support version 0 here)
* 2) same protocol (we only support ETH_P_IP for now)
* 3) same set of flags
* 4) same key if the key field is present.
*/
greh2 = (struct gre_base_hdr *)(p->data + off);
if (greh2->flags != greh->flags ||
greh2->protocol != greh->protocol) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
if (greh->flags & GRE_KEY) {
/* compare keys */
if (*(__be32 *)(greh2+1) != *(__be32 *)(greh+1)) {
NAPI_GRO_CB(p)->same_flow = 0;
continue;
}
}
}
skb_gro_pull(skb, grehlen);
/* Adjusted NAPI_GRO_CB(skb)->csum after skb_gro_pull()*/
skb_gro_postpull_rcsum(skb, greh, grehlen);
pp = ptype->callbacks.gro_receive(head, skb);
flush = 0;
out_unlock:
rcu_read_unlock();
out:
NAPI_GRO_CB(skb)->flush |= flush;
return pp;
}
| 166,906 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: test_js (void) {
GString *result = g_string_new("");
/* simple javascript can be evaluated and returned */
parse_cmd_line("js ('x' + 345).toUpperCase()", result);
g_assert_cmpstr("X345", ==, result->str);
/* uzbl commands can be run from javascript */
uzbl.net.useragent = "Test useragent";
parse_cmd_line("js Uzbl.run('print @useragent').toUpperCase();", result);
g_assert_cmpstr("TEST USERAGENT", ==, result->str);
g_string_free(result, TRUE);
}
Commit Message: disable Uzbl javascript object because of security problem.
CWE ID: CWE-264 | test_js (void) {
GString *result = g_string_new("");
/* simple javascript can be evaluated and returned */
parse_cmd_line("js ('x' + 345).toUpperCase()", result);
g_assert_cmpstr("X345", ==, result->str);
g_string_free(result, TRUE);
}
| 165,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Utterance::~Utterance() {
DCHECK_EQ(completion_task_, static_cast<Task *>(NULL));
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | Utterance::~Utterance() {
| 170,397 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *pktap_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint32 pkt_len, rectype, dlt;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP");
col_clear(pinfo->cinfo, COL_INFO);
pkt_len = tvb_get_letohl(tvb, offset);
col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len);
/* Dissect the packet */
ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA);
pktap_tree = proto_item_add_subtree(ti, ett_pktap);
proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
if (pkt_len < MIN_PKTAP_HDR_LEN) {
proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short,
tvb, offset, 4);
return;
}
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
rectype = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
dlt = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24,
ENC_ASCII|ENC_NA);
offset += 24;
proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
offset += 20;
proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
/*offset += 20;*/
if (rectype == PKT_REC_PACKET) {
next_tvb = tvb_new_subset_remaining(tvb, pkt_len);
dissector_try_uint(wtap_encap_dissector_table,
wtap_pcap_encap_to_wtap_encap(dlt), next_tvb, pinfo, tree);
}
}
Commit Message: The WTAP_ENCAP_ETHERNET dissector needs to be passed a struct eth_phdr.
We now require that. Make it so.
Bug: 12440
Change-Id: Iffee520976b013800699bde3c6092a3e86be0d76
Reviewed-on: https://code.wireshark.org/review/15424
Reviewed-by: Guy Harris <[email protected]>
CWE ID: CWE-20 | dissect_pktap(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
proto_tree *pktap_tree = NULL;
proto_item *ti = NULL;
tvbuff_t *next_tvb;
int offset = 0;
guint32 pkt_len, rectype, dlt;
int wtap_encap;
struct eth_phdr eth;
void *phdr;
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PKTAP");
col_clear(pinfo->cinfo, COL_INFO);
pkt_len = tvb_get_letohl(tvb, offset);
col_add_fstr(pinfo->cinfo, COL_INFO, "PKTAP, %u byte header", pkt_len);
/* Dissect the packet */
ti = proto_tree_add_item(tree, proto_pktap, tvb, offset, pkt_len, ENC_NA);
pktap_tree = proto_item_add_subtree(ti, ett_pktap);
proto_tree_add_item(pktap_tree, hf_pktap_hdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
if (pkt_len < MIN_PKTAP_HDR_LEN) {
proto_tree_add_expert(tree, pinfo, &ei_pktap_hdrlen_too_short,
tvb, offset, 4);
return;
}
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_rectype, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
rectype = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_dlt, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
dlt = tvb_get_letohl(tvb, offset);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ifname, tvb, offset, 24,
ENC_ASCII|ENC_NA);
offset += 24;
proto_tree_add_item(pktap_tree, hf_pktap_flags, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pfamily, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_llhdrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_lltrlrlen, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_pid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_cmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
offset += 20;
proto_tree_add_item(pktap_tree, hf_pktap_svc_class, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_iftype, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_ifunit, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(pktap_tree, hf_pktap_epid, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
proto_tree_add_item(pktap_tree, hf_pktap_ecmdname, tvb, offset, 20,
ENC_UTF_8|ENC_NA);
/*offset += 20;*/
if (rectype == PKT_REC_PACKET) {
next_tvb = tvb_new_subset_remaining(tvb, pkt_len);
wtap_encap = wtap_pcap_encap_to_wtap_encap(dlt);
switch (wtap_encap) {
case WTAP_ENCAP_ETHERNET:
eth.fcs_len = -1; /* Unknown whether we have an FCS */
phdr = ð
break;
default:
phdr = NULL;
break;
}
dissector_try_uint_new(wtap_encap_dissector_table,
wtap_encap, next_tvb, pinfo, tree, TRUE, phdr);
}
}
| 167,143 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(FilesystemIterator, getFlags)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));
} /* }}} */
/* {{{ proto void FilesystemIterator::setFlags(long $flags)
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(FilesystemIterator, getFlags)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK));
} /* }}} */
/* {{{ proto void FilesystemIterator::setFlags(long $flags)
| 167,044 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
jas_image_t *image)
{
int pad;
int nz;
int z;
int c;
int y;
int x;
int v;
int i;
jas_matrix_t *data[3];
/* Note: This function does not properly handle images with a colormap. */
/* Avoid compiler warnings about unused parameters. */
cmap = 0;
for (i = 0; i < jas_image_numcmpts(image); ++i) {
data[i] = jas_matrix_create(1, jas_image_width(image));
assert(data[i]);
}
pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8;
for (y = 0; y < hdr->height; y++) {
nz = 0;
z = 0;
for (x = 0; x < hdr->width; x++) {
while (nz < hdr->depth) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
z = (z << 8) | c;
nz += 8;
}
v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth);
z &= RAS_ONES(nz - hdr->depth);
nz -= hdr->depth;
if (jas_image_numcmpts(image) == 3) {
jas_matrix_setv(data[0], x, (RAS_GETRED(v)));
jas_matrix_setv(data[1], x, (RAS_GETGREEN(v)));
jas_matrix_setv(data[2], x, (RAS_GETBLUE(v)));
} else {
jas_matrix_setv(data[0], x, (v));
}
}
if (pad) {
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1,
data[i])) {
return -1;
}
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
jas_matrix_destroy(data[i]);
}
return 0;
}
Commit Message: Fixed a few bugs in the RAS encoder and decoder where errors were tested
with assertions instead of being gracefully handled.
CWE ID: | static int ras_getdatastd(jas_stream_t *in, ras_hdr_t *hdr, ras_cmap_t *cmap,
jas_image_t *image)
{
int pad;
int nz;
int z;
int c;
int y;
int x;
int v;
int i;
jas_matrix_t *data[3];
/* Note: This function does not properly handle images with a colormap. */
/* Avoid compiler warnings about unused parameters. */
cmap = 0;
assert(jas_image_numcmpts(image) <= 3);
for (i = 0; i < 3; ++i) {
data[i] = 0;
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
if (!(data[i] = jas_matrix_create(1, jas_image_width(image)))) {
goto error;
}
}
pad = RAS_ROWSIZE(hdr) - (hdr->width * hdr->depth + 7) / 8;
for (y = 0; y < hdr->height; y++) {
nz = 0;
z = 0;
for (x = 0; x < hdr->width; x++) {
while (nz < hdr->depth) {
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
z = (z << 8) | c;
nz += 8;
}
v = (z >> (nz - hdr->depth)) & RAS_ONES(hdr->depth);
z &= RAS_ONES(nz - hdr->depth);
nz -= hdr->depth;
if (jas_image_numcmpts(image) == 3) {
jas_matrix_setv(data[0], x, (RAS_GETRED(v)));
jas_matrix_setv(data[1], x, (RAS_GETGREEN(v)));
jas_matrix_setv(data[2], x, (RAS_GETBLUE(v)));
} else {
jas_matrix_setv(data[0], x, (v));
}
}
if (pad) {
if ((c = jas_stream_getc(in)) == EOF) {
goto error;
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
if (jas_image_writecmpt(image, i, 0, y, hdr->width, 1,
data[i])) {
goto error;
}
}
}
for (i = 0; i < jas_image_numcmpts(image); ++i) {
jas_matrix_destroy(data[i]);
data[i] = 0;
}
return 0;
error:
for (i = 0; i < 3; ++i) {
if (data[i]) {
jas_matrix_destroy(data[i]);
}
}
return -1;
}
| 168,740 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::GetNext(
const BlockEntry* pCurr,
const BlockEntry*& pNext) const
{
assert(pCurr);
assert(m_entries);
assert(m_entries_count > 0);
size_t idx = pCurr->GetIndex();
assert(idx < size_t(m_entries_count));
assert(m_entries[idx] == pCurr);
++idx;
if (idx >= size_t(m_entries_count))
{
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) //error
{
pNext = NULL;
return status;
}
if (status > 0)
{
pNext = NULL;
return 0;
}
assert(m_entries);
assert(m_entries_count > 0);
assert(idx < size_t(m_entries_count));
}
pNext = m_entries[idx];
assert(pNext);
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::GetNext(
size_t idx = pCurr->GetIndex();
assert(idx < size_t(m_entries_count));
assert(m_entries[idx] == pCurr);
++idx;
if (idx >= size_t(m_entries_count)) {
long long pos;
long len;
const long status = Parse(pos, len);
if (status < 0) { // error
pNext = NULL;
return status;
}
if (status > 0) {
pNext = NULL;
return 0;
}
assert(m_entries);
assert(m_entries_count > 0);
assert(idx < size_t(m_entries_count));
}
pNext = m_entries[idx];
assert(pNext);
return 0;
}
| 174,345 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: log2vis_encoded_string (PyObject * string, const char *encoding,
FriBidiParType base_direction, int clean, int reordernsm)
{
PyObject *logical = NULL; /* logical unicode object */
PyObject *result = NULL; /* output string object */
/* Always needed for the string length */
logical = PyUnicode_Decode (PyString_AS_STRING (string),
PyString_GET_SIZE (string),
encoding, "strict");
if (logical == NULL)
return NULL;
if (strcmp (encoding, "utf-8") == 0)
/* Shortcut for utf8 strings (little faster) */
result = log2vis_utf8 (string,
PyUnicode_GET_SIZE (logical),
base_direction, clean, reordernsm);
else
{
/* Invoke log2vis_unicode and encode back to encoding */
PyObject *visual = log2vis_unicode (logical, base_direction, clean, reordernsm);
if (visual)
{
result = PyUnicode_Encode (PyUnicode_AS_UNICODE
(visual),
PyUnicode_GET_SIZE (visual),
encoding, "strict");
Py_DECREF (visual);
}
}
Py_DECREF (logical);
return result;
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119 | log2vis_encoded_string (PyObject * string, const char *encoding,
| 165,640 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_png_set_strip_alpha_add(image_transform *this,
PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
}
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_strip_alpha_add(image_transform *this,
const image_transform **that, png_byte colour_type, png_byte bit_depth)
{
UNUSED(bit_depth)
this->next = *that;
*that = this;
return (colour_type & PNG_COLOR_MASK_ALPHA) != 0;
}
| 173,651 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: base::string16 GetApplicationNameForProtocol(const GURL& url) {
base::string16 application_name;
if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
application_name = GetAppForProtocolUsingAssocQuery(url);
if (!application_name.empty())
return application_name;
}
return GetAppForProtocolUsingRegistry(url);
}
Commit Message: Validate external protocols before launching on Windows
Bug: 889459
Change-Id: Id33ca6444bff1e6dd71b6000823cf6fec09746ef
Reviewed-on: https://chromium-review.googlesource.com/c/1256208
Reviewed-by: Greg Thompson <[email protected]>
Commit-Queue: Mustafa Emre Acer <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597611}
CWE ID: CWE-20 | base::string16 GetApplicationNameForProtocol(const GURL& url) {
if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
base::string16 application_name = GetAppForProtocolUsingAssocQuery(url);
if (!application_name.empty())
return application_name;
}
return GetAppForProtocolUsingRegistry(url);
}
| 172,637 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void close_connection(h2o_http2_conn_t *conn)
{
conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING;
if (conn->_write.buf_in_flight != NULL || h2o_timeout_is_linked(&conn->_write.timeout_entry)) {
/* there is a pending write, let on_write_complete actually close the connection */
} else {
close_connection_now(conn);
}
}
Commit Message: h2: use after free on premature connection close #920
lib/http2/connection.c:on_read() calls parse_input(), which might free
`conn`. It does so in particular if the connection preface isn't
the expected one in expect_preface(). `conn` is then used after the free
in `if (h2o_timeout_is_linked(&conn->_write.timeout_entry)`.
We fix this by adding a return value to close_connection that returns a
negative value if `conn` has been free'd and can't be used anymore.
Credits for finding the bug to Tim Newsham.
CWE ID: | void close_connection(h2o_http2_conn_t *conn)
int close_connection(h2o_http2_conn_t *conn)
{
conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING;
if (conn->_write.buf_in_flight != NULL || h2o_timeout_is_linked(&conn->_write.timeout_entry)) {
/* there is a pending write, let on_write_complete actually close the connection */
} else {
close_connection_now(conn);
return -1;
}
return 0;
}
| 167,225 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Mac_Read_POST_Resource( FT_Library library,
FT_Stream stream,
FT_Long *offsets,
FT_Long resource_cnt,
FT_Long face_index,
FT_Face *aface )
{
FT_Error error = FT_Err_Cannot_Open_Resource;
FT_Memory memory = library->memory;
FT_Byte* pfb_data;
int i, type, flags;
FT_Long len;
FT_Long pfb_len, pfb_pos, pfb_lenpos;
FT_Long rlen, temp;
if ( face_index == -1 )
face_index = 0;
if ( face_index != 0 )
return error;
/* Find the length of all the POST resources, concatenated. Assume */
/* worst case (each resource in its own section). */
pfb_len = 0;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit;
if ( FT_READ_LONG( temp ) )
goto Exit;
pfb_len += temp + 6;
}
if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) )
goto Exit;
pfb_data[0] = 0x80;
pfb_data[1] = 1; /* Ascii section */
pfb_data[2] = 0; /* 4-byte length, fill in later */
pfb_data[3] = 0;
pfb_data[4] = 0;
pfb_data[5] = 0;
pfb_pos = 6;
pfb_lenpos = 2;
len = 0;
type = 1;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit2;
if ( FT_READ_LONG( rlen ) )
goto Exit;
if ( FT_READ_USHORT( flags ) )
goto Exit;
rlen -= 2; /* the flags are part of the resource */
if ( ( flags >> 8 ) == type )
len += rlen;
else
{
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
if ( ( flags >> 8 ) == 5 ) /* End of font mark */
break;
pfb_data[pfb_pos++] = 0x80;
type = flags >> 8;
len = rlen;
pfb_data[pfb_pos++] = (FT_Byte)type;
pfb_lenpos = pfb_pos;
pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
}
error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen );
pfb_pos += rlen;
}
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
return open_face_from_buffer( library,
pfb_data,
pfb_pos,
face_index,
"type1",
aface );
Exit2:
FT_FREE( pfb_data );
Exit:
return error;
}
Commit Message:
CWE ID: CWE-119 | Mac_Read_POST_Resource( FT_Library library,
FT_Stream stream,
FT_Long *offsets,
FT_Long resource_cnt,
FT_Long face_index,
FT_Face *aface )
{
FT_Error error = FT_Err_Cannot_Open_Resource;
FT_Memory memory = library->memory;
FT_Byte* pfb_data;
int i, type, flags;
FT_Long len;
FT_Long pfb_len, pfb_pos, pfb_lenpos;
FT_Long rlen, temp;
if ( face_index == -1 )
face_index = 0;
if ( face_index != 0 )
return error;
/* Find the length of all the POST resources, concatenated. Assume */
/* worst case (each resource in its own section). */
pfb_len = 0;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit;
if ( FT_READ_LONG( temp ) )
goto Exit;
pfb_len += temp + 6;
}
if ( FT_ALLOC( pfb_data, (FT_Long)pfb_len + 2 ) )
goto Exit;
pfb_data[0] = 0x80;
pfb_data[1] = 1; /* Ascii section */
pfb_data[2] = 0; /* 4-byte length, fill in later */
pfb_data[3] = 0;
pfb_data[4] = 0;
pfb_data[5] = 0;
pfb_pos = 6;
pfb_lenpos = 2;
len = 0;
type = 1;
for ( i = 0; i < resource_cnt; ++i )
{
error = FT_Stream_Seek( stream, offsets[i] );
if ( error )
goto Exit2;
if ( FT_READ_LONG( rlen ) )
goto Exit;
if ( FT_READ_USHORT( flags ) )
goto Exit;
rlen -= 2; /* the flags are part of the resource */
if ( ( flags >> 8 ) == type )
len += rlen;
else
{
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
if ( ( flags >> 8 ) == 5 ) /* End of font mark */
break;
pfb_data[pfb_pos++] = 0x80;
type = flags >> 8;
len = rlen;
pfb_data[pfb_pos++] = (FT_Byte)type;
pfb_lenpos = pfb_pos;
pfb_data[pfb_pos++] = 0; /* 4-byte length, fill in later */
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
pfb_data[pfb_pos++] = 0;
}
error = FT_Stream_Read( stream, (FT_Byte *)pfb_data + pfb_pos, rlen );
if ( error )
goto Exit2;
pfb_pos += rlen;
}
pfb_data[pfb_lenpos ] = (FT_Byte)( len );
pfb_data[pfb_lenpos + 1] = (FT_Byte)( len >> 8 );
pfb_data[pfb_lenpos + 2] = (FT_Byte)( len >> 16 );
pfb_data[pfb_lenpos + 3] = (FT_Byte)( len >> 24 );
return open_face_from_buffer( library,
pfb_data,
pfb_pos,
face_index,
"type1",
aface );
Exit2:
FT_FREE( pfb_data );
Exit:
return error;
}
| 165,006 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_terminate (MyObject *obj, GError **error)
{
g_main_loop_quit (loop);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_terminate (MyObject *obj, GError **error)
| 165,123 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: iperf_json_printf(const char *format, ...)
{
cJSON* o;
va_list argp;
const char *cp;
char name[100];
char* np;
cJSON* j;
o = cJSON_CreateObject();
if (o == NULL)
return NULL;
va_start(argp, format);
np = name;
for (cp = format; *cp != '\0'; ++cp) {
switch (*cp) {
case ' ':
break;
case ':':
*np = '\0';
break;
case '%':
++cp;
switch (*cp) {
case 'b':
j = cJSON_CreateBool(va_arg(argp, int));
break;
case 'd':
j = cJSON_CreateInt(va_arg(argp, int64_t));
break;
case 'f':
j = cJSON_CreateFloat(va_arg(argp, double));
break;
case 's':
j = cJSON_CreateString(va_arg(argp, char *));
break;
default:
return NULL;
}
if (j == NULL)
return NULL;
cJSON_AddItemToObject(o, name, j);
np = name;
break;
default:
*np++ = *cp;
break;
}
}
va_end(argp);
return o;
}
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 | iperf_json_printf(const char *format, ...)
{
cJSON* o;
va_list argp;
const char *cp;
char name[100];
char* np;
cJSON* j;
o = cJSON_CreateObject();
if (o == NULL)
return NULL;
va_start(argp, format);
np = name;
for (cp = format; *cp != '\0'; ++cp) {
switch (*cp) {
case ' ':
break;
case ':':
*np = '\0';
break;
case '%':
++cp;
switch (*cp) {
case 'b':
j = cJSON_CreateBool(va_arg(argp, int));
break;
case 'd':
j = cJSON_CreateNumber(va_arg(argp, int64_t));
break;
case 'f':
j = cJSON_CreateNumber(va_arg(argp, double));
break;
case 's':
j = cJSON_CreateString(va_arg(argp, char *));
break;
default:
return NULL;
}
if (j == NULL)
return NULL;
cJSON_AddItemToObject(o, name, j);
np = name;
break;
default:
*np++ = *cp;
break;
}
}
va_end(argp);
return o;
}
| 167,318 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: check_acl(pam_handle_t *pamh,
const char *sense, const char *this_user, const char *other_user,
int noent_code, int debug)
{
struct passwd *pwd;
FILE *fp = NULL;
int i, fd = -1, save_errno;
uid_t fsuid;
struct stat st;
/* Check this user's <sense> file. */
pwd = pam_modutil_getpwnam(pamh, this_user);
if (pwd == NULL) {
pam_syslog(pamh, LOG_ERR,
"error determining home directory for '%s'",
this_user);
return PAM_SESSION_ERR;
}
/* Figure out what that file is really named. */
i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense);
if ((i >= (int)sizeof(path)) || (i < 0)) {
pam_syslog(pamh, LOG_ERR,
"name of user's home directory is too long");
return PAM_SESSION_ERR;
}
fsuid = setfsuid(pwd->pw_uid);
if (!stat(path, &st)) {
if (!S_ISREG(st.st_mode))
errno = EINVAL;
fd = open(path, O_RDONLY | O_NOCTTY);
fd = open(path, O_RDONLY | O_NOCTTY);
}
save_errno = errno;
setfsuid(fsuid);
if (fd >= 0) {
if (!fstat(fd, &st)) {
if (!S_ISREG(st.st_mode))
save_errno = errno;
close(fd);
}
}
if (fp) {
char buf[LINE_MAX], *tmp;
/* Scan the file for a list of specs of users to "trust". */
while (fgets(buf, sizeof(buf), fp) != NULL) {
tmp = memchr(buf, '\r', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
tmp = memchr(buf, '\n', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
if (fnmatch(buf, other_user, 0) == 0) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s %s allowed by %s",
other_user, sense, path);
}
fclose(fp);
return PAM_SUCCESS;
}
}
/* If there's no match in the file, we fail. */
if (debug) {
pam_syslog(pamh, LOG_DEBUG, "%s not listed in %s",
other_user, path);
}
fclose(fp);
return PAM_PERM_DENIED;
} else {
/* Default to okay if the file doesn't exist. */
errno = save_errno;
switch (errno) {
case ENOENT:
if (noent_code == PAM_SUCCESS) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, ignoring",
path);
}
} else {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, failing",
path);
}
}
return noent_code;
default:
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"error opening %s: %m", path);
}
return PAM_PERM_DENIED;
}
}
}
Commit Message:
CWE ID: | check_acl(pam_handle_t *pamh,
const char *sense, const char *this_user, const char *other_user,
int noent_code, int debug)
{
struct passwd *pwd;
FILE *fp = NULL;
int i, fd = -1, save_errno;
struct stat st;
PAM_MODUTIL_DEF_PRIVS(privs);
/* Check this user's <sense> file. */
pwd = pam_modutil_getpwnam(pamh, this_user);
if (pwd == NULL) {
pam_syslog(pamh, LOG_ERR,
"error determining home directory for '%s'",
this_user);
return PAM_SESSION_ERR;
}
/* Figure out what that file is really named. */
i = snprintf(path, sizeof(path), "%s/.xauth/%s", pwd->pw_dir, sense);
if ((i >= (int)sizeof(path)) || (i < 0)) {
pam_syslog(pamh, LOG_ERR,
"name of user's home directory is too long");
return PAM_SESSION_ERR;
}
if (pam_modutil_drop_priv(pamh, &privs, pwd))
return PAM_SESSION_ERR;
if (!stat(path, &st)) {
if (!S_ISREG(st.st_mode))
errno = EINVAL;
fd = open(path, O_RDONLY | O_NOCTTY);
fd = open(path, O_RDONLY | O_NOCTTY);
}
save_errno = errno;
if (pam_modutil_regain_priv(pamh, &privs)) {
if (fd >= 0)
close(fd);
return PAM_SESSION_ERR;
}
if (fd >= 0) {
if (!fstat(fd, &st)) {
if (!S_ISREG(st.st_mode))
save_errno = errno;
close(fd);
}
}
if (fp) {
char buf[LINE_MAX], *tmp;
/* Scan the file for a list of specs of users to "trust". */
while (fgets(buf, sizeof(buf), fp) != NULL) {
tmp = memchr(buf, '\r', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
tmp = memchr(buf, '\n', sizeof(buf));
if (tmp != NULL) {
*tmp = '\0';
}
if (fnmatch(buf, other_user, 0) == 0) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s %s allowed by %s",
other_user, sense, path);
}
fclose(fp);
return PAM_SUCCESS;
}
}
/* If there's no match in the file, we fail. */
if (debug) {
pam_syslog(pamh, LOG_DEBUG, "%s not listed in %s",
other_user, path);
}
fclose(fp);
return PAM_PERM_DENIED;
} else {
/* Default to okay if the file doesn't exist. */
errno = save_errno;
switch (errno) {
case ENOENT:
if (noent_code == PAM_SUCCESS) {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, ignoring",
path);
}
} else {
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"%s does not exist, failing",
path);
}
}
return noent_code;
default:
if (debug) {
pam_syslog(pamh, LOG_DEBUG,
"error opening %s: %m", path);
}
return PAM_PERM_DENIED;
}
}
}
| 164,818 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void PrintViewManagerBase::OnDidPrintPage(
const PrintHostMsg_DidPrintPage_Params& params) {
if (!OpportunisticallyCreatePrintJob(params.document_cookie))
return;
PrintedDocument* document = print_job_->document();
if (!document || params.document_cookie != document->cookie()) {
return;
}
#if defined(OS_MACOSX)
const bool metafile_must_be_valid = true;
#else
const bool metafile_must_be_valid = expecting_first_page_;
expecting_first_page_ = false;
#endif
std::unique_ptr<base::SharedMemory> shared_buf;
if (metafile_must_be_valid) {
if (!base::SharedMemory::IsHandleValid(params.metafile_data_handle)) {
NOTREACHED() << "invalid memory handle";
web_contents()->Stop();
return;
}
shared_buf =
base::MakeUnique<base::SharedMemory>(params.metafile_data_handle, true);
if (!shared_buf->Map(params.data_size)) {
NOTREACHED() << "couldn't map";
web_contents()->Stop();
return;
}
} else {
if (base::SharedMemory::IsHandleValid(params.metafile_data_handle)) {
NOTREACHED() << "unexpected valid memory handle";
web_contents()->Stop();
base::SharedMemory::CloseHandle(params.metafile_data_handle);
return;
}
}
std::unique_ptr<PdfMetafileSkia> metafile(
new PdfMetafileSkia(SkiaDocumentType::PDF));
if (metafile_must_be_valid) {
if (!metafile->InitFromData(shared_buf->memory(), params.data_size)) {
NOTREACHED() << "Invalid metafile header";
web_contents()->Stop();
return;
}
}
#if defined(OS_WIN)
print_job_->AppendPrintedPage(params.page_number);
if (metafile_must_be_valid) {
scoped_refptr<base::RefCountedBytes> bytes = new base::RefCountedBytes(
reinterpret_cast<const unsigned char*>(shared_buf->memory()),
params.data_size);
document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf"));
const auto& settings = document->settings();
if (settings.printer_is_textonly()) {
print_job_->StartPdfToTextConversion(bytes, params.page_size);
} else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) &&
!base::FeatureList::IsEnabled(
features::kDisablePostScriptPrinting)) {
print_job_->StartPdfToPostScriptConversion(bytes, params.content_area,
params.physical_offsets,
settings.printer_is_ps2());
} else {
bool print_text_with_gdi = settings.print_text_with_gdi() &&
!settings.printer_is_xps() &&
base::FeatureList::IsEnabled(
features::kGdiTextPrinting);
print_job_->StartPdfToEmfConversion(
bytes, params.page_size, params.content_area, print_text_with_gdi);
}
}
#else
document->SetPage(params.page_number,
std::move(metafile),
#if defined(OS_WIN)
0.0f /* dummy shrink_factor */,
#endif
params.page_size,
params.content_area);
ShouldQuitFromInnerMessageLoop();
#endif
}
Commit Message: Use pdf compositor service for printing when OOPIF is enabled
When OOPIF is enabled (by site-per-process flag or
top-document-isolation feature), use the pdf compositor service for
converting PaintRecord to PDF on renderers.
In the future, this will make compositing PDF from multiple renderers
possible.
[email protected]
BUG=455764
Change-Id: I3c28f03f4358e4228239fe1a33384f85e7716e8f
Reviewed-on: https://chromium-review.googlesource.com/699765
Commit-Queue: Wei Li <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#511616}
CWE ID: CWE-254 | void PrintViewManagerBase::OnDidPrintPage(
const PrintHostMsg_DidPrintPage_Params& params) {
// Ready to composite. Starting a print job.
if (!OpportunisticallyCreatePrintJob(params.document_cookie))
return;
PrintedDocument* document = print_job_->document();
if (!document || params.document_cookie != document->cookie()) {
return;
}
#if defined(OS_MACOSX)
const bool metafile_must_be_valid = true;
#else
const bool metafile_must_be_valid = expecting_first_page_;
expecting_first_page_ = false;
#endif
std::unique_ptr<base::SharedMemory> shared_buf;
if (metafile_must_be_valid) {
if (!base::SharedMemory::IsHandleValid(params.metafile_data_handle)) {
NOTREACHED() << "invalid memory handle";
web_contents()->Stop();
return;
}
auto* client = PrintCompositeClient::FromWebContents(web_contents());
if (IsOopifEnabled() && !client->for_preview() &&
!document->settings().is_modifiable()) {
client->DoComposite(
params.metafile_data_handle, params.data_size,
base::BindOnce(&PrintViewManagerBase::OnComposePdfDone,
weak_ptr_factory_.GetWeakPtr(), params));
return;
}
shared_buf =
std::make_unique<base::SharedMemory>(params.metafile_data_handle, true);
if (!shared_buf->Map(params.data_size)) {
NOTREACHED() << "couldn't map";
web_contents()->Stop();
return;
}
} else {
if (base::SharedMemory::IsHandleValid(params.metafile_data_handle)) {
NOTREACHED() << "unexpected valid memory handle";
web_contents()->Stop();
base::SharedMemory::CloseHandle(params.metafile_data_handle);
return;
}
}
UpdateForPrintedPage(params, metafile_must_be_valid, std::move(shared_buf));
}
void PrintViewManagerBase::UpdateForPrintedPage(
const PrintHostMsg_DidPrintPage_Params& params,
bool has_valid_page_data,
std::unique_ptr<base::SharedMemory> shared_buf) {
PrintedDocument* document = print_job_->document();
if (!document)
return;
#if defined(OS_WIN)
print_job_->AppendPrintedPage(params.page_number);
if (has_valid_page_data) {
scoped_refptr<base::RefCountedBytes> bytes(new base::RefCountedBytes(
reinterpret_cast<const unsigned char*>(shared_buf->memory()),
shared_buf->mapped_size()));
document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf"));
const auto& settings = document->settings();
if (settings.printer_is_textonly()) {
print_job_->StartPdfToTextConversion(bytes, params.page_size);
} else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) &&
!base::FeatureList::IsEnabled(
features::kDisablePostScriptPrinting)) {
print_job_->StartPdfToPostScriptConversion(bytes, params.content_area,
params.physical_offsets,
settings.printer_is_ps2());
} else {
bool print_text_with_gdi =
settings.print_text_with_gdi() && !settings.printer_is_xps() &&
base::FeatureList::IsEnabled(features::kGdiTextPrinting);
print_job_->StartPdfToEmfConversion(
bytes, params.page_size, params.content_area, print_text_with_gdi);
}
}
#else
std::unique_ptr<PdfMetafileSkia> metafile =
std::make_unique<PdfMetafileSkia>(SkiaDocumentType::PDF);
if (has_valid_page_data) {
if (!metafile->InitFromData(shared_buf->memory(),
shared_buf->mapped_size())) {
NOTREACHED() << "Invalid metafile header";
web_contents()->Stop();
return;
}
}
document->SetPage(params.page_number, std::move(metafile), params.page_size,
params.content_area);
ShouldQuitFromInnerMessageLoop();
#endif
}
| 171,892 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: tt_cmap14_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_selectors;
if ( table + 2 + 4 + 4 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 2;
length = TT_NEXT_ULONG( p );
num_selectors = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
/* length < 10 + 11 * num_selectors ? */
length < 10 ||
( length - 10 ) / 11 < num_selectors )
FT_INVALID_TOO_SHORT;
/* check selectors, they must be in increasing order */
{
/* we start lastVarSel at 1 because a variant selector value of 0
* isn't valid.
*/
FT_ULong n, lastVarSel = 1;
for ( n = 0; n < num_selectors; n++ )
{
FT_ULong varSel = TT_NEXT_UINT24( p );
FT_ULong defOff = TT_NEXT_ULONG( p );
FT_ULong nondefOff = TT_NEXT_ULONG( p );
if ( defOff >= length || nondefOff >= length )
FT_INVALID_TOO_SHORT;
if ( varSel < lastVarSel )
FT_INVALID_DATA;
lastVarSel = varSel + 1;
/* check the default table (these glyphs should be reached */
/* through the normal Unicode cmap, no GIDs, just check order) */
if ( defOff != 0 )
{
FT_Byte* defp = table + defOff;
FT_ULong numRanges = TT_NEXT_ULONG( defp );
FT_ULong i;
FT_ULong lastBase = 0;
/* defp + numRanges * 4 > valid->limit ? */
if ( numRanges > (FT_ULong)( valid->limit - defp ) / 4 )
FT_INVALID_TOO_SHORT;
if ( base + cnt >= 0x110000UL ) /* end of Unicode */
FT_INVALID_DATA;
if ( base < lastBase )
FT_INVALID_DATA;
lastBase = base + cnt + 1U;
}
}
/* and the non-default table (these glyphs are specified here) */
if ( nondefOff != 0 )
{
FT_Byte* ndp = table + nondefOff;
FT_ULong numMappings = TT_NEXT_ULONG( ndp );
/* and the non-default table (these glyphs are specified here) */
if ( nondefOff != 0 )
{
FT_Byte* ndp = table + nondefOff;
FT_ULong numMappings = TT_NEXT_ULONG( ndp );
FT_ULong i, lastUni = 0;
/* numMappings * 4 > (FT_ULong)( valid->limit - ndp ) ? */
if ( numMappings > ( (FT_ULong)( valid->limit - ndp ) ) / 4 )
FT_INVALID_TOO_SHORT;
for ( i = 0; i < numMappings; ++i )
lastUni = uni + 1U;
if ( valid->level >= FT_VALIDATE_TIGHT &&
gid >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
}
}
Commit Message:
CWE ID: CWE-125 | tt_cmap14_validate( FT_Byte* table,
FT_Validator valid )
{
FT_Byte* p;
FT_ULong length;
FT_ULong num_selectors;
if ( table + 2 + 4 + 4 > valid->limit )
FT_INVALID_TOO_SHORT;
p = table + 2;
length = TT_NEXT_ULONG( p );
num_selectors = TT_NEXT_ULONG( p );
if ( length > (FT_ULong)( valid->limit - table ) ||
/* length < 10 + 11 * num_selectors ? */
length < 10 ||
( length - 10 ) / 11 < num_selectors )
FT_INVALID_TOO_SHORT;
/* check selectors, they must be in increasing order */
{
/* we start lastVarSel at 1 because a variant selector value of 0
* isn't valid.
*/
FT_ULong n, lastVarSel = 1;
for ( n = 0; n < num_selectors; n++ )
{
FT_ULong varSel = TT_NEXT_UINT24( p );
FT_ULong defOff = TT_NEXT_ULONG( p );
FT_ULong nondefOff = TT_NEXT_ULONG( p );
if ( defOff >= length || nondefOff >= length )
FT_INVALID_TOO_SHORT;
if ( varSel < lastVarSel )
FT_INVALID_DATA;
lastVarSel = varSel + 1;
/* check the default table (these glyphs should be reached */
/* through the normal Unicode cmap, no GIDs, just check order) */
if ( defOff != 0 )
{
FT_Byte* defp = table + defOff;
FT_ULong numRanges;
FT_ULong i;
FT_ULong lastBase = 0;
if ( defp + 4 > valid->limit )
FT_INVALID_TOO_SHORT;
numRanges = TT_NEXT_ULONG( defp );
/* defp + numRanges * 4 > valid->limit ? */
if ( numRanges > (FT_ULong)( valid->limit - defp ) / 4 )
FT_INVALID_TOO_SHORT;
if ( base + cnt >= 0x110000UL ) /* end of Unicode */
FT_INVALID_DATA;
if ( base < lastBase )
FT_INVALID_DATA;
lastBase = base + cnt + 1U;
}
}
/* and the non-default table (these glyphs are specified here) */
if ( nondefOff != 0 )
{
FT_Byte* ndp = table + nondefOff;
FT_ULong numMappings = TT_NEXT_ULONG( ndp );
/* and the non-default table (these glyphs are specified here) */
if ( nondefOff != 0 )
{
FT_Byte* ndp = table + nondefOff;
FT_ULong numMappings;
FT_ULong i, lastUni = 0;
if ( ndp + 4 > valid->limit )
FT_INVALID_TOO_SHORT;
numMappings = TT_NEXT_ULONG( ndp );
/* numMappings * 5 > (FT_ULong)( valid->limit - ndp ) ? */
if ( numMappings > ( (FT_ULong)( valid->limit - ndp ) ) / 5 )
FT_INVALID_TOO_SHORT;
for ( i = 0; i < numMappings; ++i )
lastUni = uni + 1U;
if ( valid->level >= FT_VALIDATE_TIGHT &&
gid >= TT_VALID_GLYPH_COUNT( valid ) )
FT_INVALID_GLYPH_ID;
}
}
}
}
| 165,426 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: image_transform_set_end(PNG_CONST image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
UNUSED(this)
UNUSED(that)
UNUSED(pp)
UNUSED(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_set_end(PNG_CONST image_transform *this,
image_transform_set_end(const image_transform *this,
transform_display *that, png_structp pp, png_infop pi)
{
UNUSED(this)
UNUSED(that)
UNUSED(pp)
UNUSED(pi)
}
| 173,657 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int scm_fp_copy(struct cmsghdr *cmsg, struct scm_fp_list **fplp)
{
int *fdp = (int*)CMSG_DATA(cmsg);
struct scm_fp_list *fpl = *fplp;
struct file **fpp;
int i, num;
num = (cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)))/sizeof(int);
if (num <= 0)
return 0;
if (num > SCM_MAX_FD)
return -EINVAL;
if (!fpl)
{
fpl = kmalloc(sizeof(struct scm_fp_list), GFP_KERNEL);
if (!fpl)
return -ENOMEM;
*fplp = fpl;
fpl->count = 0;
fpl->max = SCM_MAX_FD;
}
fpp = &fpl->fp[fpl->count];
if (fpl->count + num > fpl->max)
return -EINVAL;
/*
* Verify the descriptors and increment the usage count.
*/
for (i=0; i< num; i++)
{
int fd = fdp[i];
struct file *file;
if (fd < 0 || !(file = fget_raw(fd)))
return -EBADF;
*fpp++ = file;
fpl->count++;
}
return num;
}
Commit Message: unix: correctly track in-flight fds in sending process user_struct
The commit referenced in the Fixes tag incorrectly accounted the number
of in-flight fds over a unix domain socket to the original opener
of the file-descriptor. This allows another process to arbitrary
deplete the original file-openers resource limit for the maximum of
open files. Instead the sending processes and its struct cred should
be credited.
To do so, we add a reference counted struct user_struct pointer to the
scm_fp_list and use it to account for the number of inflight unix fds.
Fixes: 712f4aad406bb1 ("unix: properly account for FDs passed over unix sockets")
Reported-by: David Herrmann <[email protected]>
Cc: David Herrmann <[email protected]>
Cc: Willy Tarreau <[email protected]>
Cc: Linus Torvalds <[email protected]>
Suggested-by: Linus Torvalds <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-399 | static int scm_fp_copy(struct cmsghdr *cmsg, struct scm_fp_list **fplp)
{
int *fdp = (int*)CMSG_DATA(cmsg);
struct scm_fp_list *fpl = *fplp;
struct file **fpp;
int i, num;
num = (cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)))/sizeof(int);
if (num <= 0)
return 0;
if (num > SCM_MAX_FD)
return -EINVAL;
if (!fpl)
{
fpl = kmalloc(sizeof(struct scm_fp_list), GFP_KERNEL);
if (!fpl)
return -ENOMEM;
*fplp = fpl;
fpl->count = 0;
fpl->max = SCM_MAX_FD;
fpl->user = NULL;
}
fpp = &fpl->fp[fpl->count];
if (fpl->count + num > fpl->max)
return -EINVAL;
/*
* Verify the descriptors and increment the usage count.
*/
for (i=0; i< num; i++)
{
int fd = fdp[i];
struct file *file;
if (fd < 0 || !(file = fget_raw(fd)))
return -EBADF;
*fpp++ = file;
fpl->count++;
}
if (!fpl->user)
fpl->user = get_uid(current_user());
return num;
}
| 167,392 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
return network_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 | NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
| 170,627 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WorkerFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason) const {
probe::didBlockRequest(global_scope_, resource_request, nullptr,
fetch_initiator_info, blocked_reason);
}
Commit Message: DevTools: send proper resource type in Network.RequestWillBeSent
This patch plumbs resoure type into the DispatchWillSendRequest
instrumenation. This allows us to report accurate type in
Network.RequestWillBeSent event, instead of "Other", that we report
today.
BUG=765501
R=dgozman
Change-Id: I0134c08b841e8dd247fdc8ff208bfd51e462709c
Reviewed-on: https://chromium-review.googlesource.com/667504
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Andrey Lushnikov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#507936}
CWE ID: CWE-119 | void WorkerFetchContext::DispatchDidBlockRequest(
const ResourceRequest& resource_request,
const FetchInitiatorInfo& fetch_initiator_info,
ResourceRequestBlockedReason blocked_reason,
Resource::Type resource_type) const {
probe::didBlockRequest(global_scope_, resource_request, nullptr,
fetch_initiator_info, blocked_reason, resource_type);
}
| 172,475 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static BT_HDR *create_pbuf(UINT16 len, UINT8 *data)
{
BT_HDR* p_buf = GKI_getbuf((UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR)));
if (p_buf) {
UINT8* pbuf_data;
p_buf->len = len;
p_buf->offset = BTA_HH_MIN_OFFSET;
pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset;
memcpy(pbuf_data, data, len);
}
return p_buf;
}
Commit Message: DO NOT MERGE btif: check overflow on create_pbuf size
Bug: 27930580
Change-Id: Ieb1f23f9a8a937b21f7c5eca92da3b0b821400e6
CWE ID: CWE-119 | static BT_HDR *create_pbuf(UINT16 len, UINT8 *data)
{
UINT16 buflen = (UINT16) (len + BTA_HH_MIN_OFFSET + sizeof(BT_HDR));
if (buflen < len) {
android_errorWriteWithInfoLog(0x534e4554, "28672558", -1, NULL, 0);
return NULL;
}
BT_HDR* p_buf = GKI_getbuf(buflen);
if (p_buf) {
UINT8* pbuf_data;
p_buf->len = len;
p_buf->offset = BTA_HH_MIN_OFFSET;
pbuf_data = (UINT8*) (p_buf + 1) + p_buf->offset;
memcpy(pbuf_data, data, len);
}
return p_buf;
}
| 173,757 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (is_swapped_out_) {
if (request.url() != GURL("about:swappedout"))
return WebKit::WebNavigationPolicyIgnore;
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
int cumulative_bindings =
RenderProcess::current()->GetEnabledBindings();
bool should_fork =
content::GetContentClient()->HasWebUIScheme(url) ||
(cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
frame->isViewSourceModeEnabled();
if (!should_fork) {
if (request.httpMethod() == "GET") {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
Commit Message: Use a new scheme for swapping out RenderViews.
BUG=118664
TEST=none
Review URL: http://codereview.chromium.org/9720004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@127986 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | WebNavigationPolicy RenderViewImpl::decidePolicyForNavigation(
WebFrame* frame, const WebURLRequest& request, WebNavigationType type,
const WebNode&, WebNavigationPolicy default_policy, bool is_redirect) {
if (is_swapped_out_) {
if (request.url() != GURL(chrome::kSwappedOutURL))
return WebKit::WebNavigationPolicyIgnore;
// Allow chrome::kSwappedOutURL to complete.
return default_policy;
}
const GURL& url = request.url();
bool is_content_initiated =
DocumentState::FromDataSource(frame->provisionalDataSource())->
navigation_state()->is_content_initiated();
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(switches::kEnableStrictSiteIsolation) &&
!frame->parent() && (is_content_initiated || is_redirect)) {
WebString origin_str = frame->document().securityOrigin().toString();
GURL frame_url(origin_str.utf8().data());
if (frame_url.GetOrigin() != url.GetOrigin()) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
}
if (is_content_initiated) {
bool browser_handles_top_level_requests =
renderer_preferences_.browser_handles_top_level_requests &&
IsNonLocalTopLevelNavigation(url, frame, type);
if (browser_handles_top_level_requests ||
renderer_preferences_.browser_handles_all_requests) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
page_id_ = -1;
last_page_id_sent_to_browser_ = -1;
OpenURL(frame, url, referrer, default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
if (!frame->parent() && is_content_initiated &&
!url.SchemeIs(chrome::kAboutScheme)) {
bool send_referrer = false;
int cumulative_bindings =
RenderProcess::current()->GetEnabledBindings();
bool should_fork =
content::GetContentClient()->HasWebUIScheme(url) ||
(cumulative_bindings & content::BINDINGS_POLICY_WEB_UI) ||
url.SchemeIs(chrome::kViewSourceScheme) ||
frame->isViewSourceModeEnabled();
if (!should_fork) {
if (request.httpMethod() == "GET") {
bool is_initial_navigation = page_id_ == -1;
should_fork = content::GetContentClient()->renderer()->ShouldFork(
frame, url, is_initial_navigation, &send_referrer);
}
}
if (should_fork) {
Referrer referrer(
GURL(request.httpHeaderField(WebString::fromUTF8("Referer"))),
GetReferrerPolicyFromRequest(request));
OpenURL(
frame, url, send_referrer ? referrer : Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore; // Suppress the load here.
}
}
GURL old_url(frame->dataSource()->request().url());
bool is_fork =
old_url == GURL(chrome::kAboutBlankURL) &&
historyBackListCount() < 1 &&
historyForwardListCount() < 1 &&
frame->opener() == NULL &&
frame->parent() == NULL &&
is_content_initiated &&
default_policy == WebKit::WebNavigationPolicyCurrentTab &&
type == WebKit::WebNavigationTypeOther;
if (is_fork) {
OpenURL(frame, url, Referrer(), default_policy);
return WebKit::WebNavigationPolicyIgnore;
}
return default_policy;
}
| 171,032 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void HTMLCanvasElement::Dispose() {
if (PlaceholderFrame())
ReleasePlaceholderFrame();
if (context_) {
context_->DetachHost();
context_ = nullptr;
}
if (canvas2d_bridge_) {
canvas2d_bridge_->SetCanvasResourceHost(nullptr);
canvas2d_bridge_ = nullptr;
}
if (gpu_memory_usage_) {
DCHECK_GT(global_accelerated_context_count_, 0u);
global_accelerated_context_count_--;
}
global_gpu_memory_usage_ -= gpu_memory_usage_;
}
Commit Message: Clean up CanvasResourceDispatcher on finalizer
We may have pending mojo messages after GC, so we want to drop the
dispatcher as soon as possible.
Bug: 929757,913964
Change-Id: I5789bcbb55aada4a74c67a28758f07686f8911c0
Reviewed-on: https://chromium-review.googlesource.com/c/1489175
Reviewed-by: Ken Rockot <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Auto-Submit: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#635833}
CWE ID: CWE-416 | void HTMLCanvasElement::Dispose() {
if (PlaceholderFrame())
ReleasePlaceholderFrame();
// We need to drop frame dispatcher, to prevent mojo calls from completing.
frame_dispatcher_ = nullptr;
if (context_) {
context_->DetachHost();
context_ = nullptr;
}
if (canvas2d_bridge_) {
canvas2d_bridge_->SetCanvasResourceHost(nullptr);
canvas2d_bridge_ = nullptr;
}
if (gpu_memory_usage_) {
DCHECK_GT(global_accelerated_context_count_, 0u);
global_accelerated_context_count_--;
}
global_gpu_memory_usage_ -= gpu_memory_usage_;
}
| 173,028 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool PluginInfoMessageFilter::Context::FindEnabledPlugin(
int render_view_id,
const GURL& url,
const GURL& top_origin_url,
const std::string& mime_type,
ChromeViewHostMsg_GetPluginInfo_Status* status,
WebPluginInfo* plugin,
std::string* actual_mime_type,
scoped_ptr<PluginMetadata>* plugin_metadata) const {
bool allow_wildcard = true;
std::vector<WebPluginInfo> matching_plugins;
std::vector<std::string> mime_types;
PluginService::GetInstance()->GetPluginInfoArray(
url, mime_type, allow_wildcard, &matching_plugins, &mime_types);
if (matching_plugins.empty()) {
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound;
return false;
}
content::PluginServiceFilter* filter =
PluginService::GetInstance()->GetFilter();
size_t i = 0;
for (; i < matching_plugins.size(); ++i) {
if (!filter || filter->IsPluginEnabled(render_process_id_,
render_view_id,
resource_context_,
url,
top_origin_url,
&matching_plugins[i])) {
break;
}
}
bool enabled = i < matching_plugins.size();
if (!enabled) {
i = 0;
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled;
}
*plugin = matching_plugins[i];
*actual_mime_type = mime_types[i];
if (plugin_metadata)
*plugin_metadata = PluginFinder::GetInstance()->GetPluginMetadata(*plugin);
return enabled;
}
Commit Message: Follow-on fixes and naming changes for https://codereview.chromium.org/12086077/
BUG=172573
Review URL: https://codereview.chromium.org/12177018
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@180600 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-287 | bool PluginInfoMessageFilter::Context::FindEnabledPlugin(
int render_view_id,
const GURL& url,
const GURL& top_origin_url,
const std::string& mime_type,
ChromeViewHostMsg_GetPluginInfo_Status* status,
WebPluginInfo* plugin,
std::string* actual_mime_type,
scoped_ptr<PluginMetadata>* plugin_metadata) const {
bool allow_wildcard = true;
std::vector<WebPluginInfo> matching_plugins;
std::vector<std::string> mime_types;
PluginService::GetInstance()->GetPluginInfoArray(
url, mime_type, allow_wildcard, &matching_plugins, &mime_types);
if (matching_plugins.empty()) {
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kNotFound;
return false;
}
content::PluginServiceFilter* filter =
PluginService::GetInstance()->GetFilter();
size_t i = 0;
for (; i < matching_plugins.size(); ++i) {
if (!filter || filter->IsPluginAvailable(render_process_id_,
render_view_id,
resource_context_,
url,
top_origin_url,
&matching_plugins[i])) {
break;
}
}
bool enabled = i < matching_plugins.size();
if (!enabled) {
i = 0;
status->value = ChromeViewHostMsg_GetPluginInfo_Status::kDisabled;
}
*plugin = matching_plugins[i];
*actual_mime_type = mime_types[i];
if (plugin_metadata)
*plugin_metadata = PluginFinder::GetInstance()->GetPluginMetadata(*plugin);
return enabled;
}
| 171,471 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token,
policy::BrowserPolicyConnector::TokenType token_type) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
NOTREACHED() << "Cloud policy subsystem not initialized.";
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentOtherFailed,
policy::kMetricEnrollmentSize);
if (is_showing_)
actor_->ShowFatalEnrollmentError();
return;
}
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
connector->SetDeviceCredentials(user_, token, token_type);
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token,
policy::BrowserPolicyConnector::TokenType token_type) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
NOTREACHED() << "Cloud policy subsystem not initialized.";
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentOtherFailed,
policy::kMetricEnrollmentSize);
if (is_showing_)
actor_->ShowFatalEnrollmentError();
return;
}
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
connector->RegisterForDevicePolicy(user_, token, token_type);
}
| 170,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%') return;
switch(ctxt->instate) {
case XML_PARSER_CDATA_SECTION:
return;
case XML_PARSER_COMMENT:
return;
case XML_PARSER_START_TAG:
return;
case XML_PARSER_END_TAG:
return;
case XML_PARSER_EOF:
xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);
return;
case XML_PARSER_PROLOG:
case XML_PARSER_START:
case XML_PARSER_MISC:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL);
return;
case XML_PARSER_ENTITY_DECL:
case XML_PARSER_CONTENT:
case XML_PARSER_ATTRIBUTE_VALUE:
case XML_PARSER_PI:
case XML_PARSER_SYSTEM_LITERAL:
case XML_PARSER_PUBLIC_LITERAL:
/* we just ignore it there */
return;
case XML_PARSER_EPILOG:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL);
return;
case XML_PARSER_ENTITY_VALUE:
/*
* NOTE: in the case of entity values, we don't do the
* substitution here since we need the literal
* entity value to be able to save the internal
* subset of the document.
* This will be handled by xmlStringDecodeEntities
*/
return;
case XML_PARSER_DTD:
/*
* [WFC: Well-Formedness Constraint: PEs in Internal Subset]
* In the internal DTD subset, parameter-entity references
* can occur only where markup declarations can occur, not
* within markup declarations.
* In that case this is handled in xmlParseMarkupDecl
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
return;
if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0)
return;
break;
case XML_PARSER_IGNORE:
return;
}
NEXT;
name = xmlParseName(ctxt);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL);
} else {
if (RAW == ';') {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
(entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
* this is done independently.
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"PEReference: %s is not a parameter entity\n",
name);
}
}
} else {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
}
}
}
Commit Message: libxml: XML_PARSER_EOF checks from upstream
BUG=229019
TBR=cpu
Review URL: https://chromiumcodereview.appspot.com/14053009
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@196804 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) {
const xmlChar *name;
xmlEntityPtr entity = NULL;
xmlParserInputPtr input;
if (RAW != '%') return;
switch(ctxt->instate) {
case XML_PARSER_CDATA_SECTION:
return;
case XML_PARSER_COMMENT:
return;
case XML_PARSER_START_TAG:
return;
case XML_PARSER_END_TAG:
return;
case XML_PARSER_EOF:
xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL);
return;
case XML_PARSER_PROLOG:
case XML_PARSER_START:
case XML_PARSER_MISC:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL);
return;
case XML_PARSER_ENTITY_DECL:
case XML_PARSER_CONTENT:
case XML_PARSER_ATTRIBUTE_VALUE:
case XML_PARSER_PI:
case XML_PARSER_SYSTEM_LITERAL:
case XML_PARSER_PUBLIC_LITERAL:
/* we just ignore it there */
return;
case XML_PARSER_EPILOG:
xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL);
return;
case XML_PARSER_ENTITY_VALUE:
/*
* NOTE: in the case of entity values, we don't do the
* substitution here since we need the literal
* entity value to be able to save the internal
* subset of the document.
* This will be handled by xmlStringDecodeEntities
*/
return;
case XML_PARSER_DTD:
/*
* [WFC: Well-Formedness Constraint: PEs in Internal Subset]
* In the internal DTD subset, parameter-entity references
* can occur only where markup declarations can occur, not
* within markup declarations.
* In that case this is handled in xmlParseMarkupDecl
*/
if ((ctxt->external == 0) && (ctxt->inputNr == 1))
return;
if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0)
return;
break;
case XML_PARSER_IGNORE:
return;
}
NEXT;
name = xmlParseName(ctxt);
if (xmlParserDebugEntities)
xmlGenericError(xmlGenericErrorContext,
"PEReference: %s\n", name);
if (name == NULL) {
xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL);
} else {
if (RAW == ';') {
NEXT;
if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL))
entity = ctxt->sax->getParameterEntity(ctxt->userData, name);
if (ctxt->instate == XML_PARSER_EOF)
return;
if (entity == NULL) {
/*
* [ WFC: Entity Declared ]
* In a document without any DTD, a document with only an
* internal DTD subset which contains no parameter entity
* references, or a document with "standalone='yes'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->standalone == 1) ||
((ctxt->hasExternalSubset == 0) &&
(ctxt->hasPErefs == 0))) {
xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n", name);
} else {
/*
* [ VC: Entity Declared ]
* In a document with an external subset or external
* parameter entities with "standalone='no'", ...
* ... The declaration of a parameter entity must precede
* any reference to it...
*/
if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) {
xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
} else
xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY,
"PEReference: %%%s; not found\n",
name, NULL);
ctxt->valid = 0;
}
} else if (ctxt->input->free != deallocblankswrapper) {
input = xmlNewBlanksWrapperInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
} else {
if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) ||
(entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) {
xmlChar start[4];
xmlCharEncoding enc;
/*
* handle the extra spaces added before and after
* c.f. http://www.w3.org/TR/REC-xml#as-PE
* this is done independently.
*/
input = xmlNewEntityInputStream(ctxt, entity);
if (xmlPushInput(ctxt, input) < 0)
return;
/*
* Get the 4 first bytes and decode the charset
* if enc != XML_CHAR_ENCODING_NONE
* plug some encoding conversion routines.
* Note that, since we may have some non-UTF8
* encoding (like UTF16, bug 135229), the 'length'
* is not known, but we can calculate based upon
* the amount of data in the buffer.
*/
GROW
if (ctxt->instate == XML_PARSER_EOF)
return;
if ((ctxt->input->end - ctxt->input->cur)>=4) {
start[0] = RAW;
start[1] = NXT(1);
start[2] = NXT(2);
start[3] = NXT(3);
enc = xmlDetectCharEncoding(start, 4);
if (enc != XML_CHAR_ENCODING_NONE) {
xmlSwitchEncoding(ctxt, enc);
}
}
if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) &&
(CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) &&
(IS_BLANK_CH(NXT(5)))) {
xmlParseTextDecl(ctxt);
}
} else {
xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER,
"PEReference: %s is not a parameter entity\n",
name);
}
}
} else {
xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL);
}
}
}
| 171,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: StateBase* writeBlob(v8::Handle<v8::Value> value, StateBase* next)
{
Blob* blob = V8Blob::toNative(value.As<v8::Object>());
if (!blob)
return 0;
if (blob->hasBeenClosed())
return handleError(DataCloneError, "A Blob object has been closed, and could therefore not be cloned.", next);
int blobIndex = -1;
m_blobDataHandles.add(blob->uuid(), blob->blobDataHandle());
if (appendBlobInfo(blob->uuid(), blob->type(), blob->size(), &blobIndex))
m_writer.writeBlobIndex(blobIndex);
else
m_writer.writeBlob(blob->uuid(), blob->type(), blob->size());
return 0;
}
Commit Message: Replace further questionable HashMap::add usages in bindings
BUG=390928
[email protected]
Review URL: https://codereview.chromium.org/411273002
git-svn-id: svn://svn.chromium.org/blink/trunk@178823 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | StateBase* writeBlob(v8::Handle<v8::Value> value, StateBase* next)
{
Blob* blob = V8Blob::toNative(value.As<v8::Object>());
if (!blob)
return 0;
if (blob->hasBeenClosed())
return handleError(DataCloneError, "A Blob object has been closed, and could therefore not be cloned.", next);
int blobIndex = -1;
m_blobDataHandles.set(blob->uuid(), blob->blobDataHandle());
if (appendBlobInfo(blob->uuid(), blob->type(), blob->size(), &blobIndex))
m_writer.writeBlobIndex(blobIndex);
else
m_writer.writeBlob(blob->uuid(), blob->type(), blob->size());
return 0;
}
| 171,650 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info)
{
char
magick[MagickPathExtent];
ErrorManager
*error_manager;
ExceptionInfo
*exception;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*iptc_profile,
*profile;
/*
Determine length of binary data stored here.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Validate that this was written as a Photoshop resource format slug.
*/
for (i=0; i < 10; i++)
magick[i]=(char) GetCharacter(jpeg_info);
magick[10]='\0';
length-=10;
if (length <= 10)
return(TRUE);
if (LocaleCompare(magick,"Photoshop ") != 0)
{
/*
Not a IPTC profile, return.
*/
for (i=0; i < (ssize_t) length; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Remove the version number.
*/
for (i=0; i < 4; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
if (length <= 11)
return(TRUE);
length-=4;
error_manager=(ErrorManager *) jpeg_info->client_data;
exception=error_manager->exception;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=GetCharacter(jpeg_info);
if (c == EOF)
break;
*p++=(unsigned char) c;
}
error_manager->profile=NULL;
if (i != (ssize_t) length)
{
profile=DestroyStringInfo(profile);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"InsufficientImageDataInFile","`%s'",
image->filename);
return(FALSE);
}
/* The IPTC profile is actually an 8bim */
iptc_profile=(StringInfo *) GetImageProfile(image,"8bim");
if (iptc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(iptc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: iptc, %.20g bytes",(double) length);
return(TRUE);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/1641
CWE ID: | static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info)
{
char
magick[MagickPathExtent];
ErrorManager
*error_manager;
ExceptionInfo
*exception;
Image
*image;
MagickBooleanType
status;
register ssize_t
i;
register unsigned char
*p;
size_t
length;
StringInfo
*iptc_profile,
*profile;
/*
Determine length of binary data stored here.
*/
length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8);
length+=(size_t) GetCharacter(jpeg_info);
length-=2;
if (length <= 14)
{
while (length-- > 0)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Validate that this was written as a Photoshop resource format slug.
*/
for (i=0; i < 10; i++)
magick[i]=(char) GetCharacter(jpeg_info);
magick[10]='\0';
length-=10;
if (length <= 10)
return(TRUE);
if (LocaleCompare(magick,"Photoshop ") != 0)
{
/*
Not a IPTC profile, return.
*/
for (i=0; i < (ssize_t) length; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
return(TRUE);
}
/*
Remove the version number.
*/
for (i=0; i < 4; i++)
if (GetCharacter(jpeg_info) == EOF)
break;
if (length <= 11)
return(TRUE);
length-=4;
error_manager=(ErrorManager *) jpeg_info->client_data;
exception=error_manager->exception;
image=error_manager->image;
profile=BlobToStringInfo((const void *) NULL,length);
if (profile == (StringInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
error_manager->profile=profile;
p=GetStringInfoDatum(profile);
for (i=0; i < (ssize_t) length; i++)
{
int
c;
c=GetCharacter(jpeg_info);
if (c == EOF)
break;
*p++=(unsigned char) c;
}
error_manager->profile=NULL;
if (i != (ssize_t) length)
{
profile=DestroyStringInfo(profile);
(void) ThrowMagickException(exception,GetMagickModule(),
CorruptImageError,"InsufficientImageDataInFile","`%s'",
image->filename);
return(FALSE);
}
/*
The IPTC profile is actually an 8bim.
*/
iptc_profile=(StringInfo *) GetImageProfile(image,"8bim");
if (iptc_profile != (StringInfo *) NULL)
{
ConcatenateStringInfo(iptc_profile,profile);
profile=DestroyStringInfo(profile);
}
else
{
status=SetImageProfile(image,"8bim",profile,exception);
profile=DestroyStringInfo(profile);
if (status == MagickFalse)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(FALSE);
}
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"Profile: iptc, %.20g bytes",(double) length);
return(TRUE);
}
| 169,488 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
int i, j, jidx;
/* volatile so we can gdFree it on return from longjmp */
volatile JSAMPROW row = 0;
JSAMPROW rowptr[1];
jmpbuf_wrapper jmpbufw;
JDIMENSION nlines;
char comment[255];
memset (&cinfo, 0, sizeof (cinfo));
memset (&jerr, 0, sizeof (jerr));
cinfo.err = jpeg_std_error (&jerr);
cinfo.client_data = &jmpbufw;
if (setjmp (jmpbufw.jmpbuf) != 0) {
/* we're here courtesy of longjmp */
if (row) {
gdFree (row);
}
return;
}
cinfo.err->error_exit = fatal_jpeg_error;
jpeg_create_compress (&cinfo);
cinfo.image_width = im->sx;
cinfo.image_height = im->sy;
cinfo.input_components = 3; /* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
jpeg_set_defaults (&cinfo);
cinfo.density_unit = 1;
cinfo.X_density = im->res_x;
cinfo.Y_density = im->res_y;
if (quality >= 0) {
jpeg_set_quality (&cinfo, quality, TRUE);
}
/* If user requests interlace, translate that to progressive JPEG */
if (gdImageGetInterlaced (im)) {
jpeg_simple_progression (&cinfo);
}
jpeg_gdIOCtx_dest (&cinfo, outfile);
row = (JSAMPROW) safe_emalloc(cinfo.image_width * cinfo.input_components, sizeof(JSAMPLE), 0);
memset(row, 0, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE));
rowptr[0] = row;
jpeg_start_compress (&cinfo, TRUE);
if (quality >= 0) {
snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), quality = %d\n", GD_JPEG_VERSION, JPEG_LIB_VERSION, quality);
} else {
snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), default quality\n", GD_JPEG_VERSION, JPEG_LIB_VERSION);
}
jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int) strlen (comment));
if (im->trueColor) {
#if BITS_IN_JSAMPLE == 12
gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry");
goto error;
#endif /* BITS_IN_JSAMPLE == 12 */
for (i = 0; i < im->sy; i++) {
for (jidx = 0, j = 0; j < im->sx; j++) {
int val = im->tpixels[i][j];
row[jidx++] = gdTrueColorGetRed (val);
row[jidx++] = gdTrueColorGetGreen (val);
row[jidx++] = gdTrueColorGetBlue (val);
}
nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
if (nlines != 1) {
gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines);
}
}
} else {
for (i = 0; i < im->sy; i++) {
for (jidx = 0, j = 0; j < im->sx; j++) {
int idx = im->pixels[i][j];
/* NB: Although gd RGB values are ints, their max value is
* 255 (see the documentation for gdImageColorAllocate())
* -- perfect for 8-bit JPEG encoding (which is the norm)
*/
#if BITS_IN_JSAMPLE == 8
row[jidx++] = im->red[idx];
row[jidx++] = im->green[idx];
row[jidx++] = im->blue[idx];
#elif BITS_IN_JSAMPLE == 12
row[jidx++] = im->red[idx] << 4;
row[jidx++] = im->green[idx] << 4;
row[jidx++] = im->blue[idx] << 4;
#else
#error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12
#endif
}
nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
if (nlines != 1) {
gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines);
}
}
}
jpeg_finish_compress (&cinfo);
jpeg_destroy_compress (&cinfo);
gdFree (row);
}
Commit Message: Sync with upstream
Even though libgd/libgd#492 is not a relevant bug fix for PHP, since
the binding doesn't use the `gdImage*Ptr()` functions at all, we're
porting the fix to stay in sync here.
CWE ID: CWE-415 | void gdImageJpegCtx (gdImagePtr im, gdIOCtx * outfile, int quality)
{
_gdImageJpegCtx(im, outfile, quality);
}
/* returns 0 on success, 1 on failure */
static int _gdImageJpegCtx(gdImagePtr im, gdIOCtx *outfile, int quality)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
int i, j, jidx;
/* volatile so we can gdFree it on return from longjmp */
volatile JSAMPROW row = 0;
JSAMPROW rowptr[1];
jmpbuf_wrapper jmpbufw;
JDIMENSION nlines;
char comment[255];
memset (&cinfo, 0, sizeof (cinfo));
memset (&jerr, 0, sizeof (jerr));
cinfo.err = jpeg_std_error (&jerr);
cinfo.client_data = &jmpbufw;
if (setjmp (jmpbufw.jmpbuf) != 0) {
/* we're here courtesy of longjmp */
if (row) {
gdFree (row);
}
return 1;
}
cinfo.err->error_exit = fatal_jpeg_error;
jpeg_create_compress (&cinfo);
cinfo.image_width = im->sx;
cinfo.image_height = im->sy;
cinfo.input_components = 3; /* # of color components per pixel */
cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
jpeg_set_defaults (&cinfo);
cinfo.density_unit = 1;
cinfo.X_density = im->res_x;
cinfo.Y_density = im->res_y;
if (quality >= 0) {
jpeg_set_quality (&cinfo, quality, TRUE);
}
/* If user requests interlace, translate that to progressive JPEG */
if (gdImageGetInterlaced (im)) {
jpeg_simple_progression (&cinfo);
}
jpeg_gdIOCtx_dest (&cinfo, outfile);
row = (JSAMPROW) safe_emalloc(cinfo.image_width * cinfo.input_components, sizeof(JSAMPLE), 0);
memset(row, 0, cinfo.image_width * cinfo.input_components * sizeof(JSAMPLE));
rowptr[0] = row;
jpeg_start_compress (&cinfo, TRUE);
if (quality >= 0) {
snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), quality = %d\n", GD_JPEG_VERSION, JPEG_LIB_VERSION, quality);
} else {
snprintf(comment, sizeof(comment)-1, "CREATOR: gd-jpeg v%s (using IJG JPEG v%d), default quality\n", GD_JPEG_VERSION, JPEG_LIB_VERSION);
}
jpeg_write_marker (&cinfo, JPEG_COM, (unsigned char *) comment, (unsigned int) strlen (comment));
if (im->trueColor) {
#if BITS_IN_JSAMPLE == 12
gd_error("gd-jpeg: error: jpeg library was compiled for 12-bit precision. This is mostly useless, because JPEGs on the web are 8-bit and such versions of the jpeg library won't read or write them. GD doesn't support these unusual images. Edit your jmorecfg.h file to specify the correct precision and completely 'make clean' and 'make install' libjpeg again. Sorry");
goto error;
#endif /* BITS_IN_JSAMPLE == 12 */
for (i = 0; i < im->sy; i++) {
for (jidx = 0, j = 0; j < im->sx; j++) {
int val = im->tpixels[i][j];
row[jidx++] = gdTrueColorGetRed (val);
row[jidx++] = gdTrueColorGetGreen (val);
row[jidx++] = gdTrueColorGetBlue (val);
}
nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
if (nlines != 1) {
gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines);
}
}
} else {
for (i = 0; i < im->sy; i++) {
for (jidx = 0, j = 0; j < im->sx; j++) {
int idx = im->pixels[i][j];
/* NB: Although gd RGB values are ints, their max value is
* 255 (see the documentation for gdImageColorAllocate())
* -- perfect for 8-bit JPEG encoding (which is the norm)
*/
#if BITS_IN_JSAMPLE == 8
row[jidx++] = im->red[idx];
row[jidx++] = im->green[idx];
row[jidx++] = im->blue[idx];
#elif BITS_IN_JSAMPLE == 12
row[jidx++] = im->red[idx] << 4;
row[jidx++] = im->green[idx] << 4;
row[jidx++] = im->blue[idx] << 4;
#else
#error IJG JPEG library BITS_IN_JSAMPLE value must be 8 or 12
#endif
}
nlines = jpeg_write_scanlines (&cinfo, rowptr, 1);
if (nlines != 1) {
gd_error_ex(GD_WARNING, "gd_jpeg: warning: jpeg_write_scanlines returns %u -- expected 1", nlines);
}
}
}
jpeg_finish_compress (&cinfo);
jpeg_destroy_compress (&cinfo);
gdFree (row);
return 0;
}
| 169,735 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
Commit Message: CVE-2017-13038/PPP: Do bounds checking.
This fixes a buffer over-read discovered by Brian 'geeknik' Carpenter.
Add a test using the capture file supplied by Katie Holly.
CWE ID: CWE-125 | handle_mlppp(netdissect_options *ndo,
const u_char *p, int length)
{
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "MLPPP, "));
if (length < 2) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
if (!ND_TTEST_16BITS(p)) {
ND_PRINT((ndo, "[|mlppp]"));
return;
}
ND_PRINT((ndo, "seq 0x%03x, Flags [%s], length %u",
(EXTRACT_16BITS(p))&0x0fff, /* only support 12-Bit sequence space for now */
bittok2str(ppp_ml_flag_values, "none", *p & 0xc0),
length));
}
| 167,844 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PHP_MINIT_FUNCTION(spl_directory)
{
REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions);
memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone;
spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast;
spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info;
spl_ce_SplFileInfo->serialize = zend_class_serialize_deny;
spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny;
REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions);
zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator);
REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator);
spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS);
spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions);
REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator);
memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers));
spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check;
#ifdef HAVE_GLOB
REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions);
REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable);
#endif
REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions);
REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator);
REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV);
REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions);
return SUCCESS;
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | PHP_MINIT_FUNCTION(spl_directory)
{
REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions);
memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone;
spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast;
spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info;
spl_ce_SplFileInfo->serialize = zend_class_serialize_deny;
spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny;
REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions);
zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator);
REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator);
spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS);
REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS);
spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator;
REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions);
REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator);
memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers));
spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check;
#ifdef HAVE_GLOB
REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions);
REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable);
#endif
REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions);
REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator);
REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY);
REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV);
REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions);
return SUCCESS;
}
| 167,026 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct ipv6_txoptions *ipv6_update_options(struct sock *sk,
struct ipv6_txoptions *opt)
{
if (inet_sk(sk)->is_icsk) {
if (opt &&
!((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) &&
inet_sk(sk)->inet_daddr != LOOPBACK4_IPV6) {
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
}
}
opt = xchg(&inet6_sk(sk)->opt, opt);
sk_dst_reset(sk);
return opt;
}
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 | struct ipv6_txoptions *ipv6_update_options(struct sock *sk,
struct ipv6_txoptions *opt)
{
if (inet_sk(sk)->is_icsk) {
if (opt &&
!((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) &&
inet_sk(sk)->inet_daddr != LOOPBACK4_IPV6) {
struct inet_connection_sock *icsk = inet_csk(sk);
icsk->icsk_ext_hdr_len = opt->opt_flen + opt->opt_nflen;
icsk->icsk_sync_mss(sk, icsk->icsk_pmtu_cookie);
}
}
opt = xchg((__force struct ipv6_txoptions **)&inet6_sk(sk)->opt,
opt);
sk_dst_reset(sk);
return opt;
}
| 167,337 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GURL SanitizeFrontendURL(const GURL& url,
const std::string& scheme,
const std::string& host,
const std::string& path,
bool allow_query_and_fragment) {
std::vector<std::string> query_parts;
std::string fragment;
if (allow_query_and_fragment) {
for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
std::string value = SanitizeFrontendQueryParam(it.GetKey(),
it.GetValue());
if (!value.empty()) {
query_parts.push_back(
base::StringPrintf("%s=%s", it.GetKey().c_str(), value.c_str()));
}
}
if (url.has_ref())
fragment = '#' + url.ref();
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
std::string constructed =
base::StringPrintf("%s://%s%s%s%s", scheme.c_str(), host.c_str(),
path.c_str(), query.c_str(), fragment.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
return result;
}
Commit Message: Improve sanitization of remoteFrontendUrl in DevTools
This change ensures that the decoded remoteFrontendUrl parameter cannot
contain any single quote in its value. As of this commit, none of the
permitted query params in SanitizeFrontendQueryParam can contain single
quotes.
Note that the existing SanitizeEndpoint function does not explicitly
check for single quotes. This is fine since single quotes in the query
string are already URL-encoded and the values validated by
SanitizeEndpoint are not url-decoded elsewhere.
BUG=798163
TEST=Manually, see https://crbug.com/798163#c1
TEST=./unit_tests --gtest_filter=DevToolsUIBindingsTest.SanitizeFrontendURL
Change-Id: I5a08e8ce6f1abc2c8d2a0983fef63e1e194cd242
Reviewed-on: https://chromium-review.googlesource.com/846979
Reviewed-by: Dmitry Gozman <[email protected]>
Commit-Queue: Rob Wu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#527250}
CWE ID: CWE-20 | GURL SanitizeFrontendURL(const GURL& url,
const std::string& scheme,
const std::string& host,
const std::string& path,
bool allow_query_and_fragment) {
std::vector<std::string> query_parts;
std::string fragment;
if (allow_query_and_fragment) {
for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) {
std::string value = SanitizeFrontendQueryParam(it.GetKey(),
it.GetValue());
if (!value.empty()) {
query_parts.push_back(
base::StringPrintf("%s=%s", it.GetKey().c_str(), value.c_str()));
}
}
if (url.has_ref() && url.ref_piece().find('\'') == base::StringPiece::npos)
fragment = '#' + url.ref();
}
std::string query =
query_parts.empty() ? "" : "?" + base::JoinString(query_parts, "&");
std::string constructed =
base::StringPrintf("%s://%s%s%s%s", scheme.c_str(), host.c_str(),
path.c_str(), query.c_str(), fragment.c_str());
GURL result = GURL(constructed);
if (!result.is_valid())
return GURL();
return result;
}
| 172,689 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_mb_regex_free_cache(php_mb_regex_t **pre)
{
onig_free(*pre);
}
Commit Message: Fix bug #72402: _php_mb_regex_ereg_replace_exec - double free
CWE ID: CWE-415 | static void php_mb_regex_free_cache(php_mb_regex_t **pre)
static void php_mb_regex_free_cache(php_mb_regex_t **pre)
{
onig_free(*pre);
}
| 167,122 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AppCacheDatabase::FindCacheForGroup(int64_t group_id,
CacheRecord* record) {
DCHECK(record);
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, group_id, online_wildcard, update_time, cache_size"
" FROM Caches WHERE group_id = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, group_id);
if (!statement.Step())
return false;
ReadCacheRecord(statement, record);
return true;
}
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 | bool AppCacheDatabase::FindCacheForGroup(int64_t group_id,
CacheRecord* record) {
DCHECK(record);
if (!LazyOpen(kDontCreate))
return false;
static const char kSql[] =
"SELECT cache_id, group_id, online_wildcard, update_time, cache_size, "
"padding_size"
" FROM Caches WHERE group_id = ?";
sql::Statement statement(db_->GetCachedStatement(SQL_FROM_HERE, kSql));
statement.BindInt64(0, group_id);
if (!statement.Step())
return false;
ReadCacheRecord(statement, record);
return true;
}
| 172,974 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static struct dentry *proc_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int err;
struct super_block *sb;
struct pid_namespace *ns;
char *options;
if (flags & MS_KERNMOUNT) {
ns = (struct pid_namespace *)data;
options = NULL;
} else {
ns = task_active_pid_ns(current);
options = data;
/* Does the mounter have privilege over the pid namespace? */
if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
return ERR_PTR(-EPERM);
}
sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns);
if (IS_ERR(sb))
return ERR_CAST(sb);
if (!proc_parse_options(options, ns)) {
deactivate_locked_super(sb);
return ERR_PTR(-EINVAL);
}
if (!sb->s_root) {
err = proc_fill_super(sb);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
/* User space would break if executables appear on proc */
sb->s_iflags |= SB_I_NOEXEC;
}
return dget(sb->s_root);
}
Commit Message: Merge branch 'stacking-fixes' (vfs stacking fixes from Jann)
Merge filesystem stacking fixes from Jann Horn.
* emailed patches from Jann Horn <[email protected]>:
sched: panic on corrupted stack end
ecryptfs: forbid opening files without mmap handler
proc: prevent stacking filesystems on top
CWE ID: CWE-119 | static struct dentry *proc_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int err;
struct super_block *sb;
struct pid_namespace *ns;
char *options;
if (flags & MS_KERNMOUNT) {
ns = (struct pid_namespace *)data;
options = NULL;
} else {
ns = task_active_pid_ns(current);
options = data;
/* Does the mounter have privilege over the pid namespace? */
if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN))
return ERR_PTR(-EPERM);
}
sb = sget(fs_type, proc_test_super, proc_set_super, flags, ns);
if (IS_ERR(sb))
return ERR_CAST(sb);
/*
* procfs isn't actually a stacking filesystem; however, there is
* too much magic going on inside it to permit stacking things on
* top of it
*/
sb->s_stack_depth = FILESYSTEM_MAX_STACK_DEPTH;
if (!proc_parse_options(options, ns)) {
deactivate_locked_super(sb);
return ERR_PTR(-EINVAL);
}
if (!sb->s_root) {
err = proc_fill_super(sb);
if (err) {
deactivate_locked_super(sb);
return ERR_PTR(err);
}
sb->s_flags |= MS_ACTIVE;
/* User space would break if executables appear on proc */
sb->s_iflags |= SB_I_NOEXEC;
}
return dget(sb->s_root);
}
| 167,444 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RenderFrameHostImpl::ResetFeaturePolicy() {
RenderFrameHostImpl* parent_frame_host = GetParent();
const FeaturePolicy* parent_policy =
parent_frame_host ? parent_frame_host->get_feature_policy() : nullptr;
ParsedFeaturePolicyHeader container_policy =
frame_tree_node()->effective_container_policy();
feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
parent_policy, container_policy, last_committed_origin_);
}
Commit Message: Correctly reset FP in RFHI whenever origin changes
Bug: 713364
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Change-Id: Id8bb923750e20f3db6fc9358b1d44120513ac95f
Reviewed-on: https://chromium-review.googlesource.com/482380
Commit-Queue: Ian Clelland <[email protected]>
Reviewed-by: Charles Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#466778}
CWE ID: CWE-254 | void RenderFrameHostImpl::ResetFeaturePolicy() {
RenderFrameHostImpl* parent_frame_host = GetParent();
const FeaturePolicy* parent_policy =
parent_frame_host ? parent_frame_host->feature_policy() : nullptr;
ParsedFeaturePolicyHeader container_policy =
frame_tree_node()->effective_container_policy();
feature_policy_ = FeaturePolicy::CreateFromParentPolicy(
parent_policy, container_policy, last_committed_origin_);
}
| 171,964 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PreresolveJob::PreresolveJob(PreconnectRequest preconnect_request,
PreresolveInfo* info)
: url(std::move(preconnect_request.origin)),
num_sockets(preconnect_request.num_sockets),
allow_credentials(preconnect_request.allow_credentials),
network_isolation_key(
std::move(preconnect_request.network_isolation_key)),
info(info) {
DCHECK_GE(num_sockets, 0);
}
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 | PreresolveJob::PreresolveJob(PreconnectRequest preconnect_request,
PreresolveInfo* info)
: url(preconnect_request.origin.GetURL()),
num_sockets(preconnect_request.num_sockets),
allow_credentials(preconnect_request.allow_credentials),
network_isolation_key(
std::move(preconnect_request.network_isolation_key)),
info(info) {
DCHECK_GE(num_sockets, 0);
}
| 172,376 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.